repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Cleverdesk/cleverdesk
src/main/java/net/cleverdesk/cleverdesk/ui/form/InputField.kt
1
1021
/** * 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 net.cleverdesk.cleverdesk.ui.form import net.cleverdesk.cleverdesk.ui.Action class InputField() : AbstractInputField<String>() { override val name: String = "InputField" var type: String = "text" public var onClickAction: Action? = null public var max: Int? = null public var validation_pattern: ValidationPatter? = null }
gpl-3.0
34d26b68debc8155f2597aaca8659df9
31.935484
72
0.727718
4.201646
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/TimelineContentTextView.kt
1
4475
/* * 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.view import android.annotation.SuppressLint import android.content.Context import android.text.Spannable import android.text.method.BaseMovementMethod import android.text.method.MovementMethod import android.text.style.ClickableSpan import android.util.AttributeSet import android.view.MotionEvent import android.widget.TextView import org.mariotaku.chameleon.view.ChameleonTextView import de.vanita5.twittnuker.extension.setupEmojiFactory import java.lang.ref.WeakReference /** * Returns true when not clicking links * Created by mariotaku on 15/11/20. */ class TimelineContentTextView( context: Context, attrs: AttributeSet? = null ) : ChameleonTextView(context, attrs) { init { setupEmojiFactory() } override fun dispatchTouchEvent(event: MotionEvent): Boolean { // FIXME simple workaround to https://code.google.com/p/android/issues/detail?id=191430 // Android clears TextView when setText(), so setText before touch if (event.actionMasked == MotionEvent.ACTION_DOWN && isTextSelectable) { if (selectionEnd != selectionStart) { val text = text setText(null) setText(text) } } return super.dispatchTouchEvent(event) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { if (isTextSelectable) { return super.onTouchEvent(event) } return super.onTouchEvent(event) } override fun getDefaultMovementMethod(): MovementMethod { return InternalMovementMethod() } override fun setClickable(clickable: Boolean) { super.setClickable(clickable && isTextSelectable) } override fun setLongClickable(longClickable: Boolean) { super.setLongClickable(longClickable && isTextSelectable) } override fun onTextContextMenuItem(id: Int): Boolean { try { return super.onTextContextMenuItem(id) } catch (e: AbstractMethodError) { // http://crashes.to/s/69acd0ea0de return true } } internal class InternalMovementMethod : BaseMovementMethod() { private var targetSpan: WeakReference<ClickableSpan?>? = null override fun canSelectArbitrarily() = true override fun onTouchEvent(widget: TextView, text: Spannable, event: MotionEvent): Boolean { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { val layout = widget.layout val x = event.x - widget.paddingLeft + widget.scrollX val y = event.y - widget.paddingTop + widget.scrollY val line = layout.getLineForVertical(Math.round(y)) val offset = layout.getOffsetForHorizontal(line, x) if (x <= layout.getLineWidth(line)) { targetSpan = WeakReference(text.getSpans(offset, offset, ClickableSpan::class.java).firstOrNull()) } else { targetSpan = null } } MotionEvent.ACTION_UP -> { val span = targetSpan?.get() ?: return false span.onClick(widget) targetSpan = null return true } MotionEvent.ACTION_CANCEL -> { targetSpan = null } } return targetSpan?.get() != null } } }
gpl-3.0
2364fd41dc9aaa490edbabfa5f006736
34.52381
122
0.637989
4.922992
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/feed/view/CardLargeHeaderView.kt
1
3836
package org.wikipedia.feed.view import android.content.Context import android.graphics.drawable.GradientDrawable import android.net.Uri import android.util.AttributeSet import android.view.LayoutInflater import androidx.annotation.ColorInt import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.palette.graphics.Palette import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.databinding.ViewCardHeaderLargeBinding import org.wikipedia.util.L10nUtil import org.wikipedia.util.ResourceUtil import org.wikipedia.util.StringUtil import org.wikipedia.util.TransitionUtil import org.wikipedia.views.FaceAndColorDetectImageView.OnImageLoadListener class CardLargeHeaderView : ConstraintLayout { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) val binding = ViewCardHeaderLargeBinding.inflate(LayoutInflater.from(context), this) init { resetBackgroundColor() } val sharedElements = TransitionUtil.getSharedElements(context, binding.viewCardHeaderLargeImage) fun setLanguageCode(langCode: String): CardLargeHeaderView { L10nUtil.setConditionalLayoutDirection(this, langCode) return this } fun setImage(uri: Uri?): CardLargeHeaderView { binding.viewCardHeaderLargeImage.visibility = if (uri == null) GONE else VISIBLE binding.viewCardHeaderLargeImage.loadImage(uri, roundedCorners = true, cropped = true, listener = ImageLoadListener()) return this } fun setTitle(title: String?): CardLargeHeaderView { binding.viewCardHeaderLargeTitle.text = StringUtil.fromHtml(title) return this } fun setSubtitle(subtitle: CharSequence?): CardLargeHeaderView { binding.viewCardHeaderLargeSubtitle.text = subtitle return this } private fun resetBackgroundColor() { setGradientDrawableBackground(ContextCompat.getColor(context, R.color.base100), ContextCompat.getColor(context, R.color.base20)) } private inner class ImageLoadListener : OnImageLoadListener { override fun onImageLoaded(palette: Palette, bmpWidth: Int, bmpHeight: Int) { var color1 = palette.getLightVibrantColor(ContextCompat.getColor(context, R.color.base70)) var color2 = palette.getLightMutedColor(ContextCompat.getColor(context, R.color.base30)) if (WikipediaApp.instance.currentTheme.isDark) { color1 = ResourceUtil.darkenColor(color1) color2 = ResourceUtil.darkenColor(color2) } else { color1 = ResourceUtil.lightenColor(color1) color2 = ResourceUtil.lightenColor(color2) } setGradientDrawableBackground(color1, color2) } override fun onImageFailed() { resetBackgroundColor() } } private fun setGradientDrawableBackground(@ColorInt leftColor: Int, @ColorInt rightColor: Int) { val gradientDrawable = GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, intArrayOf(leftColor, rightColor)) // card background gradientDrawable.alpha = 70 gradientDrawable.cornerRadius = binding.viewCardHeaderLargeBorderBase.radius binding.viewCardHeaderLargeContainer.background = gradientDrawable // card border's background, which depends on the margin that is applied to the borderBaseView gradientDrawable.alpha = 90 gradientDrawable.cornerRadius = resources.getDimension(R.dimen.wiki_card_radius) binding.viewCardHeaderLargeBorderContainer.background = gradientDrawable } }
apache-2.0
d1e0f7b0402dc74a0876f2c818ab8d98
40.695652
126
0.740094
5.09429
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/content/TwidereSQLiteOpenHelper.kt
1
16870
/* * 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.util.content import android.accounts.AccountManager import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.os.Build import org.mariotaku.kpreferences.get import org.mariotaku.library.objectcursor.ObjectCursor import org.mariotaku.sqliteqb.library.* import org.mariotaku.sqliteqb.library.Columns.Column import org.mariotaku.sqliteqb.library.query.SQLCreateTriggerQuery.Event import org.mariotaku.sqliteqb.library.query.SQLCreateTriggerQuery.Type import de.vanita5.twittnuker.TwittnukerConstants.SHARED_PREFERENCES_NAME import de.vanita5.twittnuker.annotation.CustomTabType import de.vanita5.twittnuker.constant.defaultAPIConfigKey import de.vanita5.twittnuker.model.Tab import de.vanita5.twittnuker.model.tab.TabConfiguration import de.vanita5.twittnuker.provider.TwidereDataStore.* import de.vanita5.twittnuker.provider.TwidereDataStore.Messages.Conversations import de.vanita5.twittnuker.util.content.DatabaseUpgradeHelper.safeUpgrade import de.vanita5.twittnuker.util.migrateAccounts import java.util.* class TwidereSQLiteOpenHelper( private val context: Context, name: String, version: Int ) : SQLiteOpenHelper(context, name, null, version) { override fun onCreate(db: SQLiteDatabase) { db.beginTransaction() db.execSQL(createTable(Statuses.TABLE_NAME, Statuses.COLUMNS, Statuses.TYPES, true)) db.execSQL(createTable(Activities.AboutMe.TABLE_NAME, Activities.AboutMe.COLUMNS, Activities.AboutMe.TYPES, true)) db.execSQL(createTable(Drafts.TABLE_NAME, Drafts.COLUMNS, Drafts.TYPES, true)) db.setTransactionSuccessful() db.endTransaction() db.beginTransaction() db.execSQL(createTable(CachedUsers.TABLE_NAME, CachedUsers.COLUMNS, CachedUsers.TYPES, true, createConflictReplaceConstraint(CachedUsers.USER_KEY))) db.execSQL(createTable(CachedStatuses.TABLE_NAME, CachedStatuses.COLUMNS, CachedStatuses.TYPES, true)) db.execSQL(createTable(CachedTrends.Local.TABLE_NAME, CachedTrends.Local.COLUMNS, CachedTrends.Local.TYPES, true)) db.execSQL(createTable(CachedHashtags.TABLE_NAME, CachedHashtags.COLUMNS, CachedHashtags.TYPES, true)) db.execSQL(createTable(CachedRelationships.TABLE_NAME, CachedRelationships.COLUMNS, CachedRelationships.TYPES, true, createConflictReplaceConstraint(CachedRelationships.ACCOUNT_KEY, CachedRelationships.USER_KEY))) db.setTransactionSuccessful() db.endTransaction() db.beginTransaction() db.execSQL(createTable(Filters.Users.TABLE_NAME, Filters.Users.COLUMNS, Filters.Users.TYPES, true)) db.execSQL(createTable(Filters.Keywords.TABLE_NAME, Filters.Keywords.COLUMNS, Filters.Keywords.TYPES, true)) db.execSQL(createTable(Filters.Sources.TABLE_NAME, Filters.Sources.COLUMNS, Filters.Sources.TYPES, true)) db.execSQL(createTable(Filters.Links.TABLE_NAME, Filters.Links.COLUMNS, Filters.Links.TYPES, true)) db.execSQL(createTable(Filters.Subscriptions.TABLE_NAME, Filters.Subscriptions.COLUMNS, Filters.Subscriptions.TYPES, true)) db.setTransactionSuccessful() db.endTransaction() db.beginTransaction() db.execSQL(createTable(Messages.TABLE_NAME, Messages.COLUMNS, Messages.TYPES, true, messagesConstraint())) db.execSQL(createTable(Conversations.TABLE_NAME, Conversations.COLUMNS, Conversations.TYPES, true, messageConversationsConstraint())) db.setTransactionSuccessful() db.endTransaction() db.beginTransaction() db.execSQL(createTable(Tabs.TABLE_NAME, Tabs.COLUMNS, Tabs.TYPES, true)) db.execSQL(createTable(SavedSearches.TABLE_NAME, SavedSearches.COLUMNS, SavedSearches.TYPES, true)) db.execSQL(createTable(SearchHistory.TABLE_NAME, SearchHistory.COLUMNS, SearchHistory.TYPES, true)) db.execSQL(createTable(PushNotifications.TABLE_NAME, PushNotifications.COLUMNS, PushNotifications.TYPES, true)) db.setTransactionSuccessful() db.endTransaction() db.beginTransaction() createTriggers(db) createIndices(db) db.setTransactionSuccessful() db.endTransaction() setupDefaultTabs(db) } private fun setupDefaultTabs(db: SQLiteDatabase) { val creator = ObjectCursor.valuesCreatorFrom(Tab::class.java) db.beginTransaction() @CustomTabType val tabTypes = arrayOf(CustomTabType.HOME_TIMELINE, CustomTabType.NOTIFICATIONS_TIMELINE, CustomTabType.DIRECT_MESSAGES, CustomTabType.TRENDS_SUGGESTIONS) for (i in 0 until tabTypes.size) { @CustomTabType val tabType = tabTypes[i] val conf = TabConfiguration.ofType(tabType) ?: continue val tab = Tab().apply { this.type = tabType this.icon = conf.icon.persistentKey this.position = i } db.insert(Tabs.TABLE_NAME, null, creator.create(tab)) } db.setTransactionSuccessful() db.endTransaction() } private fun createConflictReplaceConstraint(vararg columns: String): Constraint { return Constraint.unique(Columns(*columns), OnConflict.IGNORE) } private fun createIndices(db: SQLiteDatabase) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return db.execSQL(createIndex("statuses_index", Statuses.TABLE_NAME, arrayOf(Statuses.ACCOUNT_KEY), true)) } private fun createTriggers(db: SQLiteDatabase) { db.execSQL(SQLQueryBuilder.dropTrigger(true, "delete_old_statuses").sql) db.execSQL(SQLQueryBuilder.dropTrigger(true, "delete_old_cached_statuses").sql) db.execSQL(SQLQueryBuilder.dropTrigger(true, "on_user_cache_update_trigger").sql) db.execSQL(SQLQueryBuilder.dropTrigger(true, "delete_old_cached_hashtags").sql) db.execSQL(createDeleteDuplicateStatusTrigger("delete_old_statuses", Statuses.TABLE_NAME).sql) db.execSQL(createDeleteDuplicateStatusTrigger("delete_old_cached_statuses", CachedStatuses.TABLE_NAME).sql) // Update user info in filtered users val cachedUsersTable = Table(CachedUsers.TABLE_NAME) val filteredUsersTable = Table(Filters.Users.TABLE_NAME) db.execSQL(SQLQueryBuilder.createTrigger(false, true, "on_user_cache_update_trigger") .type(Type.BEFORE) .event(Event.INSERT) .on(cachedUsersTable) .forEachRow(true) .actions(SQLQueryBuilder.update(OnConflict.REPLACE, filteredUsersTable) .set(SetValue(Column(Filters.Users.NAME), Column(Table.NEW, CachedUsers.NAME)), SetValue(Column(Filters.Users.SCREEN_NAME), Column(Table.NEW, CachedUsers.SCREEN_NAME))) .where(Expression.equals(Column(Filters.Users.USER_KEY), Column(Table.NEW, CachedUsers.USER_KEY))) .build()) .buildSQL()) // Delete duplicated hashtags ignoring case val cachedHashtagsTable = Table(CachedHashtags.TABLE_NAME) db.execSQL(SQLQueryBuilder.createTrigger(false, true, "delete_old_cached_hashtags") .type(Type.BEFORE) .event(Event.INSERT) .on(cachedHashtagsTable) .forEachRow(true) .actions(SQLQueryBuilder.deleteFrom(cachedHashtagsTable) .where(Expression.like(Column(CachedHashtags.NAME), Column(Table.NEW, CachedHashtags.NAME))) .build()) .buildSQL()) } private fun createDeleteDuplicateStatusTrigger(triggerName: String, tableName: String): SQLQuery { val table = Table(tableName) val deleteOld = SQLQueryBuilder.deleteFrom(table).where(Expression.and( Expression.equals(Column(Statuses.ACCOUNT_KEY), Column(Table.NEW, Statuses.ACCOUNT_KEY)), Expression.equals(Column(Statuses.ID), Column(Table.NEW, Statuses.ID)) )).build() return SQLQueryBuilder.createTrigger(false, true, triggerName) .type(Type.BEFORE).event(Event.INSERT).on(table).forEachRow(true) .actions(deleteOld).build() } override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { handleVersionChange(db, oldVersion, newVersion) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { handleVersionChange(db, oldVersion, newVersion) if (oldVersion <= 43 && newVersion >= 44 && newVersion <= 153) { val values = ContentValues() val prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE) // Here I use old consumer key/secret because it's default key for // older versions val defaultAPIConfig = prefs[defaultAPIConfigKey] values.put(Accounts.CONSUMER_KEY, defaultAPIConfig.consumerKey) values.put(Accounts.CONSUMER_SECRET, defaultAPIConfig.consumerSecret) db.update(Accounts.TABLE_NAME, values, null, null) } } private fun handleVersionChange(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { if (oldVersion <= 153) { migrateLegacyAccounts(db) if (newVersion > 153) { migrateAccounts(AccountManager.get(context), db) db.execSQL(SQLQueryBuilder.dropTable(true, Accounts.TABLE_NAME).sql) } } if (oldVersion <= 164) { try { db.execSQL(SQLQueryBuilder.dropView(true, "messages").sql) } catch (e: IllegalArgumentException) { // Ignore http://crashes.to/s/5f46822a382 } db.execSQL(SQLQueryBuilder.dropView(true, "messages_conversation_entries").sql) db.execSQL(SQLQueryBuilder.dropTrigger(true, "delete_old_received_messages").sql) db.execSQL(SQLQueryBuilder.dropTrigger(true, "delete_old_sent_messages").sql) db.execSQL(SQLQueryBuilder.dropTable(true, "messages_inbox").sql) db.execSQL(SQLQueryBuilder.dropTable(true, "messages_outbox").sql) db.execSQL(SQLQueryBuilder.dropIndex(true, "messages_inbox_index").sql) db.execSQL(SQLQueryBuilder.dropIndex(true, "messages_outbox_index").sql) } safeUpgrade(db, Statuses.TABLE_NAME, Statuses.COLUMNS, Statuses.TYPES, true, null) safeUpgrade(db, Activities.AboutMe.TABLE_NAME, Activities.AboutMe.COLUMNS, Activities.AboutMe.TYPES, true, null) migrateDrafts(db) safeUpgrade(db, CachedUsers.TABLE_NAME, CachedUsers.COLUMNS, CachedUsers.TYPES, true, null, createConflictReplaceConstraint(CachedUsers.USER_KEY)) safeUpgrade(db, CachedStatuses.TABLE_NAME, CachedStatuses.COLUMNS, CachedStatuses.TYPES, true, null) safeUpgrade(db, CachedHashtags.TABLE_NAME, CachedHashtags.COLUMNS, CachedHashtags.TYPES, true, null) safeUpgrade(db, CachedRelationships.TABLE_NAME, CachedRelationships.COLUMNS, CachedRelationships.TYPES, true, null, createConflictReplaceConstraint(CachedRelationships.ACCOUNT_KEY, CachedRelationships.USER_KEY)) migrateFilters(db, oldVersion) safeUpgrade(db, CachedTrends.Local.TABLE_NAME, CachedTrends.Local.COLUMNS, CachedTrends.Local.TYPES, true, null) safeUpgrade(db, Tabs.TABLE_NAME, Tabs.COLUMNS, Tabs.TYPES, false, null) safeUpgrade(db, SavedSearches.TABLE_NAME, SavedSearches.COLUMNS, SavedSearches.TYPES, true, null) // DM columns safeUpgrade(db, Messages.TABLE_NAME, Messages.COLUMNS, Messages.TYPES, true, null, messagesConstraint()) safeUpgrade(db, Conversations.TABLE_NAME, Conversations.COLUMNS, Conversations.TYPES, true, null, messageConversationsConstraint()) safeUpgrade(db, PushNotifications.TABLE_NAME, PushNotifications.COLUMNS, PushNotifications.TYPES, false, null) if (oldVersion < 131) { migrateFilteredUsers(db) } db.beginTransaction() db.execSQL(SQLQueryBuilder.dropTable(true, "network_usages").sql) db.execSQL(SQLQueryBuilder.dropTable(true, "mentions").sql) db.execSQL(SQLQueryBuilder.dropTable(true, "activities_by_friends").sql) createTriggers(db) createIndices(db) db.setTransactionSuccessful() db.endTransaction() } private fun migrateDrafts(db: SQLiteDatabase) { val draftsAlias = HashMap<String, String>() draftsAlias.put(Drafts.MEDIA, "medias") safeUpgrade(db, Drafts.TABLE_NAME, Drafts.COLUMNS, Drafts.TYPES, false, draftsAlias) } private fun migrateFilters(db: SQLiteDatabase, oldVersion: Int) { safeUpgrade(db, Filters.Users.TABLE_NAME, Filters.Users.COLUMNS, Filters.Users.TYPES, oldVersion < 49, null) val filtersAlias = HashMap<String, String>() safeUpgrade(db, Filters.Keywords.TABLE_NAME, Filters.Keywords.COLUMNS, Filters.Keywords.TYPES, oldVersion < 49, filtersAlias) safeUpgrade(db, Filters.Sources.TABLE_NAME, Filters.Sources.COLUMNS, Filters.Sources.TYPES, oldVersion < 49, filtersAlias) safeUpgrade(db, Filters.Links.TABLE_NAME, Filters.Links.COLUMNS, Filters.Links.TYPES, oldVersion < 49, filtersAlias) safeUpgrade(db, Filters.Subscriptions.TABLE_NAME, Filters.Subscriptions.COLUMNS, Filters.Subscriptions.TYPES, false, null) } private fun migrateLegacyAccounts(db: SQLiteDatabase) { val alias = HashMap<String, String>() alias[Accounts.SCREEN_NAME] = "username" alias[Accounts.NAME] = "username" alias[Accounts.ACCOUNT_KEY] = "user_id" alias[Accounts.COLOR] = "user_color" alias[Accounts.OAUTH_TOKEN_SECRET] = "token_secret" alias[Accounts.API_URL_FORMAT] = "rest_base_url" safeUpgrade(db, Accounts.TABLE_NAME, Accounts.COLUMNS, Accounts.TYPES, false, alias) } private fun migrateFilteredUsers(db: SQLiteDatabase) { db.execSQL(SQLQueryBuilder.update(OnConflict.REPLACE, Filters.Users.TABLE_NAME) .set(SetValue(Filters.Users.USER_KEY, RawSQLLang(Filters.Users.USER_KEY + "||?"))) .where(Expression.notLikeArgs(Column(Filters.Users.USER_KEY))) .buildSQL(), arrayOf<Any>("@twitter.com", "%@%")) } private fun createTable(tableName: String, columns: Array<String>, types: Array<String>, createIfNotExists: Boolean, vararg constraints: Constraint): String { val qb = SQLQueryBuilder.createTable(createIfNotExists, tableName) qb.columns(*NewColumn.createNewColumns(columns, types)) qb.constraint(*constraints) return qb.buildSQL() } private fun createIndex(indexName: String, tableName: String, columns: Array<String>, createIfNotExists: Boolean): String { val qb = SQLQueryBuilder.createIndex(false, createIfNotExists) qb.name(indexName) qb.on(Table(tableName), Columns(*columns)) return qb.buildSQL() } private fun messagesConstraint(): Constraint { return Constraint.unique("unique_message", Columns(Messages.ACCOUNT_KEY, Messages.CONVERSATION_ID, Messages.MESSAGE_ID), OnConflict.REPLACE) } private fun messageConversationsConstraint(): Constraint { return Constraint.unique("unique_message_conversations", Columns(Conversations.ACCOUNT_KEY, Conversations.CONVERSATION_ID), OnConflict.REPLACE) } }
gpl-3.0
24fb82140d414475339febc4f97b2015
48.914201
131
0.687374
4.576777
false
false
false
false
stripe/stripe-android
example/src/main/java/com/stripe/example/activity/GooglePayLauncherIntegrationActivity.kt
1
4154
package com.stripe.example.activity import android.os.Bundle import androidx.core.view.isInvisible import androidx.core.view.isVisible import com.stripe.android.googlepaylauncher.GooglePayEnvironment import com.stripe.android.googlepaylauncher.GooglePayLauncher import com.stripe.example.databinding.GooglePayActivityBinding import org.json.JSONObject class GooglePayLauncherIntegrationActivity : StripeIntentActivity() { private var clientSecret = "" private var isGooglePayReady = false private val viewBinding: GooglePayActivityBinding by lazy { GooglePayActivityBinding.inflate(layoutInflater) } private val googlePayButton: GooglePayButton by lazy { viewBinding.googlePayButton } private val snackbarController: SnackbarController by lazy { SnackbarController(viewBinding.coordinator) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) // If the activity is being recreated, load the client secret if it has already been fetched savedInstanceState?.let { clientSecret = it.getString(SAVED_CLIENT_SECRET, "") } if (clientSecret.isBlank()) { viewModel.createPaymentIntent(COUNTRY_CODE) .observe(this) { result -> result.fold( onSuccess = ::onPaymentIntentCreated, onFailure = { error -> snackbarController.show( "Could not create PaymentIntent. ${error.message}" ) } ) } } val googlePayLauncher = GooglePayLauncher( activity = this, config = GooglePayLauncher.Config( environment = GooglePayEnvironment.Test, merchantCountryCode = COUNTRY_CODE, merchantName = "Widget Store", billingAddressConfig = GooglePayLauncher.BillingAddressConfig( isRequired = true, format = GooglePayLauncher.BillingAddressConfig.Format.Full, isPhoneNumberRequired = false ), existingPaymentMethodRequired = false ), readyCallback = ::onGooglePayReady, resultCallback = ::onGooglePayResult ) viewBinding.googlePayButton.setOnClickListener { viewBinding.progressBar.isVisible = true googlePayLauncher.presentForPaymentIntent(clientSecret) } updateUi() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(SAVED_CLIENT_SECRET, clientSecret) } private fun updateUi() { val isLoadingComplete = isGooglePayReady && clientSecret.isNotBlank() viewBinding.progressBar.isInvisible = isLoadingComplete googlePayButton.isEnabled = isLoadingComplete } private fun onPaymentIntentCreated(json: JSONObject) { clientSecret = json.getString("secret") updateUi() } private fun onGooglePayReady(isReady: Boolean) { snackbarController.show("Google Pay ready? $isReady") isGooglePayReady = isReady updateUi() } private fun onGooglePayResult(result: GooglePayLauncher.Result) { viewBinding.progressBar.isInvisible = true when (result) { GooglePayLauncher.Result.Completed -> { "Successfully collected payment." } GooglePayLauncher.Result.Canceled -> { "Customer cancelled Google Pay." } is GooglePayLauncher.Result.Failed -> { "Google Pay failed. ${result.error.message}" } }.let { snackbarController.show(it) googlePayButton.isEnabled = false } } private companion object { private const val COUNTRY_CODE = "US" private const val SAVED_CLIENT_SECRET = "client_secret" } }
mit
ca2a77c9d983efdcb104028d4e66ee87
33.616667
100
0.622532
6.073099
false
false
false
false
hannesa2/owncloud-android
owncloudApp/src/androidTest/java/com/owncloud/android/utils/matchers/BottomSheetFragmentItemViewMatchers.kt
2
3438
/** * ownCloud Android client application * * @author Abel García de Prada * * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.utils.matchers import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.test.espresso.Espresso import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.matcher.BoundedMatcher import androidx.test.espresso.matcher.RootMatchers import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.withText import com.owncloud.android.R import com.owncloud.android.presentation.ui.common.BottomSheetFragmentItemView import org.hamcrest.Description import org.hamcrest.Matcher fun Int.bsfItemWithTitle(@StringRes title: Int, @ColorRes tintColor: Int?) { Espresso.onView(ViewMatchers.withId(this)).inRoot(RootMatchers.isDialog()) .check(ViewAssertions.matches(withTitle(title, tintColor))) } fun Int.bsfItemWithIcon(@DrawableRes drawable: Int, @ColorRes tintColor: Int?) { Espresso.onView(ViewMatchers.withId(this)).inRoot(RootMatchers.isDialog()) .check(ViewAssertions.matches(withIcon(drawable, tintColor))) } private fun withTitle(@StringRes title: Int, @ColorRes tintColor: Int?): Matcher<View> = object : BoundedMatcher<View, BottomSheetFragmentItemView>(BottomSheetFragmentItemView::class.java) { override fun describeTo(description: Description) { description.appendText("BottomSheetFragmentItemView with text: $title") tintColor?.let { description.appendText(" and tint color id: $tintColor") } } override fun matchesSafely(item: BottomSheetFragmentItemView): Boolean { val itemTitleView = item.findViewById<TextView>(R.id.item_title) val textMatches = withText(title).matches(itemTitleView) val textColorMatches = tintColor?.let { withTextColor(tintColor).matches(itemTitleView) } ?: true return textMatches && textColorMatches } } private fun withIcon(@DrawableRes drawable: Int, @ColorRes tintColor: Int?): Matcher<View> = object : BoundedMatcher<View, BottomSheetFragmentItemView>(BottomSheetFragmentItemView::class.java) { override fun describeTo(description: Description) { description.appendText("BottomSheetFragmentItemView with icon: $drawable") tintColor?.let { description.appendText(" and tint color id: $tintColor") } } override fun matchesSafely(item: BottomSheetFragmentItemView): Boolean { val itemIconView = item.findViewById<ImageView>(R.id.item_icon) return withDrawable(drawable, tintColor).matches(itemIconView) } }
gpl-2.0
2a10010008521e88fbe1c66893cd7764
43.636364
109
0.749491
4.669837
false
true
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/gesturehandler/react/RNGestureHandlerInteractionManager.kt
2
2297
package abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.react import android.util.SparseArray import abi44_0_0.com.facebook.react.bridge.ReadableMap import abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandler import abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerInteractionController class RNGestureHandlerInteractionManager : GestureHandlerInteractionController { private val waitForRelations = SparseArray<IntArray>() private val simultaneousRelations = SparseArray<IntArray>() fun dropRelationsForHandlerWithTag(handlerTag: Int) { waitForRelations.remove(handlerTag) simultaneousRelations.remove(handlerTag) } private fun convertHandlerTagsArray(config: ReadableMap, key: String): IntArray { val array = config.getArray(key)!! return IntArray(array.size()).also { for (i in it.indices) { it[i] = array.getInt(i) } } } fun configureInteractions(handler: GestureHandler<*>, config: ReadableMap) { handler.setInteractionController(this) if (config.hasKey(KEY_WAIT_FOR)) { val tags = convertHandlerTagsArray(config, KEY_WAIT_FOR) waitForRelations.put(handler.tag, tags) } if (config.hasKey(KEY_SIMULTANEOUS_HANDLERS)) { val tags = convertHandlerTagsArray(config, KEY_SIMULTANEOUS_HANDLERS) simultaneousRelations.put(handler.tag, tags) } } override fun shouldWaitForHandlerFailure(handler: GestureHandler<*>, otherHandler: GestureHandler<*>) = waitForRelations[handler.tag]?.any { tag -> tag == otherHandler.tag } ?: false override fun shouldRequireHandlerToWaitForFailure( handler: GestureHandler<*>, otherHandler: GestureHandler<*>, ) = false override fun shouldHandlerBeCancelledBy(handler: GestureHandler<*>, otherHandler: GestureHandler<*>) = false override fun shouldRecognizeSimultaneously( handler: GestureHandler<*>, otherHandler: GestureHandler<*>, ) = simultaneousRelations[handler.tag]?.any { tag -> tag == otherHandler.tag } ?: false fun reset() { waitForRelations.clear() simultaneousRelations.clear() } companion object { private const val KEY_WAIT_FOR = "waitFor" private const val KEY_SIMULTANEOUS_HANDLERS = "simultaneousHandlers" } }
bsd-3-clause
1a731ad5c55051fcfeec3a5c6274bce6
36.655738
110
0.747497
4.62173
false
true
false
false
Senspark/ee-x
src/android/app_lovin/src/main/java/com/ee/internal/AppLovinInterstitialAdListener.kt
1
2506
package com.ee.internal import androidx.annotation.AnyThread import com.applovin.sdk.AppLovinAd import com.applovin.sdk.AppLovinAdClickListener import com.applovin.sdk.AppLovinAdDisplayListener import com.applovin.sdk.AppLovinAdLoadListener import com.ee.ILogger import com.ee.IMessageBridge import com.ee.Thread import kotlinx.serialization.Serializable import java.util.concurrent.atomic.AtomicBoolean internal class AppLovinInterstitialAdListener( private val _bridge: IMessageBridge, private val _logger: ILogger) : AppLovinAdLoadListener, AppLovinAdDisplayListener, AppLovinAdClickListener { @Serializable @Suppress("unused") private class ErrorResponse( val code: Int, val message: String ) companion object { private val kTag = AppLovinInterstitialAdListener::class.java.name private const val kPrefix = "AppLovinBridge" private const val kOnInterstitialAdLoaded = "${kPrefix}OnInterstitialAdLoaded" private const val kOnInterstitialAdFailedToLoad = "${kPrefix}OnInterstitialAdFailedToLoad" private const val kOnInterstitialAdClicked = "${kPrefix}OnInterstitialAdClicked" private const val kOnInterstitialAdClosed = "${kPrefix}OnInterstitialAdClosed" } private val _isLoaded = AtomicBoolean(false) val isLoaded: Boolean @AnyThread get() = _isLoaded.get() override fun adReceived(ad: AppLovinAd) { Thread.runOnMainThread { _logger.debug("$kTag: ${this::adReceived.name}") _isLoaded.set(true) _bridge.callCpp(kOnInterstitialAdLoaded) } } override fun failedToReceiveAd(errorCode: Int) { Thread.runOnMainThread { _logger.info("$kTag: ${this::failedToReceiveAd.name}: code $errorCode") _bridge.callCpp(kOnInterstitialAdFailedToLoad, ErrorResponse(errorCode, "").serialize()) } } override fun adDisplayed(ad: AppLovinAd) { Thread.runOnMainThread { _logger.info("$kTag: ${this::adDisplayed.name}") } } override fun adClicked(ad: AppLovinAd) { Thread.runOnMainThread { _logger.info("$kTag: ${this::adClicked.name}") _bridge.callCpp(kOnInterstitialAdClicked) } } override fun adHidden(ad: AppLovinAd) { Thread.runOnMainThread { _logger.info(this::adHidden.name) _isLoaded.set(false) _bridge.callCpp(kOnInterstitialAdClosed) } } }
mit
af70ffe03999af0b8598a924559cb3f5
32.878378
100
0.689146
4.819231
false
false
false
false
TeamWizardry/LibrarianLib
testcore/src/main/kotlin/com/teamwizardry/librarianlib/testcore/content/utils/TestScreen.kt
1
4755
package com.teamwizardry.librarianlib.testcore.content.utils import com.mojang.blaze3d.systems.RenderSystem import com.teamwizardry.librarianlib.core.util.vec import net.minecraft.client.gui.screen.Screen import net.minecraft.client.util.math.MatrixStack import net.minecraft.item.ItemStack import net.minecraft.text.LiteralText import net.minecraft.text.Style public open class TestScreen(public val config: TestScreenConfig): Screen(LiteralText(config.title)) { public constructor(configure: TestScreenConfig.() -> Unit) : this(TestScreenConfig(configure)) override fun shouldCloseOnEsc(): Boolean = config.closeOnEsc override fun isPauseScreen(): Boolean = config.pausesGame private val screenContext = TestScreenConfig.ScreenContext(this) private var left = 0.0 private var top = 0.0 override fun onClose() { config.onClose.run(screenContext) super.onClose() } override fun init() { this.left = (width - config.size.x * config.scale) / 2 this.top = (height - config.size.y * config.scale) / 2 config.init.run(screenContext) super.init() } override fun tick() { config.tick.run(screenContext) super.tick() } override fun render(matrixStack: MatrixStack, mouseX: Int, mouseY: Int, partialTicks: Float) { matrixStack.push() matrixStack.translate(left, top, 0.0) matrixStack.scale(config.scale.toFloat(), config.scale.toFloat(), 1f) config.draw.run(TestScreenConfig.DrawContext(this, matrixStack, vec(mouseX - left, mouseY - top) / config.scale, partialTicks)) matrixStack.pop() super.render(matrixStack, mouseX, mouseY, partialTicks) } override fun charTyped(character: Char, modifiers: Int): Boolean { config.charTyped.run(TestScreenConfig.CharContext(this, character, modifiers)) return super.charTyped(character, modifiers) } override fun keyPressed(key: Int, scanCode: Int, modifiers: Int): Boolean { config.keyPressed.run(TestScreenConfig.KeyContext(this, key, scanCode, modifiers)) return super.keyPressed(key, scanCode, modifiers) } override fun keyReleased(key: Int, scanCode: Int, modifiers: Int): Boolean { config.keyReleased.run(TestScreenConfig.KeyContext(this, key, scanCode, modifiers)) return super.keyReleased(key, scanCode, modifiers) } override fun mouseClicked(x: Double, y: Double, button: Int): Boolean { config.mouseClicked.run(TestScreenConfig.MouseButtonContext(this, vec(x - left, y - top) / config.scale, button)) return super.mouseClicked(x, y, button) } override fun mouseReleased(x: Double, y: Double, button: Int): Boolean { config.mouseReleased.run(TestScreenConfig.MouseButtonContext(this, vec(x - left, y - top) / config.scale, button)) return super.mouseReleased(x, y, button) } override fun mouseScrolled(x: Double, y: Double, amount: Double): Boolean { config.mouseScrolled.run(TestScreenConfig.MouseScrollContext(this, vec(x - left, y - top) / config.scale, amount)) return super.mouseScrolled(x, y, amount) } override fun mouseMoved(x: Double, y: Double) { config.mouseMoved.run(TestScreenConfig.MouseMovedContext(this, vec(x - left, y - top) / config.scale)) super.mouseMoved(x, y) } override fun mouseDragged(startX: Double, startY: Double, button: Int, deltaX: Double, deltaY: Double): Boolean { config.mouseDragged.run(TestScreenConfig.MouseDraggedContext(this, vec(startX - left, startY - top) / config.scale, vec(deltaX, deltaY) / config.scale, button)) return super.mouseDragged(startX, startY, button, deltaX, deltaY) } // make these rendering helpers public public override fun drawHorizontalLine(matrices: MatrixStack, x1: Int, x2: Int, y: Int, color: Int) { super.drawHorizontalLine(matrices, x1, x2, y, color) } public override fun drawVerticalLine(matrices: MatrixStack, x: Int, y1: Int, y2: Int, color: Int) { super.drawVerticalLine(matrices, x, y1, y2, color) } public override fun fillGradient( matrices: MatrixStack, xStart: Int, yStart: Int, xEnd: Int, yEnd: Int, colorStart: Int, colorEnd: Int ) { super.fillGradient(matrices, xStart, yStart, xEnd, yEnd, colorStart, colorEnd) } public override fun renderTooltip(matrices: MatrixStack, stack: ItemStack, x: Int, y: Int) { super.renderTooltip(matrices, stack, x, y) } public override fun renderTextHoverEffect(matrices: MatrixStack, style: Style?, x: Int, y: Int) { super.renderTextHoverEffect(matrices, style, x, y) } }
lgpl-3.0
8ae31328efaf00f8c61d6f1a9d3e5dc2
39.305085
168
0.690011
4.043367
false
true
false
false
androidx/androidx
compose/ui/ui-text-google-fonts/src/main/java/androidx/compose/ui/text/googlefonts/FontProviderHelper.kt
3
3963
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.googlefonts import android.annotation.SuppressLint import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.content.pm.Signature import android.content.res.Resources import androidx.annotation.WorkerThread import androidx.compose.ui.text.ExperimentalTextApi import androidx.core.content.res.FontResourcesParserCompat import java.util.Arrays @SuppressLint("ListIterator") // this is not a hot code path, nor is it optimized @OptIn(ExperimentalTextApi::class) @WorkerThread internal fun GoogleFont.Provider.checkAvailable( packageManager: PackageManager, resources: Resources ): Boolean { // check package is available (false return paths) @Suppress("DEPRECATION") val providerInfo = packageManager.resolveContentProvider(providerAuthority, 0) ?: return false if (providerInfo.packageName != providerPackage) return false // now check signatures (true or except after this) val signatures = packageManager.getSignatures(providerInfo.packageName) val sortedSignatures = signatures.sortedWith(ByteArrayComparator) val allExpectedCerts = loadCertsIfNeeded(resources) val certsMatched = allExpectedCerts.any { certList -> val expected = certList?.sortedWith(ByteArrayComparator) if (expected?.size != sortedSignatures.size) return@any false for (i in expected.indices) { if (!Arrays.equals(expected[i], sortedSignatures[i])) return@any false } true } return if (certsMatched) { true } else { throwFormattedCertsMissError(signatures) } } @SuppressLint("ListIterator") // not a hot code path, not optimized private fun throwFormattedCertsMissError(signatures: List<ByteArray>): Nothing { val fullDescription = signatures.joinToString( ",", prefix = "listOf(listOf(", postfix = "))" ) { repr(it) } throw IllegalStateException( "Provided signatures did not match. Actual signatures of package are:\n\n$fullDescription" ) } private fun repr(b: ByteArray): String { return b.joinToString(",", prefix = "byteArrayOf(", postfix = ")") } @OptIn(ExperimentalTextApi::class) private fun GoogleFont.Provider.loadCertsIfNeeded(resources: Resources): List<List<ByteArray?>?> { if (certificates != null) { return certificates } return FontResourcesParserCompat.readCerts(resources, certificatesRes) } private fun PackageManager.getSignatures(packageName: String): List<ByteArray> { @Suppress("DEPRECATION") @SuppressLint("PackageManagerGetSignatures") val packageInfo: PackageInfo = getPackageInfo(packageName, PackageManager.GET_SIGNATURES) @Suppress("DEPRECATION") return convertToByteArrayList(packageInfo.signatures) } private val ByteArrayComparator = Comparator { l: ByteArray, r: ByteArray -> if (l.size != r.size) { return@Comparator l.size - r.size } var i = 0 while (i < l.size) { if (l[i] != r[i]) { return@Comparator l[i] - r[i] } ++i } 0 } private fun convertToByteArrayList(signatures: Array<Signature>): List<ByteArray> { val shaList: MutableList<ByteArray> = ArrayList() for (signature in signatures) { shaList.add(signature.toByteArray()) } return shaList }
apache-2.0
cd3c478f7e108b20d07656214e284caf
34.070796
98
0.719152
4.41314
false
false
false
false
pedroSG94/rtmp-rtsp-stream-client-java
rtmp/src/main/java/com/pedro/rtmp/rtmp/message/control/UserControl.kt
2
2414
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtmp.rtmp.message.control import com.pedro.rtmp.rtmp.chunk.ChunkStreamId import com.pedro.rtmp.rtmp.chunk.ChunkType import com.pedro.rtmp.rtmp.message.BasicHeader import com.pedro.rtmp.rtmp.message.MessageType import com.pedro.rtmp.rtmp.message.RtmpMessage import com.pedro.rtmp.utils.readUInt16 import com.pedro.rtmp.utils.readUInt32 import com.pedro.rtmp.utils.writeUInt16 import com.pedro.rtmp.utils.writeUInt32 import java.io.ByteArrayOutputStream import java.io.IOException import java.io.InputStream /** * Created by pedro on 21/04/21. */ class UserControl(var type: Type = Type.PING_REQUEST, var event: Event = Event(-1, -1)): RtmpMessage(BasicHeader(ChunkType.TYPE_0, ChunkStreamId.PROTOCOL_CONTROL.mark)) { private val TAG = "UserControl" private var bodySize = 6 override fun readBody(input: InputStream) { bodySize = 0 val t = input.readUInt16() type = Type.values().find { it.mark.toInt() == t } ?: throw IOException("unknown user control type: $t") bodySize += 2 val data = input.readUInt32() bodySize += 4 event = if (type == Type.SET_BUFFER_LENGTH) { val bufferLength = input.readUInt32() Event(data, bufferLength) } else { Event(data) } } override fun storeBody(): ByteArray { val byteArrayOutputStream = ByteArrayOutputStream() byteArrayOutputStream.writeUInt16(type.mark.toInt()) byteArrayOutputStream.writeUInt32(event.data) if (event.bufferLength != -1) { byteArrayOutputStream.writeUInt32(event.bufferLength) } return byteArrayOutputStream.toByteArray() } override fun getType(): MessageType = MessageType.USER_CONTROL override fun getSize(): Int = bodySize override fun toString(): String { return "UserControl(type=$type, event=$event, bodySize=$bodySize)" } }
apache-2.0
ff26ecf2155c506a00fd38da906d7bf4
32.541667
170
0.732809
3.957377
false
false
false
false
wealthfront/magellan
magellan-lint/src/main/java/com/wealthfront/magellan/LintRegistry.kt
1
567
package com.wealthfront.magellan import com.android.tools.lint.client.api.IssueRegistry import com.android.tools.lint.detector.api.CURRENT_API import com.android.tools.lint.detector.api.Issue internal const val PRIORITY_MED = 5 internal const val PRIORITY_HIGH = 8 internal const val PRIORITY_MAX = 10 class LintRegistry : IssueRegistry() { override val issues: List<Issue> get() = listOf( INVALID_CHILD_IN_SCREEN_CONTAINER, ENFORCE_LIFECYCLE_AWARE_ATTACHMENT, AVOID_USING_ACTIVITY ) override val api: Int get() = CURRENT_API }
apache-2.0
a5f3ea37aa53812529ff83de1a61fbbb
24.772727
54
0.744268
3.730263
false
false
false
false
bjzhou/Coolapk
app/src/main/kotlin/bjzhou/coolapk/app/net/ApkDownloader.kt
1
7609
package bjzhou.coolapk.app.net import android.Manifest import android.app.DownloadManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.Uri import android.os.Environment import android.util.Log import android.widget.Toast import bjzhou.coolapk.app.App import bjzhou.coolapk.app.model.Apk import bjzhou.coolapk.app.ui.base.BaseActivity import bjzhou.coolapk.app.util.Constant import bjzhou.coolapk.app.util.Settings import bjzhou.coolapk.app.util.Utils import io.reactivex.Observable import io.reactivex.ObservableEmitter import java.io.File import java.util.* import java.util.concurrent.TimeUnit /** * author: zhoubinjia * date: 2017/2/22 */ class ApkDownloader { private val downloadingApks = ArrayList<Apk>() private val downloadManager = App.context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager private val pendingApks = LinkedList<Apk>() private val downloadCompleteReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Log.d(TAG, "action: ${intent.action}") when(intent.action) { DownloadManager.ACTION_DOWNLOAD_COMPLETE -> { val downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) synchronized(lock) { val removeApk: Apk? = downloadingApks.firstOrNull { it.downloadId == downloadId } removeApk?.let { downloadingApks.remove(it) } if (pendingApks.isNotEmpty()) { download(pendingApks.poll()) } } if (Settings.instance.autoInstall) { val q = DownloadManager.Query() q.setFilterById(downloadId) val cursor = downloadManager.query(q) cursor.moveToFirst() val localUriString = cursor.getString(cursor .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)) cursor.close() val uri = Uri.parse(localUriString) Utils.installApk(uri) } } } } } private val packageReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Log.d(TAG, "action: ${intent.action}") when(intent.action) { Intent.ACTION_PACKAGE_ADDED, Intent.ACTION_PACKAGE_REPLACED -> { if (Settings.instance.deleteFileAfterInstall) { val pkgName = intent.data.schemeSpecificPart val pkgInfo = App.context.packageManager.getPackageInfo(pkgName, 0) val fileName = Apk.getFileName(pkgName, pkgInfo.versionName) val file = File(Settings.instance.downloadDir, fileName) if (file.exists() && file.delete()) { Toast.makeText(App.context, "安装包已删除", Toast.LENGTH_SHORT).show() } } } } } } init { val downloadFilter = IntentFilter() downloadFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE) val packageFilter = IntentFilter() packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED) packageFilter.addAction(Intent.ACTION_PACKAGE_REPLACED) packageFilter.addDataScheme("package") App.context.registerReceiver(downloadCompleteReceiver, downloadFilter) App.context.registerReceiver(packageReceiver, packageFilter) } private var mPermissionGranted = true fun checkPermission(activity: BaseActivity) { activity.checkPermissions({ permission, succeed -> mPermissionGranted = succeed }, Manifest.permission.WRITE_EXTERNAL_STORAGE) } fun download(apk: Apk?) { if (!Utils.networkConnected) { return } if (!mPermissionGranted) { return } if (apk == null) { return } if (downloadingApks.contains(apk)) { return } if (pendingApks.contains(apk)) { return } synchronized(lock) { if (downloadingApks.size >= Settings.instance.maxDownloadNumber) { pendingApks.offer(apk) return } } val apkFile = File(Settings.instance.downloadDir, apk.filename) if (apkFile.exists()) { apkFile.delete() } Log.d(TAG, apk.url) val request = DownloadManager.Request(Uri.parse(apk.url)) request.setDestinationInExternalFilesDir(App.context, Environment.DIRECTORY_DOWNLOADS, apk.filename) request.setMimeType("application/vnd.android.package-archive") request.addRequestHeader("Cookie", "coolapk_did=" + Constant.COOLAPK_DID) val id = downloadManager.enqueue(request) apk.downloadId = id synchronized(lock) { downloadingApks.add(apk) } } fun getDownloadStatus(apk: Apk?): DownloadStatus { val status = DownloadStatus() if (apk == null) { return status } if (pendingApks.contains(apk)) { status.status = DownloadManager.STATUS_PENDING return status } val index = downloadingApks.indexOf(apk) if (index != -1) { apk.downloadId = downloadingApks[index].downloadId } if (apk.downloadId == -1L) { return status } val q = DownloadManager.Query() q.setFilterById(apk.downloadId) val cursor = downloadManager.query(q) cursor.moveToFirst() val bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)) val bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)) val column_status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) cursor.close() val dl_progress = (bytes_downloaded * 100L / bytes_total).toInt() status.percent = dl_progress status.status = column_status return status } fun observeDownloadStatus(apk: Apk?): Observable<DownloadStatus> { return Observable.interval(100, TimeUnit.MILLISECONDS) .flatMap { Observable.create { it: ObservableEmitter<DownloadStatus> -> val status = getDownloadStatus(apk) if (status.status == DownloadStatus.STATUS_NOT_STARTED) { it.onComplete() return@create } it.onNext(status) if (status.status == DownloadManager.STATUS_SUCCESSFUL || status.status == DownloadManager.STATUS_FAILED) { it.onComplete() } } } } private object Holder { val INSTANCE = ApkDownloader() } companion object { val instance: ApkDownloader by lazy { Holder.INSTANCE } val TAG: String = ApkDownloader::class.java.simpleName val lock: Any = Any() } }
gpl-2.0
40a40ea486d647d4e4d0f01ad9d80ea2
35.009479
131
0.583257
5.115825
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/wpmangareader/gsnation/src/GSNation.kt
1
2618
package eu.kanade.tachiyomi.extension.fr.gsnation import eu.kanade.tachiyomi.multisrc.wpmangareader.WPMangaReader import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.SManga import okhttp3.Response import org.jsoup.nodes.Document import java.text.SimpleDateFormat import java.util.Locale class GSNation : WPMangaReader("GS Nation", "http://gs-nation.fr", "fr", dateFormat = SimpleDateFormat("MMMM dd, yyyy", Locale.FRANCE)) { // remove the novels from the response override fun searchMangaParse(response: Response): MangasPage { val mangasPage = super.searchMangaParse(response) return MangasPage( mangasPage.mangas .filterNot { it.title.startsWith("novel", true) } .distinctBy { it.url }, mangasPage.hasNextPage ) } override fun latestUpdatesParse(response: Response): MangasPage = searchMangaParse(response) override fun popularMangaParse(response: Response): MangasPage = searchMangaParse(response) override fun mangaDetailsParse(document: Document) = SManga.create().apply { author = document.select(".imptdt:contains(auteur) i").text() artist = document.select(".tsinfo .imptdt:contains(artiste) i").text() genre = document.select(".mgen a").joinToString { it.text() } status = parseStatus(document.select(".tsinfo .imptdt:contains(statut) i").text()) thumbnail_url = document.select("div.thumb img").attr("abs:src") description = document.select(".entry-content[itemprop=description]").joinToString("\n") { it.text() } title = document.selectFirst("h1.entry-title").text() // add series type(manga/manhwa/manhua/other) thinggy to genre document.select(seriesTypeSelector).firstOrNull()?.ownText()?.let { if (it.isEmpty().not() && genre!!.contains(it, true).not()) { genre += if (genre!!.isEmpty()) it else ", $it" } } // add alternative name to manga description document.select(altNameSelector).firstOrNull()?.ownText()?.let { if (it.isEmpty().not()) { description += when { description!!.isEmpty() -> altName + it else -> "\n\n$altName" + it } } } } override fun parseStatus(status: String) = when { status.contains("En cours") -> SManga.ONGOING status.contains("Terminée") -> SManga.COMPLETED status.contains("Licenciée") -> SManga.LICENSED else -> SManga.UNKNOWN } }
apache-2.0
18a986a24829817d750d88daae6f9504
39.246154
137
0.639908
4.38191
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/bikeway/AddCycleway.kt
1
8776
package de.westnordost.streetcomplete.quests.bikeway import de.westnordost.osmapi.map.data.BoundingBox import de.westnordost.osmapi.map.data.Element import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.meta.OsmTaggings import de.westnordost.streetcomplete.data.osm.Countries import de.westnordost.streetcomplete.data.osm.OsmElementQuestType import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.download.MapDataWithGeometryHandler import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao import de.westnordost.streetcomplete.data.osm.tql.OverpassQLUtil import de.westnordost.streetcomplete.quests.bikeway.Cycleway.* class AddCycleway(private val overpassServer: OverpassMapDataDao) : OsmElementQuestType<CyclewayAnswer> { override val commitMessage = "Add whether there are cycleways" override val icon = R.drawable.ic_quest_bicycleway // See overview here: https://ent8r.github.io/blacklistr/?streetcomplete=bikeway/AddCycleway.kt // #749. sources: // Google Street View (driving around in virtual car) // https://en.wikivoyage.org/wiki/Cycling // http://peopleforbikes.org/get-local/ (US) override val enabledForCountries = Countries.noneExcept( // all of Northern and Western Europe, most of Central Europe, some of Southern Europe "NO","SE","FI","IS","DK", "GB","IE","NL","BE","FR","LU", "DE","PL","CZ","HU","AT","CH","LI", "ES","IT", // East Asia "JP","KR","TW", // some of China (East Coast) "CN-BJ","CN-TJ","CN-SD","CN-JS","CN-SH", "CN-ZJ","CN-FJ","CN-GD","CN-CQ", // Australia etc "NZ","AU", // some of Canada "CA-BC","CA-QC","CA-ON","CA-NS","CA-PE", // some of the US // West Coast, East Coast, Center, South "US-WA","US-OR","US-CA", "US-MA","US-NJ","US-NY","US-DC","US-CT","US-FL", "US-MN","US-MI","US-IL","US-WI","US-IN", "US-AZ","US-TX" ) override fun getTitle(tags: Map<String, String>) = R.string.quest_cycleway_title2 override fun isApplicableTo(element: Element):Boolean? = null override fun download(bbox: BoundingBox, handler: MapDataWithGeometryHandler): Boolean { return overpassServer.getAndHandleQuota(getOverpassQuery(bbox), handler) } /** returns overpass query string to get streets without cycleway info not near paths for * bicycles. */ private fun getOverpassQuery(bbox: BoundingBox): String { val minDistToCycleways = 15 //m return OverpassQLUtil.getGlobalOverpassBBox(bbox) + "way[highway ~ \"^(primary|primary_link|secondary|secondary_link|tertiary|tertiary_link|unclassified)$\"]" + "[area != yes]" + // not any motorroads "[motorroad != yes]" + // only without cycleway tags "[!cycleway][!\"cycleway:left\"][!\"cycleway:right\"][!\"cycleway:both\"]" + "[!\"sidewalk:bicycle\"][!\"sidewalk:both:bicycle\"][!\"sidewalk:left:bicycle\"][!\"sidewalk:right:bicycle\"]" + // not any with low speed limit because they not very likely to have cycleway infrastructure "[maxspeed !~ \"^(20|15|10|8|7|6|5|10 mph|5 mph|walk)$\"]" + // not any unpaved because of the same reason "[surface !~ \"^(" + OsmTaggings.ANYTHING_UNPAVED.joinToString("|") + ")$\"]" + // not any explicitly tagged as no bicycles "[bicycle != no]" + "[access !~ \"^private|no$\"]" + // some roads may be farther than minDistToCycleways from cycleways, not tagged with // cycleway=separate/sidepath but may have a hint that there is a separately tagged // cycleway "[bicycle != use_sidepath][\"bicycle:backward\" != use_sidepath]" + "[\"bicycle:forward\" != use_sidepath]" + " -> .streets;" + "(" + "way[highway=cycleway](around.streets: " + minDistToCycleways + ");" + // See #718: If a separate way exists, it may be that the user's answer should // correctly be tagged on that separate way and not on the street -> this app would // tag data on the wrong elements. So, don't ask at all for separately mapped ways. // :-( "way[highway ~ \"^(path|footway)$\"](around.streets: " + minDistToCycleways + ");" + ") -> .cycleways;" + "way.streets(around.cycleways: " + minDistToCycleways + ") -> .streets_near_cycleways;" + "(.streets; - .streets_near_cycleways;);" + OverpassQLUtil.getQuestPrintStatement() } override fun createForm() = AddCyclewayForm() override fun applyAnswerTo(answer: CyclewayAnswer, changes: StringMapChangesBuilder) { answer.apply { if (left == right) { left?.let { applyCyclewayAnswerTo(it.cycleway, Side.BOTH, 0, changes) } } else { left?.let { applyCyclewayAnswerTo(it.cycleway, Side.LEFT, it.dirInOneway, changes) } right?.let { applyCyclewayAnswerTo(it.cycleway, Side.RIGHT, it.dirInOneway, changes) } } applySidewalkAnswerTo(left?.cycleway, right?.cycleway, changes) if (isOnewayNotForCyclists) { changes.addOrModify("oneway:bicycle", "no") } } } private fun applySidewalkAnswerTo( cyclewayLeft: Cycleway?, cyclewayRight: Cycleway?, changes: StringMapChangesBuilder ) { val hasSidewalkLeft = cyclewayLeft != null && cyclewayLeft.isOnSidewalk val hasSidewalkRight = cyclewayRight != null && cyclewayRight.isOnSidewalk val side = when { hasSidewalkLeft && hasSidewalkRight -> Side.BOTH hasSidewalkLeft -> Side.LEFT hasSidewalkRight -> Side.RIGHT else -> null } if (side != null) { changes.addOrModify("sidewalk", side.value) } } private enum class Side(val value: String) { LEFT("left"), RIGHT("right"), BOTH("both") } private fun applyCyclewayAnswerTo(cycleway: Cycleway, side: Side, dir: Int, changes: StringMapChangesBuilder ) { val directionValue = when { dir > 0 -> "yes" dir < 0 -> "-1" else -> null } val cyclewayKey = "cycleway:" + side.value when (cycleway) { NONE, NONE_NO_ONEWAY -> { changes.add(cyclewayKey, "no") } EXCLUSIVE_LANE, ADVISORY_LANE, LANE_UNSPECIFIED -> { changes.add(cyclewayKey, "lane") if (directionValue != null) { changes.addOrModify("$cyclewayKey:oneway", directionValue) } if (cycleway == EXCLUSIVE_LANE) changes.addOrModify("$cyclewayKey:lane", "exclusive") else if (cycleway == ADVISORY_LANE) changes.addOrModify("$cyclewayKey:lane","advisory") } TRACK -> { changes.add(cyclewayKey, "track") if (directionValue != null) { changes.addOrModify("$cyclewayKey:oneway", directionValue) } } DUAL_TRACK -> { changes.add(cyclewayKey, "track") changes.addOrModify("$cyclewayKey:oneway", "no") } DUAL_LANE -> { changes.add(cyclewayKey, "lane") changes.addOrModify("$cyclewayKey:oneway", "no") changes.addOrModify("$cyclewayKey:lane", "exclusive") } SIDEWALK_EXPLICIT -> { // https://wiki.openstreetmap.org/wiki/File:Z240GemeinsamerGehundRadweg.jpeg changes.add(cyclewayKey, "track") changes.add("$cyclewayKey:segregated", "no") } SIDEWALK_OK -> { // https://wiki.openstreetmap.org/wiki/File:Z239Z1022-10GehwegRadfahrerFrei.jpeg changes.add(cyclewayKey, "no") changes.add("sidewalk:" + side.value + ":bicycle", "yes") } PICTOGRAMS -> { changes.add(cyclewayKey, "shared_lane") changes.add("$cyclewayKey:lane", "pictogram") } SUGGESTION_LANE -> { changes.add(cyclewayKey, "shared_lane") changes.add("$cyclewayKey:lane", "advisory") } BUSWAY -> { changes.add(cyclewayKey, "share_busway") } } } }
gpl-3.0
2d459d0b1ce5f836286fcadf4cb81662
42.88
124
0.578965
4.416709
false
false
false
false
robfletcher/orca
orca-kayenta/src/main/kotlin/com/netflix/spinnaker/orca/kayenta/pipeline/CleanupCanaryClustersStage.kt
4
4130
/* * Copyright 2018 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.kayenta.pipeline import com.netflix.spinnaker.orca.api.pipeline.graph.StageDefinitionBuilder import com.netflix.spinnaker.orca.api.pipeline.graph.StageGraphBuilder import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution import com.netflix.spinnaker.orca.clouddriver.pipeline.cluster.DisableClusterStage import com.netflix.spinnaker.orca.clouddriver.pipeline.cluster.ShrinkClusterStage import com.netflix.spinnaker.orca.kayenta.ServerGroupSpec import com.netflix.spinnaker.orca.kayenta.cluster import com.netflix.spinnaker.orca.kayenta.deployments import com.netflix.spinnaker.orca.kayenta.regions import com.netflix.spinnaker.orca.pipeline.WaitStage import org.springframework.stereotype.Component @Component class CleanupCanaryClustersStage : StageDefinitionBuilder { companion object { @JvmStatic val STAGE_TYPE = "cleanupCanaryClusters" } override fun beforeStages(parent: StageExecution, graph: StageGraphBuilder) { val deployments = parent.deployments val disableStages = deployments.serverGroupPairs.flatMap { pair -> listOf( graph.add { it.type = DisableClusterStage.STAGE_TYPE it.name = "Disable control cluster ${pair.control.cluster}" it.context.putAll(pair.control.toContext) it.context["remainingEnabledServerGroups"] = 0 // Even if disabling fails, move on to shrink below which will have another go at destroying the server group it.continuePipelineOnFailure = true }, graph.add { it.type = DisableClusterStage.STAGE_TYPE it.name = "Disable experiment cluster ${pair.experiment.cluster}" it.context.putAll(pair.experiment.toContext) it.context["remainingEnabledServerGroups"] = 0 // Even if disabling fails, move on to shrink below which will have another go at destroying the server group it.continuePipelineOnFailure = true } ) } // wait to allow time for manual inspection val waitStage = graph.add { it.type = WaitStage.STAGE_TYPE it.name = "Wait before cleanup" it.context["waitTime"] = deployments.delayBeforeCleanup.seconds } disableStages.forEach { // Continue the stages even if disabling one of the clusters fails - subsequent stages will delete them // but we need to make sure they run it.allowSiblingStagesToContinueOnFailure = true graph.connect(it, waitStage) } deployments.serverGroupPairs.forEach { pair -> // destroy control cluster graph.connect(waitStage) { it.type = ShrinkClusterStage.STAGE_TYPE it.name = "Cleanup control cluster ${pair.control.cluster}" it.context.putAll(pair.control.toContext) it.context["allowDeleteActive"] = true it.context["shrinkToSize"] = 0 it.continuePipelineOnFailure = true } // destroy experiment cluster graph.connect(waitStage) { it.type = ShrinkClusterStage.STAGE_TYPE it.name = "Cleanup experiment cluster ${pair.experiment.cluster}" it.context.putAll(pair.experiment.toContext) it.context["allowDeleteActive"] = true it.context["shrinkToSize"] = 0 it.continuePipelineOnFailure = true } } } private val ServerGroupSpec.toContext get() = mapOf( "cloudProvider" to cloudProvider, "credentials" to account, "cluster" to cluster, "moniker" to moniker, "regions" to regions ) }
apache-2.0
c5a51474e7416f6d19929463a9bd7159
37.598131
119
0.713317
4.479393
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/course_revenue/mapper/RevenuePriceMapper.kt
2
1339
package org.stepik.android.view.course_revenue.mapper import android.content.Context import android.text.SpannedString import androidx.core.text.buildSpannedString import androidx.core.text.scale import org.stepic.droid.R import java.util.Currency import javax.inject.Inject class RevenuePriceMapper @Inject constructor( private val context: Context ) { companion object { private const val RUB_FORMAT = "RUB" } fun mapToDisplayPrice(currencyCode: String, price: String, debitPrefixRequired: Boolean = false): SpannedString = when (currencyCode) { RUB_FORMAT -> { val first = price.substring(0, price.lastIndex - 1) val second = price.takeLast(2) context.getString(R.string.rub_format, price) buildSpannedString { if (debitPrefixRequired) { append("+") } append(first) scale(0.85f) { append(second) append(" ") append(Currency.getInstance(currencyCode).symbol) } } } else -> buildSpannedString { append("$price $currencyCode") } } }
apache-2.0
6a9a5dd12de6abc07574ae0cdbbbf0e3
30.162791
117
0.544436
5.110687
false
false
false
false
mattvchandler/ProgressBars
app/src/main/java/list/Adapter.kt
1
9871
/* Copyright (C) 2020 Matthew Chandler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.mattvchandler.progressbars.list import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.RecyclerView import org.mattvchandler.progressbars.Progress_bars import org.mattvchandler.progressbars.databinding.ProgressBarRowBinding import org.mattvchandler.progressbars.databinding.SingleProgressBarRowBinding import org.mattvchandler.progressbars.db.DB import org.mattvchandler.progressbars.db.Data import org.mattvchandler.progressbars.db.Progress_bars_table import org.mattvchandler.progressbars.settings.Settings import org.mattvchandler.progressbars.util.Notification_handler import java.io.Serializable import java.security.InvalidParameterException private typealias Stack<T> = MutableList<T> private fun <T> Stack<T>.pop(): T { val t = this.last() this.removeAt(this.size - 1) return t } private fun <T> Stack<T>.push(t: T) { this.add(t) } private data class Undo_event(val type: Type, val data: Data?, val pos: Int?, val old_pos: Int?): Serializable { enum class Type{ ADD, REMOVE, EDIT, MOVE } } // keeps track of timer GUI rows class Adapter(private val activity: Progress_bars): RecyclerView.Adapter<Adapter.Holder>() { private val data_list = mutableListOf<View_data>() private val undo_stack: Stack<Undo_event> = mutableListOf() private val redo_stack: Stack<Undo_event> = mutableListOf() private var moved_from_pos = 0 // an individual row object inner class Holder(private val row_binding: ViewDataBinding): RecyclerView.ViewHolder(row_binding.root), View.OnClickListener { internal lateinit var data: View_data fun bind(data: View_data) { this.data = data when(row_binding) { is ProgressBarRowBinding -> row_binding.data = data is SingleProgressBarRowBinding -> row_binding.data = data } } fun update() = data.update_display(activity.resources) // click the row to edit its data override fun onClick(v: View) { // create and launch an intent to launch the editor val intent = Intent(activity, Settings::class.java) intent.putExtra(Settings.EXTRA_EDIT_DATA, data) activity.startActivityForResult(intent, Progress_bars.RESULT_EDIT_DATA) } } init { setHasStableIds(true) val db = DB(activity).readableDatabase val cursor = db.rawQuery(Progress_bars_table.SELECT_ALL_ROWS_NO_WIDGET, null) cursor.moveToFirst() for(i in 0 until cursor.count) { add_item(Data(cursor), i) cursor.moveToNext() } cursor.close() db.close() } override fun onCreateViewHolder(parent_in: ViewGroup, viewType: Int): Holder { // create a new row val inflater = LayoutInflater.from(activity) val row_binding = when(viewType) { SEPARATE_TIME_VIEW -> ProgressBarRowBinding.inflate(inflater, parent_in, false) SINGLE_TIME_VIEW -> SingleProgressBarRowBinding.inflate(inflater, parent_in, false) else -> throw(InvalidParameterException("Unknown viewType: $viewType")) } val holder = Holder(row_binding) row_binding.root.setOnClickListener(holder) return holder } override fun onBindViewHolder(holder: Holder, position: Int) { // move to the requested position and bind the data holder.bind(data_list[position]) } override fun getItemViewType(position: Int): Int { return if(data_list[position].separate_time) SEPARATE_TIME_VIEW else SINGLE_TIME_VIEW } override fun getItemId(position: Int) = data_list[position].id.toLong() override fun getItemCount() = data_list.size fun find_by_id(id: Int) = data_list.indexOfFirst{ it.id == id} fun apply_repeat(id: Int) { val pos = find_by_id(id) if(pos < 0) return data_list[pos].update_alarms(activity) data_list[pos].reinit(activity) } // called when a row is deleted fun on_item_dismiss(pos: Int) { redo_stack.clear() undo_stack.push(Undo_event(Undo_event.Type.REMOVE, Data(data_list[pos]), pos, null)) activity.invalidateOptionsMenu() remove_item(pos) } // called when a row is selected for deletion or reordering fun on_selected(pos: Int) { moved_from_pos = pos } // called when a row is released from reordering fun on_cleared(pos: Int) { if(pos != RecyclerView.NO_POSITION && pos != moved_from_pos) { redo_stack.clear() undo_stack.push(Undo_event(Undo_event.Type.MOVE, null, pos, moved_from_pos)) activity.invalidateOptionsMenu() } } fun set_edited(data: Data) { redo_stack.clear() var pos = find_by_id(data.id) if(pos >= 0) { undo_stack.push(Undo_event(Undo_event.Type.EDIT, Data(data_list[pos]), pos, null)) edit_item(data, pos) } else { pos = data_list.size add_item(data, pos) activity.scroll_to(pos) undo_stack.push(Undo_event(Undo_event.Type.ADD, null, pos, null)) } activity.invalidateOptionsMenu() } private fun add_item(data: Data, pos: Int) { data.register_alarms(activity) data_list.add(pos, View_data(activity, data)) notifyItemInserted(pos) } private fun edit_item(data: Data, pos: Int) { data.update_alarms(activity) data_list[pos] = View_data(activity, data) notifyItemChanged(pos) } private fun remove_item(pos: Int) { data_list[pos].unregister_alarms(activity) Notification_handler.cancel_alarm(activity, data_list[pos]) data_list.removeAt(pos) notifyItemRemoved(pos) } fun move_item(from_pos: Int, to_pos: Int) { val moved = data_list.removeAt(from_pos) data_list.add(to_pos, moved) notifyItemMoved(from_pos, to_pos) } fun can_undo() = undo_stack.isNotEmpty() fun can_redo() = redo_stack.isNotEmpty() fun undo() = undo_redo(undo_stack, redo_stack) fun redo() = undo_redo(redo_stack, undo_stack) private fun undo_redo(stack: Stack<Undo_event>, inverse_stack: Stack<Undo_event>) { if(stack.isEmpty()) return val event = stack.pop() when(event.type) { Undo_event.Type.ADD -> { inverse_stack.push(Undo_event(Undo_event.Type.REMOVE, Data(data_list[event.pos!!]), event.pos, null)) remove_item(event.pos) } Undo_event.Type.REMOVE -> { inverse_stack.push(Undo_event(Undo_event.Type.ADD, null, event.pos, null)) add_item(event.data!!, event.pos!!) } Undo_event.Type.EDIT -> { inverse_stack.push(Undo_event(Undo_event.Type.EDIT, Data(data_list[event.pos!!]), event.pos, null)) edit_item(event.data!!, event.pos) } Undo_event.Type.MOVE -> { inverse_stack.push(Undo_event(Undo_event.Type.MOVE, null, event.old_pos!!, event.pos!!)) move_item(event.pos, event.old_pos) } } activity.invalidateOptionsMenu() } var undo_redo_stacks get() = Pair(undo_stack, redo_stack) as Serializable set(stack_pair) { val (new_undo_stack, new_redo_stack) = stack_pair as Pair<*, *> undo_stack.clear() redo_stack.clear() @Suppress("UNCHECKED_CAST") undo_stack.addAll(new_undo_stack as Stack<Undo_event>) @Suppress("UNCHECKED_CAST") redo_stack.addAll(new_redo_stack as Stack<Undo_event>) } fun save_to_db() { val db = DB(activity).writableDatabase db.beginTransaction() try { db.delete(Progress_bars_table.TABLE_NAME, "${Progress_bars_table.ORDER_COL} IS NOT NULL", null) for(i in 0 until data_list.size) { data_list[i].order_ind = i data_list[i].insert(db) } db.setTransactionSuccessful() } finally { db.endTransaction() db.close() } } companion object { private const val SEPARATE_TIME_VIEW = 0 private const val SINGLE_TIME_VIEW = 1 } }
mit
12cefa22f82551e3baa6d9411ec17ce5
30.536741
129
0.625266
4.092454
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerViewerAdapter.kt
1
7141
package eu.kanade.tachiyomi.ui.reader.viewer.pager import android.view.View import android.view.ViewGroup import eu.kanade.tachiyomi.ui.reader.model.ChapterTransition import eu.kanade.tachiyomi.ui.reader.model.InsertPage import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.ui.reader.model.ViewerChapters import eu.kanade.tachiyomi.ui.reader.viewer.hasMissingChapters import eu.kanade.tachiyomi.util.system.createReaderThemeContext import eu.kanade.tachiyomi.util.system.logcat import eu.kanade.tachiyomi.widget.ViewPagerAdapter /** * Pager adapter used by this [viewer] to where [ViewerChapters] updates are posted. */ class PagerViewerAdapter(private val viewer: PagerViewer) : ViewPagerAdapter() { /** * List of currently set items. */ var items: MutableList<Any> = mutableListOf() private set /** * Holds preprocessed items so they don't get removed when changing chapter */ private var preprocessed: MutableMap<Int, InsertPage> = mutableMapOf() var nextTransition: ChapterTransition.Next? = null private set var currentChapter: ReaderChapter? = null /** * Context that has been wrapped to use the correct theme values based on the * current app theme and reader background color */ private var readerThemedContext = viewer.activity.createReaderThemeContext() /** * Updates this adapter with the given [chapters]. It handles setting a few pages of the * next/previous chapter to allow seamless transitions and inverting the pages if the viewer * has R2L direction. */ fun setChapters(chapters: ViewerChapters, forceTransition: Boolean) { val newItems = mutableListOf<Any>() // Forces chapter transition if there is missing chapters val prevHasMissingChapters = hasMissingChapters(chapters.currChapter, chapters.prevChapter) val nextHasMissingChapters = hasMissingChapters(chapters.nextChapter, chapters.currChapter) // Add previous chapter pages and transition. if (chapters.prevChapter != null) { // We only need to add the last few pages of the previous chapter, because it'll be // selected as the current chapter when one of those pages is selected. val prevPages = chapters.prevChapter.pages if (prevPages != null) { newItems.addAll(prevPages.takeLast(2)) } } // Skip transition page if the chapter is loaded & current page is not a transition page if (prevHasMissingChapters || forceTransition || chapters.prevChapter?.state !is ReaderChapter.State.Loaded) { newItems.add(ChapterTransition.Prev(chapters.currChapter, chapters.prevChapter)) } var insertPageLastPage: InsertPage? = null // Add current chapter. val currPages = chapters.currChapter.pages if (currPages != null) { val pages = currPages.toMutableList() val lastPage = pages.last() // Insert preprocessed pages into current page list preprocessed.keys.sortedDescending() .forEach { key -> if (lastPage.index == key) { insertPageLastPage = preprocessed[key] } preprocessed[key]?.let { pages.add(key + 1, it) } } newItems.addAll(pages) } currentChapter = chapters.currChapter // Add next chapter transition and pages. nextTransition = ChapterTransition.Next(chapters.currChapter, chapters.nextChapter) .also { if (nextHasMissingChapters || forceTransition || chapters.nextChapter?.state !is ReaderChapter.State.Loaded ) { newItems.add(it) } } if (chapters.nextChapter != null) { // Add at most two pages, because this chapter will be selected before the user can // swap more pages. val nextPages = chapters.nextChapter.pages if (nextPages != null) { newItems.addAll(nextPages.take(2)) } } // Resets double-page splits, else insert pages get misplaced items.filterIsInstance<InsertPage>().also { items.removeAll(it) } if (viewer is R2LPagerViewer) { newItems.reverse() } preprocessed = mutableMapOf() items = newItems notifyDataSetChanged() // Will skip insert page otherwise if (insertPageLastPage != null) { viewer.moveToPage(insertPageLastPage!!) } } /** * Returns the amount of items of the adapter. */ override fun getCount(): Int { return items.size } /** * Creates a new view for the item at the given [position]. */ override fun createView(container: ViewGroup, position: Int): View { return when (val item = items[position]) { is ReaderPage -> PagerPageHolder(readerThemedContext, viewer, item) is ChapterTransition -> PagerTransitionHolder(readerThemedContext, viewer, item) else -> throw NotImplementedError("Holder for ${item.javaClass} not implemented") } } /** * Returns the current position of the given [view] on the adapter. */ override fun getItemPosition(view: Any): Int { if (view is PositionableView) { val position = items.indexOf(view.item) if (position != -1) { return position } else { logcat { "Position for ${view.item} not found" } } } return POSITION_NONE } fun onPageSplit(currentPage: Any?, newPage: InsertPage) { if (currentPage !is ReaderPage) return val currentIndex = items.indexOf(currentPage) // Put aside preprocessed pages for next chapter so they don't get removed when changing chapter if (currentPage.chapter.chapter.id != currentChapter?.chapter?.id) { preprocessed[newPage.index] = newPage return } val placeAtIndex = when (viewer) { is L2RPagerViewer, is VerticalPagerViewer, -> currentIndex + 1 else -> currentIndex } // It will enter a endless cycle of insert pages if (viewer is R2LPagerViewer && placeAtIndex - 1 >= 0 && items[placeAtIndex - 1] is InsertPage) { return } // Same here it will enter a endless cycle of insert pages if (items[placeAtIndex] is InsertPage) { return } items.add(placeAtIndex, newPage) notifyDataSetChanged() } fun cleanupPageSplit() { val insertPages = items.filterIsInstance(InsertPage::class.java) items.removeAll(insertPages) notifyDataSetChanged() } fun refresh() { readerThemedContext = viewer.activity.createReaderThemeContext() } }
apache-2.0
f6fb41b30dc46bf56ff72edd2b73860e
34.17734
118
0.629744
4.948718
false
false
false
false
pambrose/prometheus-proxy
src/test/kotlin/io/prometheus/InProcessTestNoAdminMetricsTest.kt
1
1590
/* * Copyright © 2020 Paul Ambrose ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction") package io.prometheus import com.github.pambrose.common.util.simpleClassName import io.prometheus.TestConstants.DEFAULT_CHUNK_SIZE import io.prometheus.TestConstants.DEFAULT_TIMEOUT import io.prometheus.TestUtils.startAgent import io.prometheus.TestUtils.startProxy import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll class InProcessTestNoAdminMetricsTest : CommonTests(ProxyCallTestArgs(agent = agent, startPort = 10100, caller = simpleClassName)) { companion object : CommonCompanion() { @JvmStatic @BeforeAll fun setUp() = setItUp( { startProxy("nometrics") }, { startAgent( serverName = "nometrics", scrapeTimeoutSecs = DEFAULT_TIMEOUT, chunkContentSizeKbs = DEFAULT_CHUNK_SIZE ) } ) @JvmStatic @AfterAll fun takeDown() = takeItDown() } }
apache-2.0
3572800f2c0a7baef52a18b1c87efe92
30.8
94
0.715544
4.271505
false
true
false
false
k9mail/k-9
app/core/src/main/java/com/fsck/k9/message/html/HtmlConverter.kt
1
1761
package com.fsck.k9.message.html import org.jsoup.Jsoup /** * Contains common routines to convert html to text and vice versa. */ object HtmlConverter { /** * When generating previews, Spannable objects that can't be converted into a String are * represented as 0xfffc. When displayed, these show up as undisplayed squares. These constants * define the object character and the replacement character. */ private const val PREVIEW_OBJECT_CHARACTER = 0xfffc.toChar() private const val PREVIEW_OBJECT_REPLACEMENT = 0x20.toChar() // space /** * toHtml() converts non-breaking spaces into the UTF-8 non-breaking space, which doesn't get * rendered properly in some clients. Replace it with a simple space. */ private const val NBSP_CHARACTER = 0x00a0.toChar() // utf-8 non-breaking space private const val NBSP_REPLACEMENT = 0x20.toChar() // space /** * Convert an HTML string to a plain text string. */ @JvmStatic fun htmlToText(html: String): String { val document = Jsoup.parse(html) return HtmlToPlainText.toPlainText(document.body()) .replace(PREVIEW_OBJECT_CHARACTER, PREVIEW_OBJECT_REPLACEMENT) .replace(NBSP_CHARACTER, NBSP_REPLACEMENT) } /** * Convert a text string into an HTML document. * * No HTML headers or footers are added to the result. Headers and footers are added at display time. */ @JvmStatic fun textToHtml(text: String): String { return EmailTextToHtml.convert(text) } /** * Convert a plain text string into an HTML fragment. */ @JvmStatic fun textToHtmlFragment(text: String): String { return TextToHtml.toHtmlFragment(text) } }
apache-2.0
6559395962928430d2cceff02726d736
32.865385
106
0.674617
4.284672
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/FirstEntityWithPIdImpl.kt
2
5874
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class FirstEntityWithPIdImpl: FirstEntityWithPId, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _data: String? = null override val data: String get() = _data!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: FirstEntityWithPIdData?): ModifiableWorkspaceEntityBase<FirstEntityWithPId>(), FirstEntityWithPId.Builder { constructor(): this(FirstEntityWithPIdData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity FirstEntityWithPId is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isDataInitialized()) { error("Field FirstEntityWithPId#data should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field FirstEntityWithPId#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): FirstEntityWithPIdData = result ?: super.getEntityData() as FirstEntityWithPIdData override fun getEntityClass(): Class<FirstEntityWithPId> = FirstEntityWithPId::class.java } } class FirstEntityWithPIdData : WorkspaceEntityData.WithCalculablePersistentId<FirstEntityWithPId>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<FirstEntityWithPId> { val modifiable = FirstEntityWithPIdImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): FirstEntityWithPId { val entity = FirstEntityWithPIdImpl() entity._data = data entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun persistentId(): PersistentEntityId<*> { return FirstPId(data) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return FirstEntityWithPId::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as FirstEntityWithPIdData if (this.data != other.data) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as FirstEntityWithPIdData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } }
apache-2.0
ab1e36e5b2fbdbc1761e9f51abc13c64
33.763314
137
0.649983
6.170168
false
false
false
false
PolymerLabs/arcs
java/arcs/core/util/performance/Timer.kt
1
2399
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.util.performance import arcs.core.util.TaggedLog import arcs.core.util.Time /** A [Timer] times the execution of an operation. */ class Timer(val time: Time) { val logger = TaggedLog { "Timer" } /** Times the execution of the given [block]. */ inline fun <T> time(crossinline block: () -> T): TimedResult<T> { val startTime = time.nanoTime val endTime: Long val result = try { block() } finally { endTime = time.nanoTime } return TimedResult( result, endTime - startTime ) } /** Times the exeuction of the given suspending [block]. */ @Suppress("REDUNDANT_INLINE_SUSPEND_FUNCTION_TYPE") // It's not redundant. suspend inline fun <T> timeSuspending(block: suspend () -> T): TimedResult<T> { val startTime = time.nanoTime val endTime: Long val result = try { block() } finally { endTime = time.nanoTime } return TimedResult( result, endTime - startTime ) } /** * Times the execution of the given [block], and both logs the result and records it in * [TimingMeasurements]. */ inline fun <T> timeAndLog(metric: String, crossinline block: () -> T): T { val result = time(block) val timeMs = result.elapsedNanos / 1_000_000 logger.info { "$metric: $timeMs" } TimingMeasurements.record(metric, timeMs) return result.result } /** * Times the execution of the given [block], and both logs the result and records it in * [TimingMeasurements]. */ @Suppress("REDUNDANT_INLINE_SUSPEND_FUNCTION_TYPE") // It's not redundant. suspend inline fun <T> timeAndLogSuspending(metric: String, block: suspend () -> T): T { val result = timeSuspending(block) val timeMs = result.elapsedNanos / 1_000_000 logger.info { "$metric: $timeMs" } TimingMeasurements.record(metric, timeMs) return result.result } } /** * Wrapper for the result of a timed operation, along with the total elapsed milliseconds required * for the operation. */ data class TimedResult<T>(val result: T, val elapsedNanos: Long)
bsd-3-clause
8398e36469f313b842780d6f939d390d
28.256098
98
0.666111
3.965289
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/layers/recurrent/deltarnn/DeltaRNNLayerStructureSpec.kt
1
30471
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.layers.recurrent.deltarnn import com.kotlinnlp.simplednn.core.arrays.DistributionArray import com.kotlinnlp.simplednn.core.layers.models.recurrent.LayersWindow import com.kotlinnlp.simplednn.core.layers.models.recurrent.deltarnn.DeltaRNNLayerParameters import com.kotlinnlp.simplednn.core.optimizer.getErrorsOf import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertFailsWith import kotlin.test.assertNull import kotlin.test.assertTrue /** * */ class DeltaRNNLayerStructureSpec : Spek({ describe("a DeltaRNNLayer") { context("forward") { context("without previous state context") { val layer = DeltaRNNLayerStructureUtils.buildLayer(DeltaLayersWindow.Empty) layer.forward() it("should match the expected candidate") { assertTrue { layer.candidate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.568971, 0.410323, -0.39693, 0.648091, -0.449441)), tolerance = 1.0e-06) } } it("should match the expected partition array") { assertTrue { layer.partition.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.519989, 0.169384, 0.668188, 0.325195, 0.601088)), tolerance = 1.0e-06) } } it("should match the expected output") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.287518, 0.06939, -0.259175, 0.20769, -0.263768)), tolerance = 1.0e-06) } } } context("with previous state context") { val layer = DeltaRNNLayerStructureUtils.buildLayer(DeltaLayersWindow.Back) layer.forward() it("should match the expected candidate") { assertTrue { layer.candidate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.576403, 0.40594, -0.222741, 0.36182, -0.42253)), tolerance = 1.0e-06) } } it("should match the expected partition array") { assertTrue { layer.partition.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.519989, 0.169384, 0.668188, 0.325195, 0.601088)), tolerance = 1.0e-06) } } it("should match the expected output") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.202158, 0.228591, -0.240679, -0.350224, -0.476828)), tolerance = 1.0e-06) } } } } context("forward with relevance") { context("without previous state context") { val layer = DeltaRNNLayerStructureUtils.buildLayer(DeltaLayersWindow.Empty) val contributions = DeltaRNNLayerParameters( inputSize = 4, outputSize = 5, weightsInitializer = null, biasesInitializer = null) layer.forward(contributions) it("should match the expected candidate") { assertTrue { layer.candidate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.568971, 0.410323, -0.39693, 0.648091, -0.449441)), tolerance = 1.0e-06) } } it("should match the expected partition array") { assertTrue { layer.partition.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.519989, 0.169384, 0.668188, 0.325195, 0.601088)), tolerance = 1.0e-06) } } it("should match the expected output") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.287518, 0.06939, -0.259175, 0.20769, -0.263768)), tolerance = 1.0e-06) } } it("should match the expected contributions of the input") { val inputContrib: DenseNDArray = contributions.feedforwardUnit.weights.values assertTrue { inputContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.4, -0.54, 0.72, -0.6), doubleArrayOf(-0.56, 0.36, -0.09, -0.8), doubleArrayOf(-0.56, 0.63, -0.27, 0.5), doubleArrayOf(-0.64, 0.81, 0.0, -0.1), doubleArrayOf(-0.32, -0.9, 0.63, 0.8) )), tolerance = 1.0e-06) } } it("should match the expected recurrent contributions") { val recContrib: DenseNDArray = contributions.recurrentUnit.weights.values assertTrue { recContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0), doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0) )), tolerance = 1.0e-06) } } layer.setOutputRelevance(DistributionArray.uniform(length = 5)) layer.propagateRelevanceToGates(contributions) layer.setInputRelevance(contributions) it("should match the expected relevance of the partition array") { val relevance: DenseNDArray = layer.partition.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.1, 0.1, 0.1, 0.1)), tolerance = 1.0e-06) } } it("should match the expected relevance of the candidate") { val relevance: DenseNDArray = layer.candidate.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.1, 0.1, 0.1, 0.1)), tolerance = 1.0e-06) } } it("should match the expected relevance of the d1 input array") { val relevance: DenseNDArray = layer.relevanceSupport.d1Input.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.1, 0.1, 0.1, 0.1)), tolerance = 1.0e-06) } } it("should match the expected input relevance") { val relevance: DenseNDArray = layer.inputArray.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.058871, -0.524906, 1.314539, 0.269238)), tolerance = 1.0e-06) } } it("should throw an Exception when calculating the recurrent relevance") { assertFailsWith <KotlinNullPointerException> { layer.setRecurrentRelevance(contributions) } } } context("with previous state context") { val prevStateLayer = DeltaLayersWindow.Back.getPrevState() val contextWindow = mock<LayersWindow>() val layer = DeltaRNNLayerStructureUtils.buildLayer(contextWindow) val contributions = DeltaRNNLayerParameters(inputSize = 4, outputSize = 5) whenever(contextWindow.getPrevState()).thenReturn(prevStateLayer) layer.forward(contributions) it("should match the expected candidate") { assertTrue { layer.candidate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.576403, 0.40594, -0.222741, 0.36182, -0.42253)), tolerance = 1.0e-06) } } it("should match the expected partition array") { assertTrue { layer.partition.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.519989, 0.169384, 0.668188, 0.325195, 0.601088)), tolerance = 1.0e-06) } } it("should match the expected output") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.202158, 0.228591, -0.240679, -0.350224, -0.476828)), tolerance = 1.0e-06) } } it("should match the expected contributions of the input") { val inputContrib: DenseNDArray = contributions.feedforwardUnit.weights.values assertTrue { inputContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.4, -0.54, 0.72, -0.6), doubleArrayOf(-0.56, 0.36, -0.09, -0.8), doubleArrayOf(-0.56, 0.63, -0.27, 0.5), doubleArrayOf(-0.64, 0.81, 0.0, -0.1), doubleArrayOf(-0.32, -0.9, 0.63, 0.8) )), tolerance = 1.0e-06) } } it("should match the expected recurrent contributions") { val recContrib: DenseNDArray = contributions.recurrentUnit.weights.values assertTrue { recContrib.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0, 0.1579, -0.23305, 0.716298, 0.464826), doubleArrayOf(0.138163, -0.1579, -0.058263, 0.501409, -0.464826), doubleArrayOf(0.177638, 0.177638, -0.203919, 0.358149, -0.332018), doubleArrayOf(0.0, -0.019738, -0.145656, 0.14326, 0.531229), doubleArrayOf(0.118425, 0.118425, -0.23305, 0.07163, 0.199211) )), tolerance = 1.0e-06) } } layer.setOutputRelevance(DistributionArray.uniform(length = 5)) layer.propagateRelevanceToGates(contributions) layer.setInputRelevance(contributions) layer.setRecurrentRelevance(contributions) it("should match the expected relevance of the partition array") { val relevance: DenseNDArray = layer.partition.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, 0.1, 0.1, 0.1, 0.1)), tolerance = 1.0e-06) } } it("should match the expected relevance of the candidate") { val relevance: DenseNDArray = layer.candidate.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.151155, 0.030391, 0.06021, -0.029987, 0.048968)), tolerance = 1.0e-06) } } it("should match the expected relevance of the d1 input array") { val relevance: DenseNDArray = layer.relevanceSupport.d1Input.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.101818, 0.031252, 0.074148, -0.028935, 0.031181)), tolerance = 1.0e-06) } } it("should match the expected relevance of the d1 recurrent array") { val relevance: DenseNDArray = layer.relevanceSupport.d1Rec.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.05417, 0.000358, -0.00857, 0.000304, 0.018798)), tolerance = 1.0e-06) } } it("should match the expected relevance of the d2 array") { val relevance: DenseNDArray = layer.relevanceSupport.d2.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.103506, -0.001219, -0.005368, -0.001356, -0.001011)), tolerance = 1.0e-06) } } it("should match the expected input relevance") { val relevance: DenseNDArray = layer.inputArray.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.156729, -0.419269, 1.161411, 0.171329)), tolerance = 1.0e-06) } } it("should match the expected recurrent relevance") { val relevance: DenseNDArray = prevStateLayer.outputArray.relevance assertTrue { relevance.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.077057, 0.03487, 0.116601, 0.037238, 0.131607)), tolerance = 1.0e-06) } } } } context("backward") { context("without previous and next state") { val layer = DeltaRNNLayerStructureUtils.buildLayer(DeltaLayersWindow.Empty) layer.forward() layer.outputArray.assignErrors(layer.outputArray.values.sub(DeltaRNNLayerStructureUtils.getOutputGold())) val paramsErrors = layer.backward(propagateToInput = true) val params = layer.params it("should match the expected errors of the outputArray") { assertTrue { layer.outputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.25913, -0.677332, -0.101842, -1.370527, -0.664109)), tolerance = 1.0e-06) } } it("should match the expected errors of the candidate array") { assertTrue { layer.candidate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.091124, -0.095413, -0.057328, -0.258489, -0.318553)), tolerance = 1.0e-06) } } it("should match the expected errors of the partition array") { assertTrue { layer.partition.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.0368, -0.039102, 0.008963, -0.194915, 0.071569)), tolerance = 1.0e-06) } } it("should match the expected errors of the candidate biases") { assertTrue { paramsErrors.getErrorsOf(params.feedforwardUnit.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.091124, -0.095413, -0.057328, -0.258489, -0.318553)), tolerance = 1.0e-06) } } it("should match the expected errors of the partition biases") { assertTrue { paramsErrors.getErrorsOf(params.recurrentUnit.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.0368, -0.039102, 0.008963, -0.194915, 0.071569)), tolerance = 1.0e-06) } } it("should match the expected errors of the alpha array") { assertTrue { paramsErrors.getErrorsOf(params.alpha)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)), tolerance = 1.0e-06) } } it("should match the expected errors of the beta1 array") { assertTrue { paramsErrors.getErrorsOf(params.beta1)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.074722, 0.104, -0.017198, -0.018094, -0.066896)), tolerance = 1.0e-06) } } it("should match the expected errors of the beta2 array") { assertTrue { paramsErrors.getErrorsOf(params.beta2)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)), tolerance = 1.0e-06) } } it("should match the expected errors of the weights") { assertTrue { (paramsErrors.getErrorsOf(params.feedforwardUnit.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.007571, 0.008517, 0.008517, -0.009463), doubleArrayOf(0.00075, 0.000843, 0.000843, -0.000937), doubleArrayOf(-0.025515, -0.028704, -0.028704, 0.031894), doubleArrayOf(0.073215, 0.082367, 0.082367, -0.091519), doubleArrayOf(-0.159192, -0.179091, -0.179091, 0.19899) )), tolerance = 1.0e-06) } } it("should match the expected errors of the recurrent weights") { assertNull(paramsErrors.getErrorsOf(params.recurrentUnit.weights)) } it("should match the expected errors of the inputArray") { assertTrue { layer.inputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.023319, 0.253729, -0.122248, 0.190719)), tolerance = 1.0e-06) } } } context("with previous state only") { val layer = DeltaRNNLayerStructureUtils.buildLayer(DeltaLayersWindow.Back) layer.forward() layer.outputArray.assignErrors(layer.outputArray.values.sub(DeltaRNNLayerStructureUtils.getOutputGold())) val paramsErrors = layer.backward(propagateToInput = true) val params = layer.params it("should match the expected errors of the outputArray") { assertTrue { layer.outputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.352809, -0.494163, -0.085426, -1.746109, -0.7161)), tolerance = 1.0e-06) } } it("should match the expected errors of the candidate array") { assertTrue { layer.candidate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.122505, -0.06991, -0.054249, -0.493489, -0.353592)), tolerance = 1.0e-06) } } it("should match the expected errors of the partition array") { assertTrue { layer.partition.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.06814, -0.0145, -0.001299, -0.413104, -0.041468)), tolerance = 1.0e-06) } } it("should match the expected errors of the candidate biases") { assertTrue { paramsErrors.getErrorsOf(params.feedforwardUnit.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.122505, -0.06991, -0.054249, -0.493489, -0.353592)), tolerance = 1.0e-06) } } it("should match the expected errors of the partition biases") { assertTrue { paramsErrors.getErrorsOf(params.recurrentUnit.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.06814, -0.0145, -0.001299, -0.413104, -0.041468)), tolerance = 1.0e-06) } } it("should match the expected errors of the alpha array") { assertTrue { paramsErrors.getErrorsOf(params.alpha)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1111, -0.003156, -0.002889, -0.017586, -0.020393)), tolerance = 1.0e-06) } } it("should match the expected errors of the beta1 array") { assertTrue { paramsErrors.getErrorsOf(params.beta1)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.100454, 0.076202, -0.016275, -0.034544, -0.074254)), tolerance = 1.0e-06) } } it("should match the expected errors of the beta2 array") { assertTrue { paramsErrors.getErrorsOf(params.beta2)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.135487, 0.002895, -0.009628, -0.251233, -0.097111)), tolerance = 1.0e-06) } } it("should match the expected errors of the weights") { assertTrue { (paramsErrors.getErrorsOf(params.feedforwardUnit.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.029084, -0.03272, -0.03272, 0.036355), doubleArrayOf(-0.010076, -0.011335, -0.011335, 0.012595), doubleArrayOf(-0.01401, -0.015761, -0.015761, 0.017512), doubleArrayOf(0.252961, 0.284582, 0.284582, -0.316202), doubleArrayOf(-0.072206, -0.081232, -0.081232, 0.090257) )), tolerance = 1.0e-06) } } it("should match the expected errors of the recurrent weights") { val wRec: DenseNDArray = paramsErrors.getErrorsOf(params.recurrentUnit.weights)!!.values as DenseNDArray assertTrue { wRec.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.000242, -0.000242, 0.000357, 0.000878, 0.000813), doubleArrayOf(0.001752, -0.001752, 0.002586, 0.00636, 0.005896), doubleArrayOf(0.011671, -0.011671, 0.017226, 0.042355, 0.039265), doubleArrayOf(-0.075195, 0.075195, -0.110982, -0.272891, -0.252981), doubleArrayOf(0.008445, -0.008445, 0.012464, 0.030647, 0.028411) )), tolerance = 1.0e-06) } } it("should match the expected errors of the inputArray") { assertTrue { layer.inputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.177606, 0.379355, -0.085751, 0.080693)), tolerance = 1.0e-06) } } } context("with next state only") { val layer = DeltaRNNLayerStructureUtils.buildLayer(DeltaLayersWindow.Front) layer.forward() layer.outputArray.assignErrors(layer.outputArray.values.sub(DeltaRNNLayerStructureUtils.getOutputGold())) val paramsErrors = layer.backward(propagateToInput = true) val params = layer.params it("should match the expected errors of the outputArray") { assertTrue { layer.outputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.075296, -0.403656, -0.191953, -0.383426, -0.699093)), tolerance = 1.0e-06) } } it("should match the expected errors of the candidate array") { assertTrue { layer.candidate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.026478, -0.056861, -0.108053, -0.072316, -0.335333)), tolerance = 1.0e-06) } } it("should match the expected errors of the partition array") { assertTrue { layer.partition.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.010693, -0.023303, 0.016893, -0.05453, 0.07534)), tolerance = 1.0e-06) } } it("should match the expected errors of the candidate biases") { assertTrue { paramsErrors.getErrorsOf(params.feedforwardUnit.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.026478, -0.056861, -0.108053, -0.072316, -0.335333)), tolerance = 1.0e-06) } } it("should match the expected errors of the partition biases") { assertTrue { paramsErrors.getErrorsOf(params.recurrentUnit.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.010693, -0.023303, 0.016893, -0.05453, 0.07534)), tolerance = 1.0e-06) } } it("should match the expected errors of the alpha array") { assertTrue { paramsErrors.getErrorsOf(params.alpha)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)), tolerance = 1.0e-06) } } it("should match the expected errors of the beta1 array") { assertTrue { paramsErrors.getErrorsOf(params.beta1)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.021712, 0.061979, -0.032416, -0.005062, -0.07042)), tolerance = 1.0e-06) } } it("should match the expected errors of the beta2 array") { assertTrue { paramsErrors.getErrorsOf(params.beta2)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0)), tolerance = 1.0e-06) } } it("should match the expected errors of the weights") { assertTrue { (paramsErrors.getErrorsOf(params.feedforwardUnit.weights)!!.values as DenseNDArray).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.0022, 0.002475, 0.002475, -0.00275), doubleArrayOf(0.000447, 0.000503, 0.000503, -0.000558), doubleArrayOf(-0.048091, -0.054102, -0.054102, 0.060114), doubleArrayOf(0.020483, 0.023044, 0.023044, -0.025604), doubleArrayOf(-0.167578, -0.188526, -0.188526, 0.209473) )), tolerance = 1.0e-06) } } it("should match the expected errors of the recurrent weights") { assertNull(paramsErrors.getErrorsOf(params.recurrentUnit.weights)) } it("should match the expected errors of the inputArray") { assertTrue { layer.inputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.10362, 0.18901, -0.126453, 0.202292)), tolerance = 1.0e-06) } } } context("with previous and next state") { val layer = DeltaRNNLayerStructureUtils.buildLayer(DeltaLayersWindow.Bilateral) layer.forward() layer.outputArray.assignErrors(layer.outputArray.values.sub(DeltaRNNLayerStructureUtils.getOutputGold())) val paramsErrors = layer.backward(propagateToInput = true) val params = layer.params it("should match the expected errors of the outputArray") { assertTrue { layer.outputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.160599, -0.233533, -0.17643, -0.841042, -0.745151)), tolerance = 1.0e-06) } } it("should match the expected errors of the candidate array") { assertTrue { layer.candidate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.055764, -0.033038, -0.11204, -0.237697, -0.367937)), tolerance = 1.0e-06) } } it("should match the expected errors of the partition array") { assertTrue { layer.partition.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.031017, -0.006853, -0.002682, -0.198978, -0.043151)), tolerance = 1.0e-06) } } it("should match the expected errors of the candidate biases") { assertTrue { paramsErrors.getErrorsOf(params.feedforwardUnit.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.055764, -0.033038, -0.11204, -0.237697, -0.367937)), tolerance = 1.0e-06) } } it("should match the expected errors of the partition biases") { assertTrue { paramsErrors.getErrorsOf(params.recurrentUnit.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.031017, -0.006853, -0.002682, -0.198978, -0.043151)), tolerance = 1.0e-06) } } it("should match the expected errors of the alpha array") { assertTrue { paramsErrors.getErrorsOf(params.alpha)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.050573, -0.001492, -0.005966, -0.008471, -0.021221)), tolerance = 1.0e-06) } } it("should match the expected errors of the beta1 array") { assertTrue { paramsErrors.getErrorsOf(params.beta1)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.045727, 0.036012, -0.033612, -0.016639, -0.077267)), tolerance = 1.0e-06) } } it("should match the expected errors of the beta2 array") { assertTrue { paramsErrors.getErrorsOf(params.beta2)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.061674, 0.001368, -0.019886, -0.121011, -0.10105)), tolerance = 1.0e-06) } } it("should match the expected errors of the weights") { assertTrue { (paramsErrors.getErrorsOf(params.feedforwardUnit.weights)!!.values).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.013239, -0.014894, -0.014894, 0.016549), doubleArrayOf(-0.004762, -0.005357, -0.005357, 0.005952), doubleArrayOf(-0.028934, -0.032551, -0.032551, 0.036168), doubleArrayOf(0.121843, 0.137073, 0.137073, -0.152304), doubleArrayOf(-0.075135, -0.084527, -0.084527, 0.093919) )), tolerance = 1.0e-06) } } it("should match the expected errors of the recurrent weights") { val wRec: DenseNDArray = paramsErrors.getErrorsOf(params.recurrentUnit.weights)!!.values as DenseNDArray assertTrue { wRec.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.00011, -0.00011, 0.000162, 0.000399, 0.000370), doubleArrayOf(0.000828, -0.000828, 0.001222, 0.003005, 0.002786), doubleArrayOf(0.024104, -0.024104, 0.035576, 0.087477, 0.081094), doubleArrayOf(-0.036219, 0.036219, -0.053457, -0.131442, -0.121852), doubleArrayOf(0.008787, -0.008787, 0.012969, 0.03189, 0.029563) )), tolerance = 1.0e-06) } } it("should match the expected errors of the inputArray") { assertTrue { layer.inputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.046517, 0.213223, -0.067537, 0.093758)), tolerance = 1.0e-06) } } } } } })
mpl-2.0
2cc3cd7f6f9006583141a34be8d6613d
38.266753
114
0.584556
4.160431
false
false
false
false
benjamin-bader/thrifty
thrifty-runtime/src/commonTest/kotlin/com/microsoft/thrifty/transport/FramedTransportTest.kt
1
2919
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.transport import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import okio.Buffer import okio.EOFException import kotlin.test.Test class FramedTransportTest { @Test fun sinkWritesFrameLength() { val buffer = Buffer() val bufferTransport = BufferTransport(buffer) val transport = FramedTransport(bufferTransport) transport.write("abcde".encodeToByteArray()) transport.flush() buffer.readInt() shouldBe 5 buffer.readUtf8() shouldBe "abcde" } @Test fun sourceReadsFrameLength() { val buffer = Buffer() buffer.writeInt(5) buffer.writeUtf8("abcdefghij") // buffer.size() is now 14 val transport = FramedTransport(BufferTransport(buffer)) val readBuffer = ByteArray(5) transport.read(readBuffer, 0, 5) shouldBe 5 buffer.size shouldBe 5L readBuffer.decodeToString() shouldBe "abcde" } @Test fun flushedDataBeginsWithFrameLength() { val target = Buffer() val source = Buffer() val transport = FramedTransport(BufferTransport(target)) source.writeUtf8("this text contains thirty-seven bytes") transport.write(source.readByteArray()) transport.flush() target.size shouldBe 41L target.readInt() shouldBe 37 target.readUtf8() shouldBe "this text contains thirty-seven bytes" } @Test fun readsSpanningMultipleFrames() { val buffer = Buffer() buffer.writeInt(6) buffer.writeUtf8("abcdef") buffer.writeInt(4) buffer.writeUtf8("ghij") val transport = FramedTransport(BufferTransport(buffer)) val readBuffer = ByteArray(10) transport.read(readBuffer, 0, 10) shouldBe 6 transport.read(readBuffer, 6, 4) shouldBe 4 readBuffer.decodeToString() shouldBe "abcdefghij" } @Test fun readHeaderWhenEOFReached() { val buffer = Buffer() val transport = FramedTransport(BufferTransport(buffer)) val readBuffer = ByteArray(10) shouldThrow<EOFException> { transport.read(readBuffer, 0, 10) } } }
apache-2.0
9fbd16403d0415bc3b9f3fa21b8ac9d5
31.076923
116
0.680027
4.546729
false
true
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/yvr_compass/CompassUltralightTransitData.kt
1
4672
/* * TroikaUltralightTransitData.kt * * Copyright 2018 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.yvr_compass import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.ultralight.UltralightCard import au.id.micolous.metrodroid.card.ultralight.UltralightCardTransitFactory import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.time.MetroTimeZone import au.id.micolous.metrodroid.transit.* import au.id.micolous.metrodroid.transit.nextfareul.NextfareUltralightTransitData import au.id.micolous.metrodroid.transit.nextfareul.NextfareUltralightTransitDataCapsule /* Based on reference at http://www.lenrek.net/experiments/compass-tickets/. */ @Parcelize class CompassUltralightTransitData (override val capsule: NextfareUltralightTransitDataCapsule) : NextfareUltralightTransitData() { override val timeZone: MetroTimeZone get() = TZ override val cardName: String get() = NAME override fun makeCurrency(value: Int) = TransitCurrency.CAD(value) private constructor(card: UltralightCard) : this(NextfareUltralightTransitData.parse(card) { raw, baseDate -> CompassUltralightTransaction(raw, baseDate) }) override fun getProductName(productCode: Int): String? = productCodes[productCode]?.let { Localizer.localizeString(it) } companion object { private const val NAME = "Compass" private val CARD_INFO = CardInfo( imageId = R.drawable.yvr_compass_card, name = NAME, locationId = R.string.location_vancouver, cardType = CardType.MifareUltralight, region = TransitRegion.CANADA, resourceExtraNote = R.string.compass_note) internal val TZ = MetroTimeZone.VANCOUVER val FACTORY: UltralightCardTransitFactory = object : UltralightCardTransitFactory { override val allCards: List<CardInfo> get() = listOf(CARD_INFO) override fun check(card: UltralightCard): Boolean { val head = card.getPage(4).data.byteArrayToInt(0, 3) if (head != 0x0a0400 && head != 0x0a0800) return false val page1 = card.getPage(5).data if (page1[1].toInt() != 1 || page1[2].toInt() and 0x80 != 0x80 || page1[3].toInt() != 0) return false val page2 = card.getPage(6).data return page2.byteArrayToInt(0, 3) == 0 } override fun parseTransitData(card: UltralightCard) = CompassUltralightTransitData(card) override fun parseTransitIdentity(card: UltralightCard): TransitIdentity = TransitIdentity(NAME, formatSerial(getSerial(card))) } private val productCodes = mapOf( 0x01 to R.string.compass_sub_daypass, 0x02 to R.string.compass_sub_one_zone, 0x03 to R.string.compass_sub_two_zone, 0x04 to R.string.compass_sub_three_zone, 0x0f to R.string.compass_sub_four_zone_wce_one_way, 0x11 to R.string.compass_sub_free_sea_island, 0x16 to R.string.compass_sub_exit, 0x1e to R.string.compass_sub_one_zone_with_yvr, 0x1f to R.string.compass_sub_two_zone_with_yvr, 0x20 to R.string.compass_sub_three_zone_with_yvr, 0x21 to R.string.compass_sub_daypass_with_yvr, 0x22 to R.string.compass_sub_bulk_daypass, 0x23 to R.string.compass_sub_bulk_one_zone, 0x24 to R.string.compass_sub_bulk_two_zone, 0x25 to R.string.compass_sub_bulk_three_zone, 0x26 to R.string.compass_sub_bulk_one_zone, 0x27 to R.string.compass_sub_bulk_two_zone, 0x28 to R.string.compass_sub_bulk_three_zone, 0x29 to R.string.compass_sub_gradpass ) } }
gpl-3.0
2c2600d3fb62acb049f44df546ae3676
42.663551
124
0.669521
4.041522
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidPosts/src/main/kotlin/com/eden/orchid/posts/pages/PostPage.kt
2
3987
package com.eden.orchid.posts.pages import com.eden.common.util.EdenUtils import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.annotations.Archetypes import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.api.render.RenderService import com.eden.orchid.api.resources.resource.OrchidResource import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.impl.relations.AssetRelation import com.eden.orchid.posts.PostCategoryArchetype import com.eden.orchid.posts.PostsGenerator import com.eden.orchid.posts.model.Author import com.eden.orchid.posts.model.CategoryModel import com.eden.orchid.posts.model.PostsModel import com.eden.orchid.utilities.extractOptionsFromResource import com.eden.orchid.utilities.resolve import org.json.JSONObject @Archetypes( Archetype(value = PostCategoryArchetype::class, key = PostsGenerator.GENERATOR_KEY), Archetype(value = ConfigArchetype::class, key = "${PostsGenerator.GENERATOR_KEY}.postPages") ) @Description(value = "A blog post.", name = "Blog Post") class PostPage( resource: OrchidResource, val categoryModel: CategoryModel, title: String ) : OrchidPage(resource, RenderService.RenderMode.TEMPLATE, "post", title) { @Option("author") @Description("The posts author. May be the `name` of a known author, or an anonymous Author config, only " + "used for this post, which is considered as a guest author." ) var authorName: Any? = null fun setAuthor(authorName: Any?) { this.authorName = authorName } val author: Author? by lazy { val postsModel: PostsModel = context.resolve() if (authorName is JSONObject) { val author = Author() author.extractOptions(context, (authorName as JSONObject).toMap()) author } else { val value = "" + authorName?.toString() postsModel.getAuthorByName(value) } } @Option @Description("A list of tags for this post, for basic taxonomic purposes. More complex taxonomic relationships " + "may be managed by other plugins, which may take post tags into consideration." ) lateinit var tags: Array<String> @Option @Description("A 'type' of post, such as 'gallery', 'video', or 'blog', which is used to determine the specific" + "post template to use for the Page Content." ) lateinit var postType: String @Option @Description("A fully-specified URL to a post's featured image, or a relative path to an Orchid image.") lateinit var featuredImage: AssetRelation @Option @Description("The permalink structure to use only for this blog post. This overrides the permalink structure set " + "in the category configuration." ) lateinit var permalink: String val category: String? get() { return categoryModel.key } val categories: Array<String> get() { return categoryModel.path.split("/").toTypedArray() } val year: Int get() { return publishDate.year } val month: Int get() { return publishDate.monthValue } val monthName: String get() { return publishDate.month.toString() } val day: Int get() { return publishDate.dayOfMonth } init { data = extractOptionsFromResource(context, resource) postInitialize(title) } override fun initialize(title: String?) { } override fun getTemplates(): List<String> { val templates = ArrayList<String>() if(!EdenUtils.isEmpty(postType)) { templates.add(0, "$key-type-$postType") } if(!EdenUtils.isEmpty(categoryModel.key)) { templates.add(0, "$key-${categoryModel.key!!}") } return templates } }
mit
4042fe0339e65032f55f27b5f87a9a9a
33.37069
120
0.682719
4.333696
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GHOAuthCredentialsUi.kt
2
2121
// 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.plugins.github.authentication.ui import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.AnimatedIcon import com.intellij.ui.dsl.builder.Panel import com.intellij.util.ui.NamedColorUtil import kotlinx.coroutines.future.await import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.authentication.GHOAuthService import org.jetbrains.plugins.github.i18n.GithubBundle.message import org.jetbrains.plugins.github.ui.util.Validator import java.util.concurrent.CancellationException import javax.swing.JComponent internal class GHOAuthCredentialsUi( val factory: GithubApiRequestExecutor.Factory, val isAccountUnique: UniqueLoginPredicate ) : GHCredentialsUi() { override fun getPreferredFocusableComponent(): JComponent? = null override fun getValidator(): Validator = { null } override suspend fun login(server: GithubServerPath): Pair<String, String> { val token = acquireToken() val executor = factory.create(token) val login = GHTokenCredentialsUi.acquireLogin(server, executor, isAccountUnique, null) return login to token } override fun handleAcquireError(error: Throwable): ValidationInfo = GHTokenCredentialsUi.handleError(error) override fun setBusy(busy: Boolean) = Unit override fun Panel.centerPanel() { row { label(message("label.login.progress")).applyToComponent { icon = AnimatedIcon.Default() foreground = NamedColorUtil.getInactiveTextColor() } } } private suspend fun acquireToken(): String { val credentialsFuture = GHOAuthService.instance.authorize() try { return credentialsFuture.await().accessToken } catch (ce: CancellationException) { credentialsFuture.completeExceptionally(ProcessCanceledException(ce)) throw ce } } }
apache-2.0
42de8d929043ce635ae765ccd50abb08
36.22807
158
0.780764
4.671806
false
false
false
false
GunoH/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/FileInDirectorySourceNames.kt
2
3920
// 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.ide.impl import com.intellij.openapi.util.io.FileUtil import com.intellij.workspaceModel.ide.CustomModuleEntitySource import com.intellij.workspaceModel.ide.JpsFileDependentEntitySource import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.ide.JpsImportedEntitySource import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.ArtifactEntity import com.intellij.workspaceModel.storage.bridgeEntities.FacetEntity import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity /** * This class is used to reuse [JpsFileEntitySource.FileInDirectory] instances when project is synchronized with JPS files after loading * storage from binary cache. */ class FileInDirectorySourceNames private constructor(entitiesBySource: Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>>) { private val mainEntityToSource: Map<Pair<Class<out WorkspaceEntity>, String>, JpsFileEntitySource.FileInDirectory> init { val sourcesMap = HashMap<Pair<Class<out WorkspaceEntity>, String>, JpsFileEntitySource.FileInDirectory>() for ((source, entities) in entitiesBySource) { val (type, entityName) = when { ModuleEntity::class.java in entities -> ModuleEntity::class.java to (entities.getValue(ModuleEntity::class.java).first() as ModuleEntity).name FacetEntity::class.java in entities -> ModuleEntity::class.java to (entities.getValue(FacetEntity::class.java).first() as FacetEntity).module.name LibraryEntity::class.java in entities -> LibraryEntity::class.java to (entities.getValue(LibraryEntity::class.java).first() as LibraryEntity).name ArtifactEntity::class.java in entities -> ArtifactEntity::class.java to (entities.getValue(ArtifactEntity::class.java).first() as ArtifactEntity).name else -> null to null } if (type != null && entityName != null) { val fileName = when { // At external storage libs and artifacts store in its own file and at [JpsLibrariesExternalFileSerializer]/[JpsArtifactEntitiesSerializer] // we can distinguish them only by directly entity name (type == LibraryEntity::class.java || type == ArtifactEntity::class.java) && (source as? JpsImportedEntitySource)?.storedExternally == true -> entityName // Module file stored at external and internal modules.xml has .iml file extension type == ModuleEntity::class.java -> "$entityName.iml" // In internal store (i.e. under `.idea` folder) each library or artifact has its own file, and we can distinguish them only by file name else -> FileUtil.sanitizeFileName(entityName) + ".xml" } sourcesMap[type to fileName] = getInternalFileSource(source) as JpsFileEntitySource.FileInDirectory } } mainEntityToSource = sourcesMap } fun findSource(entityClass: Class<out WorkspaceEntity>, fileName: String): JpsFileEntitySource.FileInDirectory? = mainEntityToSource[entityClass to fileName] companion object { fun from(storage: EntityStorage) = FileInDirectorySourceNames( storage.entitiesBySource { getInternalFileSource(it) is JpsFileEntitySource.FileInDirectory } ) fun empty() = FileInDirectorySourceNames(emptyMap()) private fun getInternalFileSource(source: EntitySource) = when (source) { is JpsFileDependentEntitySource -> source.originalSource is CustomModuleEntitySource -> source.internalSource is JpsFileEntitySource -> source else -> null } } }
apache-2.0
2e19062004f878e030c7135a62f2ce5e
57.507463
163
0.764541
5.240642
false
false
false
false
GunoH/intellij-community
plugins/devkit/intellij.devkit.workspaceModel/tests/testData/entityWithCollections/after/gen/CollectionFieldEntityImpl.kt
2
9111
package com.intellij.workspaceModel.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceSet import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class CollectionFieldEntityImpl(val dataSource: CollectionFieldEntityData) : CollectionFieldEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val versions: Set<Int> get() = dataSource.versions override val names: List<String> get() = dataSource.names override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: CollectionFieldEntityData?) : ModifiableWorkspaceEntityBase<CollectionFieldEntity, CollectionFieldEntityData>( result), CollectionFieldEntity.Builder { constructor() : this(CollectionFieldEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity CollectionFieldEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isVersionsInitialized()) { error("Field CollectionFieldEntity#versions should be initialized") } if (!getEntityData().isNamesInitialized()) { error("Field CollectionFieldEntity#names should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override fun afterModification() { val collection_versions = getEntityData().versions if (collection_versions is MutableWorkspaceSet<*>) { collection_versions.cleanModificationUpdateAction() } val collection_names = getEntityData().names if (collection_names is MutableWorkspaceList<*>) { collection_names.cleanModificationUpdateAction() } } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as CollectionFieldEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.versions != dataSource.versions) this.versions = dataSource.versions.toMutableSet() if (this.names != dataSource.names) this.names = dataSource.names.toMutableList() if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } private val versionsUpdater: (value: Set<Int>) -> Unit = { value -> changedProperty.add("versions") } override var versions: MutableSet<Int> get() { val collection_versions = getEntityData().versions if (collection_versions !is MutableWorkspaceSet) return collection_versions if (diff == null || modifiable.get()) { collection_versions.setModificationUpdateAction(versionsUpdater) } else { collection_versions.cleanModificationUpdateAction() } return collection_versions } set(value) { checkModificationAllowed() getEntityData(true).versions = value versionsUpdater.invoke(value) } private val namesUpdater: (value: List<String>) -> Unit = { value -> changedProperty.add("names") } override var names: MutableList<String> get() { val collection_names = getEntityData().names if (collection_names !is MutableWorkspaceList) return collection_names if (diff == null || modifiable.get()) { collection_names.setModificationUpdateAction(namesUpdater) } else { collection_names.cleanModificationUpdateAction() } return collection_names } set(value) { checkModificationAllowed() getEntityData(true).names = value namesUpdater.invoke(value) } override fun getEntityClass(): Class<CollectionFieldEntity> = CollectionFieldEntity::class.java } } class CollectionFieldEntityData : WorkspaceEntityData<CollectionFieldEntity>() { lateinit var versions: MutableSet<Int> lateinit var names: MutableList<String> fun isVersionsInitialized(): Boolean = ::versions.isInitialized fun isNamesInitialized(): Boolean = ::names.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<CollectionFieldEntity> { val modifiable = CollectionFieldEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): CollectionFieldEntity { return getCached(snapshot) { val entity = CollectionFieldEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun clone(): CollectionFieldEntityData { val clonedEntity = super.clone() clonedEntity as CollectionFieldEntityData clonedEntity.versions = clonedEntity.versions.toMutableWorkspaceSet() clonedEntity.names = clonedEntity.names.toMutableWorkspaceList() return clonedEntity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return CollectionFieldEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return CollectionFieldEntity(versions, names, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as CollectionFieldEntityData if (this.entitySource != other.entitySource) return false if (this.versions != other.versions) return false if (this.names != other.names) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as CollectionFieldEntityData if (this.versions != other.versions) return false if (this.names != other.names) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + versions.hashCode() result = 31 * result + names.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + versions.hashCode() result = 31 * result + names.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.versions?.let { collector.add(it::class.java) } this.names?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
82944776761bd8da9501a04c7daef477
33.642586
134
0.721216
5.397512
false
false
false
false
GunoH/intellij-community
uast/uast-common/src/com/intellij/psi/UastReferenceRegistrar.kt
2
7696
// 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. @file:JvmName("UastReferenceRegistrar") package com.intellij.psi import com.intellij.openapi.util.Key import com.intellij.openapi.util.registry.Registry import com.intellij.patterns.ElementPattern import com.intellij.patterns.StandardPatterns import com.intellij.util.ProcessingContext import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.expressions.UInjectionHost /** * Groups all UAST-based reference providers by chunks with the same priority and supported UElement types. */ fun PsiReferenceRegistrar.registerUastReferenceProvider(pattern: (UElement, ProcessingContext) -> Boolean, provider: UastReferenceProvider, priority: Double = PsiReferenceRegistrar.DEFAULT_PRIORITY) { val adapter = UastReferenceProviderAdapter(provider.supportedUElementTypes, provider) this.registerReferenceProvider(adaptPattern(pattern, provider.supportedUElementTypes), adapter, priority) } fun PsiReferenceRegistrar.registerUastReferenceProvider(pattern: ElementPattern<out UElement>, provider: UastReferenceProvider, priority: Double = PsiReferenceRegistrar.DEFAULT_PRIORITY) { this.registerUastReferenceProvider(pattern::accepts, provider, priority) } fun uastInjectionHostReferenceProvider(provider: (UExpression, PsiLanguageInjectionHost) -> Array<PsiReference>): UastInjectionHostReferenceProvider = uastInjectionHostReferenceProvider(null, provider) fun uastInjectionHostReferenceProvider(targetClass: Class<out PsiElement>?, provider: (UExpression, PsiLanguageInjectionHost) -> Array<PsiReference>): UastInjectionHostReferenceProvider = object : UastInjectionHostReferenceProvider() { override fun getReferencesForInjectionHost(uExpression: UExpression, host: PsiLanguageInjectionHost, context: ProcessingContext): Array<PsiReference> = provider(uExpression, host) override fun acceptsTarget(target: PsiElement): Boolean { return targetClass?.isInstance(target) ?: true } override fun toString(): String = "uastInjectionHostReferenceProvider($provider)" } fun <T : UElement> uastReferenceProvider(cls: Class<T>, targetClass: Class<out PsiElement>?, provider: (T, PsiElement) -> Array<PsiReference>): UastReferenceProvider = object : UastReferenceProvider(cls) { override fun getReferencesByElement(element: UElement, context: ProcessingContext): Array<PsiReference> { return provider(cls.cast(element), getRequestedPsiElement(context)) } override fun acceptsTarget(target: PsiElement): Boolean { return targetClass?.isInstance(target) ?: true } override fun toString(): String = "uastReferenceProvider($provider)" } fun getRequestedPsiElement(context: ProcessingContext): PsiElement { return context[REQUESTED_PSI_ELEMENT] } fun <T : UElement> uastReferenceProvider(cls: Class<T>, provider: (T, PsiElement) -> Array<PsiReference>): UastReferenceProvider = uastReferenceProvider(cls, null, provider) inline fun <reified T : UElement> uastReferenceProvider(noinline provider: (T, PsiElement) -> Array<PsiReference>): UastReferenceProvider = uastReferenceProvider(T::class.java, provider) internal val REQUESTED_PSI_ELEMENT: Key<PsiElement> = Key.create("REQUESTED_PSI_ELEMENT") internal val USAGE_PSI_ELEMENT: Key<PsiElement> = Key.create("USAGE_PSI_ELEMENT") internal fun adaptPattern(pattern: (UElement, ProcessingContext) -> Boolean, supportedUElementTypes: List<Class<out UElement>>): ElementPattern<out PsiElement> { val uastPatternAdapter = UastPatternAdapter(pattern, supportedUElementTypes) // optimisation until IDEA-211738 is implemented if (supportedUElementTypes.size == 1 && supportedUElementTypes[0] == UInjectionHost::class.java) { return StandardPatterns.instanceOf(PsiLanguageInjectionHost::class.java).and(uastPatternAdapter) } return uastPatternAdapter } @ApiStatus.Experimental fun uastReferenceProviderByUsage(provider: (UExpression, referencePsi: PsiLanguageInjectionHost, usagePsi: PsiElement) -> Array<PsiReference>): UastReferenceProvider = uastReferenceProviderByUsage(null, provider) /** * Creates UAST reference provider that accepts additional PSI element that could be either the same as reference PSI element or reference * element that is used in the same file and satisfy usage pattern. * * @see registerReferenceProviderByUsage */ @ApiStatus.Experimental fun uastReferenceProviderByUsage(targetClass: Class<out PsiElement>?, provider: (UExpression, referencePsi: PsiLanguageInjectionHost, usagePsi: PsiElement) -> Array<PsiReference>): UastReferenceProvider = object : UastReferenceProvider(UInjectionHost::class.java) { override fun getReferencesByElement(element: UElement, context: ProcessingContext): Array<PsiReference> { val uLiteral = element as? UExpression ?: return PsiReference.EMPTY_ARRAY val host = getRequestedPsiElement(context) as? PsiLanguageInjectionHost ?: return PsiReference.EMPTY_ARRAY val usagePsi = context[USAGE_PSI_ELEMENT] ?: getRequestedPsiElement(context) return provider(uLiteral, host, usagePsi) } override fun acceptsTarget(target: PsiElement): Boolean { return targetClass?.isInstance(target) ?: true } override fun toString(): String = "uastByUsageReferenceProvider($provider)" } /** * Registers a provider that will be called on the expressions that directly satisfy the [usagePattern] or at least one of the expression * usages satisfies the pattern if it was assigned to a variable. The provider will search for usages of variables only for expressions that * satisfy [expressionPattern]. There are standard expression patterns for usage search: [uInjectionHostInVariable] and [uExpressionInVariable]. * * Consider using [uastReferenceProviderByUsage] if you need to obtain additional context from a usage place. */ @ApiStatus.Experimental @JvmOverloads fun PsiReferenceRegistrar.registerReferenceProviderByUsage(expressionPattern: ElementPattern<out UElement>, usagePattern: ElementPattern<out UElement>, provider: UastReferenceProvider, priority: Double = PsiReferenceRegistrar.DEFAULT_PRIORITY) { this.registerUastReferenceProvider(usagePattern, provider, priority) if (Registry.`is`("uast.references.by.usage", true)) { val adapter = UastReferenceByUsageAdapter(expressionPattern, usagePattern, provider) this.registerReferenceProvider(adaptPattern(expressionPattern::accepts, adapter.supportedUElementTypes), adapter, priority) } } @ApiStatus.Experimental fun PsiReferenceRegistrar.registerReferenceProviderByUsage(usagePattern: ElementPattern<out UElement>, provider: UastReferenceProvider, priority: Double = PsiReferenceRegistrar.DEFAULT_PRIORITY) { registerReferenceProviderByUsage(uExpressionInVariable(), usagePattern, provider, priority) }
apache-2.0
2ac2c8c4fc54ebfdae58b049d5996d14
52.818182
167
0.724922
5.671334
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/stories/StoryTextPostModel.kt
1
5052
package org.thoughtcrime.securesms.stories import android.graphics.Bitmap import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.os.Parcel import android.os.Parcelable import android.view.View import androidx.core.graphics.scale import androidx.core.view.drawToBitmap import com.bumptech.glide.load.Key import com.bumptech.glide.load.Options import com.bumptech.glide.load.ResourceDecoder import com.bumptech.glide.load.engine.Resource import com.bumptech.glide.load.resource.SimpleResource import org.thoughtcrime.securesms.conversation.colors.ChatColors import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.database.model.MessageRecord import org.thoughtcrime.securesms.database.model.MmsMessageRecord import org.thoughtcrime.securesms.database.model.databaseprotos.StoryTextPost import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.fonts.TextFont import org.thoughtcrime.securesms.fonts.TextToScript import org.thoughtcrime.securesms.fonts.TypefaceCache import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.util.Base64 import org.thoughtcrime.securesms.util.ParcelUtil import java.io.IOException import java.security.MessageDigest /** * Glide model to render a StoryTextPost as a bitmap */ data class StoryTextPostModel( private val storyTextPost: StoryTextPost, private val storySentAtMillis: Long, private val storyAuthor: RecipientId ) : Key, Parcelable { override fun updateDiskCacheKey(messageDigest: MessageDigest) { messageDigest.update(storyTextPost.toByteArray()) messageDigest.update(storySentAtMillis.toString().toByteArray()) messageDigest.update(storyAuthor.serialize().toByteArray()) } val text: String = storyTextPost.body fun getPlaceholder(): Drawable { return if (storyTextPost.hasBackground()) { ChatColors.forChatColor(ChatColors.Id.NotSet, storyTextPost.background).chatBubbleMask } else { ColorDrawable(Color.TRANSPARENT) } } override fun writeToParcel(parcel: Parcel, flags: Int) { ParcelUtil.writeByteArray(parcel, storyTextPost.toByteArray()) parcel.writeLong(storySentAtMillis) parcel.writeParcelable(storyAuthor, flags) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<StoryTextPostModel> { override fun createFromParcel(parcel: Parcel): StoryTextPostModel { val storyTextPostArray = ParcelUtil.readByteArray(parcel) return StoryTextPostModel( StoryTextPost.parseFrom(storyTextPostArray), parcel.readLong(), parcel.readParcelable(RecipientId::class.java.classLoader)!! ) } override fun newArray(size: Int): Array<StoryTextPostModel?> { return arrayOfNulls(size) } fun parseFrom(messageRecord: MessageRecord): StoryTextPostModel { return parseFrom( messageRecord.body, messageRecord.timestamp, if (messageRecord.isOutgoing) Recipient.self().id else messageRecord.individualRecipient.id ) } @JvmStatic @Throws(IOException::class) fun parseFrom(body: String, storySentAtMillis: Long, storyAuthor: RecipientId): StoryTextPostModel { return StoryTextPostModel( storyTextPost = StoryTextPost.parseFrom(Base64.decode(body)), storySentAtMillis = storySentAtMillis, storyAuthor = storyAuthor ) } } class Decoder : ResourceDecoder<StoryTextPostModel, Bitmap> { companion object { private const val RENDER_HW_AR = 16f / 9f } override fun handles(source: StoryTextPostModel, options: Options): Boolean = true override fun decode(source: StoryTextPostModel, width: Int, height: Int, options: Options): Resource<Bitmap> { val message = SignalDatabase.mmsSms.getMessageFor(source.storySentAtMillis, source.storyAuthor) val view = StoryTextPostView(ApplicationDependencies.getApplication()) val typeface = TypefaceCache.get( ApplicationDependencies.getApplication(), TextFont.fromStyle(source.storyTextPost.style), TextToScript.guessScript(source.storyTextPost.body) ).blockingGet() val displayWidth: Int = ApplicationDependencies.getApplication().resources.displayMetrics.widthPixels val arHeight: Int = (RENDER_HW_AR * displayWidth).toInt() view.setTypeface(typeface) view.bindFromStoryTextPost(source.storyTextPost) view.bindLinkPreview((message as? MmsMessageRecord)?.linkPreviews?.firstOrNull()) view.invalidate() view.measure(View.MeasureSpec.makeMeasureSpec(displayWidth, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(arHeight, View.MeasureSpec.EXACTLY)) view.layout(0, 0, view.measuredWidth, view.measuredHeight) val bitmap = view.drawToBitmap().scale(width, height) return SimpleResource(bitmap) } } }
gpl-3.0
b572df5919964e10b4126b6672788bc8
36.422222
162
0.770784
4.848369
false
false
false
false
himikof/intellij-rust
src/main/kotlin/org/rust/cargo/project/workspace/Stdlib.kt
1
2359
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.workspace import com.intellij.notification.NotificationType import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import org.rust.cargo.toolchain.Rustup import org.rust.ide.notifications.showBalloon class SetupRustStdlibTask( private val module: Module, private val rustup: Rustup, private val withCurrentStdlib: (StandardLibrary) -> Unit ) : Task.Backgroundable(module.project, "Setup Rust stdlib") { private lateinit var result: Rustup.DownloadResult override fun run(indicator: ProgressIndicator) { indicator.isIndeterminate = true result = rustup.downloadStdlib() } override fun onSuccess() { if (module.isDisposed) return val result = result when (result) { is Rustup.DownloadResult.Ok -> { val stdlib = StandardLibrary.fromFile(result.library) ?: return failWithMessage("${result.library.presentableUrl} is not a valid Rust standard library") val oldLibrary = rustStandardLibrary(module) if (oldLibrary != null && stdlib.sameAsLibrary(oldLibrary)) { withCurrentStdlib(stdlib) return } runWriteAction { stdlib.attachTo(module) } withCurrentStdlib(stdlib) project.showBalloon( "Using Rust standard library at ${result.library.presentableUrl}", NotificationType.INFORMATION ) } is Rustup.DownloadResult.Err -> return failWithMessage("Failed to download standard library: ${result.error}") } } private fun failWithMessage(message: String) { project.showBalloon(message, NotificationType.ERROR) } } private fun rustStandardLibrary(module: Module): Library? = LibraryTablesRegistrar.getInstance().getLibraryTable(module.project).getLibraryByName(module.rustLibraryName)
mit
e3fcded9179290429e97821fa672a581
35.292308
118
0.678677
5.128261
false
false
false
false
google/accompanist
insets/src/main/java/com/google/accompanist/insets/WindowInsetsType.kt
1
5276
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("DEPRECATION") package com.google.accompanist.insets import androidx.annotation.FloatRange import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue /** * Mutable [androidx.compose.runtime.State] backed implementation of [WindowInsets.Type]. */ internal class MutableWindowInsetsType : WindowInsets.Type { private var ongoingAnimationsCount by mutableStateOf(0) /** * The layout inset values for this [WindowInsets.Type]. These are the insets which are defined from * the current window layout. * * You should not normally need to use this directly, and instead use [left], [top], * [right], and [bottom] to return the correct value for the current state. */ override val layoutInsets: MutableInsets = MutableInsets() /** * The animated inset values for this [WindowInsets.Type]. These are the insets which are updated from * any on-going animations. If there are no animations in progress, the returned * [Insets] will be empty. * * You should not normally need to use this directly, and instead use [left], [top], * [right], and [bottom] to return the correct value for the current state. */ override val animatedInsets: MutableInsets = MutableInsets() /** * Whether the insets are currently visible. */ override var isVisible by mutableStateOf(true) /** * Whether this insets type is being animated at this moment. */ override val animationInProgress: Boolean by derivedStateOf { ongoingAnimationsCount > 0 } /** * The progress of any ongoing animations, in the range of 0 to 1. * If there is no animation in progress, this will return 0. */ @get:FloatRange(from = 0.0, to = 1.0) override var animationFraction by mutableStateOf(0f) fun onAnimationStart() { ongoingAnimationsCount++ } fun onAnimationEnd() { ongoingAnimationsCount-- if (ongoingAnimationsCount == 0) { // If there are no on-going animations, clear out the animated insets animatedInsets.reset() animationFraction = 0f } } } /** * Shallow-immutable implementation of [WindowInsets.Type]. */ internal class ImmutableWindowInsetsType( override val layoutInsets: Insets = Insets.Empty, override val animatedInsets: Insets = Insets.Empty, override val isVisible: Boolean = false, override val animationInProgress: Boolean = false, override val animationFraction: Float = 0f, ) : WindowInsets.Type /** * Returns an instance of [WindowInsets.Type] whose values are calculated and derived from the * [WindowInsets.Type] instances passed in to [types]. * * Each [WindowInsets.Type] passed in will be coerced with each other, such that the maximum value for * each dimension is calculated and used. This is typically used for two purposes: * * 1) Creating semantic types. [WindowInsets.systemBars] is a good example, as it is the derived * insets of [WindowInsets.statusBars] and [WindowInsets.navigationBars]. * 2) Combining insets for specific usages. [navigationBarsWithImePadding] is a good example, as it * is the derived insets of the [WindowInsets.ime] insets, coerced by the * [WindowInsets.navigationBars] insets. */ @Deprecated( """ accompanist/insets is deprecated. The androidx.compose equivalent is WindowInsets.union. For more migration information, please visit https://google.github.io/accompanist/insets/#migration """ ) fun derivedWindowInsetsTypeOf(vararg types: WindowInsets.Type): WindowInsets.Type = CalculatedWindowInsetsType(*types) /** * Implementation of [WindowInsets.Type] which is the backing implementation for [derivedWindowInsetsTypeOf]. */ private class CalculatedWindowInsetsType(vararg types: WindowInsets.Type) : WindowInsets.Type { override val layoutInsets: Insets by derivedStateOf { types.fold(Insets.Empty) { acc, insetsType -> acc.coerceEachDimensionAtLeast(insetsType) } } override val animatedInsets: Insets by derivedStateOf { types.fold(Insets.Empty) { acc, insetsType -> acc.coerceEachDimensionAtLeast(insetsType) } } override val isVisible: Boolean by derivedStateOf { types.all { it.isVisible } } override val animationInProgress: Boolean by derivedStateOf { types.any { it.animationInProgress } } override val animationFraction: Float by derivedStateOf { types.maxOf { it.animationFraction } } }
apache-2.0
7c21b37ff4a1c2a2fe4e75b6fe9666d8
35.136986
118
0.71721
4.603839
false
false
false
false
ktorio/ktor
ktor-io/posix/src/io/ktor/utils/io/pool/DefaultPool.kt
1
1776
package io.ktor.utils.io.pool import kotlinx.atomicfu.* import kotlinx.atomicfu.locks.* public actual abstract class DefaultPool<T : Any> actual constructor( actual final override val capacity: Int ) : ObjectPool<T> { @Deprecated( "This API is implementation detail. Consider creating new SynchronizedObject instead", level = DeprecationLevel.WARNING ) protected val lock: SynchronizedObject = SynchronizedObject() private val instances = atomicArrayOfNulls<Any?>(capacity) private var size by atomic(0) protected actual abstract fun produceInstance(): T protected actual open fun disposeInstance(instance: T) {} protected actual open fun clearInstance(instance: T): T = instance protected actual open fun validateInstance(instance: T) {} public actual final override fun borrow(): T = synchronized(lock) { if (size == 0) return produceInstance() val idx = --size @Suppress("UNCHECKED_CAST") val instance = instances[idx].value as T instances[idx].value = null return clearInstance(instance) } public actual final override fun recycle(instance: T) { synchronized(lock) { validateInstance(instance) if (size == capacity) { disposeInstance(instance) } else { instances[size++].value = instance } } } public actual final override fun dispose() { synchronized(lock) { for (i in 0 until size) { @Suppress("UNCHECKED_CAST") val instance = instances[i].value as T instances[i].value = null disposeInstance(instance) } size = 0 } } }
apache-2.0
ea4b9b4e3f471f23f6fdfaaf9c15521f
30.157895
94
0.618243
4.919668
false
false
false
false
google/accompanist
sample/src/main/java/com/google/accompanist/sample/permissions/RequestLocationPermissionsSample.kt
1
3566
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.sample.permissions import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.rememberMultiplePermissionsState import com.google.accompanist.sample.AccompanistSampleTheme class RequestLocationPermissionsSample : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AccompanistSampleTheme { Sample() } } } } @OptIn(ExperimentalPermissionsApi::class) @Composable private fun Sample() { val locationPermissionsState = rememberMultiplePermissionsState( listOf( android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION, ) ) if (locationPermissionsState.allPermissionsGranted) { Text("Thanks! I can access your exact location :D") } else { Column { val allPermissionsRevoked = locationPermissionsState.permissions.size == locationPermissionsState.revokedPermissions.size val textToShow = if (!allPermissionsRevoked) { // If not all the permissions are revoked, it's because the user accepted the COARSE // location permission, but not the FINE one. "Yay! Thanks for letting me access your approximate location. " + "But you know what would be great? If you allow me to know where you " + "exactly are. Thank you!" } else if (locationPermissionsState.shouldShowRationale) { // Both location permissions have been denied "Getting your exact location is important for this app. " + "Please grant us fine location. Thank you :D" } else { // First time the user sees this feature or the user doesn't want to be asked again "This feature requires location permission" } val buttonText = if (!allPermissionsRevoked) { "Allow precise location" } else { "Request permissions" } Text(text = textToShow) Spacer(modifier = Modifier.height(8.dp)) Button(onClick = { locationPermissionsState.launchMultiplePermissionRequest() }) { Text(buttonText) } } } }
apache-2.0
4e52418a7f5f16e29294462ba830566d
37.76087
100
0.673303
5.087019
false
false
false
false
marius-m/wt4
app/src/main/java/lt/markmerkk/repositories/ExternalResRepository.kt
1
4494
package lt.markmerkk.repositories import lt.markmerkk.repositories.entities.ExternalRes import lt.markmerkk.repositories.entities.ExternalResJar import lt.markmerkk.repositories.entities.ExternalResLocal import org.apache.commons.io.FileUtils import org.apache.commons.io.IOUtils import org.slf4j.LoggerFactory import rx.Single import java.io.File import java.io.FileOutputStream import java.io.IOException import java.net.URISyntaxException import java.util.jar.JarFile class ExternalResRepository { fun readExternalResourceAsString(extResource: ExternalRes): Single<String> { return Single.defer { val content = when (extResource) { is ExternalResJar -> { jarFileToString(extResource.jarEntry.name) } is ExternalResLocal -> { FileUtils.readFileToString(extResource.file, Charsets.UTF_8.toString()) } } Single.just(content) } } fun readExternalResourceAsTmpFile(extResource: ExternalRes): Single<File> { return Single.defer { val tmpFile = File.createTempFile("tmp", ".data") val outFile = when (extResource) { is ExternalResJar -> { jarToFile(tmpFile, extResource.jarEntry.name) } is ExternalResLocal -> { extResource.file } } Single.just(outFile) } } fun externalResources(rootPath: String): Single<List<ExternalRes>> { return Single.defer { val jarFile = File(javaClass.protectionDomain.codeSource.location.path) if (jarFile.isFile) { readFromJarResource(rootPath, jarFile) } else { readFromLocalResource(rootPath) } } } private fun readFromLocalResource( rootPath: String ): Single<List<ExternalRes>> { return Single.defer { val url = ExternalResRepository::class.java.getResource("${File.separator}$rootPath") if (url == null) Single.error<List<ExternalRes>>(IllegalStateException("Cannot figure URL")) try { val files: List<File> = File(url.toURI()) .listFiles() ?.toList() ?: emptyList() val res = files .mapNotNull { try { ExternalResLocal( path = rootPath, name = it.name, file = it ) } catch (e: IOException) { l.warn("Cannot read ${it.name}", e) null } } Single.just(res) } catch (ex: URISyntaxException) { ex.printStackTrace() Single.error(IllegalArgumentException("Error reading local resource")) } } } private fun readFromJarResource( rootPath: String, jarFile: File ): Single<List<ExternalRes>> { return Single.defer { val jar = JarFile(jarFile) val entries = jar.entries().toList() val jarEntries = entries .filter { it.name.startsWith("$rootPath/") } .mapNotNull { try { ExternalResJar(jarEntry = it) } catch (e: IOException) { l.warn("Cannot read ${it.name}", e) null } }.filter { !it.isDirectory } jar.close() Single.just(jarEntries) } } @Throws(IOException::class) private fun jarFileToString(inputPath: String): String { val fileIs = javaClass.classLoader.getResourceAsStream(inputPath) return IOUtils.toString(fileIs, "UTF-8") } @Throws(IOException::class) private fun jarToFile(inputFile: File, inputPath: String): File { val fileIs = javaClass.classLoader.getResourceAsStream(inputPath) FileOutputStream(inputFile).use { IOUtils.copy(fileIs, it) } return inputFile } companion object { val l = LoggerFactory.getLogger(ExternalResRepository::class.java)!! } }
apache-2.0
5ed88fb6d22fa168ba0185fe429b927b
33.05303
104
0.531598
5.388489
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/GL45Core.kt
4
43142
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val GL45C = "GL45C".nativeClassGL("GL45C") { extends = GL44C documentation = """ The OpenGL functionality up to version 4.5. Includes only Core Profile symbols. OpenGL 4.5 implementations support revision 4.50 of the OpenGL Shading Language. Extensions promoted to core in this release: ${ul( registryLinkTo("ARB", "clip_control"), registryLinkTo("ARB", "cull_distance"), registryLinkTo("ARB", "ES3_1_compatibility"), registryLinkTo("ARB", "conditional_render_inverted"), registryLinkTo("KHR", "context_flush_control"), registryLinkTo("ARB", "derivative_control"), registryLinkTo("ARB", "direct_state_access"), registryLinkTo("ARB", "get_texture_sub_image"), registryLinkTo("KHR", "robustness"), registryLinkTo("ARB", "shader_texture_image_samples"), registryLinkTo("ARB", "texture_barrier") )} """ // ARB_clip_control val depths = IntConstant( "Accepted by the {@code depth} parameter of #ClipControl().", "NEGATIVE_ONE_TO_ONE"..0x935E, "ZERO_TO_ONE"..0x935F ).javaDocLinks IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.", "CLIP_ORIGIN"..0x935C, "CLIP_DEPTH_MODE"..0x935D ) void( "ClipControl", """ Controls the clipping volume behavior. These parameters update the clip control origin and depth mode respectively. The initial value of the clip control origin is #LOWER_LEFT and the initial value of the depth mode is #NEGATIVE_ONE_TO_ONE. The error #INVALID_OPERATION is generated if ClipControl is executed between the execution of #Begin() and the corresponding execution of #End(). """, GLenum("origin", "the clip origin", "#LOWER_LEFT #UPPER_LEFT"), GLenum("depth", "the clip depth mode", depths) ) // ARB_conditional_render_inverted IntConstant( "Accepted by the {@code mode} parameter of #BeginConditionalRender().", "QUERY_WAIT_INVERTED"..0x8E17, "QUERY_NO_WAIT_INVERTED"..0x8E18, "QUERY_BY_REGION_WAIT_INVERTED"..0x8E19, "QUERY_BY_REGION_NO_WAIT_INVERTED"..0x8E1A ) // ARB_cull_distance IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, and GetInteger64v.", "MAX_CULL_DISTANCES"..0x82F9, "MAX_COMBINED_CLIP_AND_CULL_DISTANCES"..0x82FA ) // ARB_direct_state_access IntConstant( "Accepted by the {@code pname} parameter of GetTextureParameter{if}v and GetTextureParameterI{i ui}v.", "TEXTURE_TARGET"..0x1006 ) IntConstant( "Accepted by the {@code pname} parameter of GetQueryObjectiv.", "QUERY_TARGET"..0x82EA ) void( "CreateTransformFeedbacks", "Returns {@code n} previously unused transform feedback object names in {@code ids}, each representing a new state vector.", AutoSize("ids")..GLsizei("n", "the number of transform feedback object names to create"), ReturnParam..GLuint.p("ids", "the buffer in which to return the names") ) void( "TransformFeedbackBufferBase", "Binds a buffer object to a transform feedback object.", GLuint("xfb", "zero or the name of an existing transform feedback object"), GLuint("index", "the transform feedback stream index"), GLuint("buffer", "the name of an existing buffer object") ) void( "TransformFeedbackBufferRange", "Binds a region of a buffer object to a transform feedback object.", GLuint("xfb", "zero or the name of an existing transform feedback object"), GLuint("index", "the transform feedback stream index"), GLuint("buffer", "the name of an existing buffer object"), GLintptr("offset", "the starting offset in basic machine units into the buffer object"), GLsizeiptr("size", "the amount of data in machine units") ) void( "GetTransformFeedbackiv", "Returns information about a transform feedback object.", GLuint("xfb", "zero or the name of an existing transform feedback object"), GLenum("pname", "the parameter to query", "#TRANSFORM_FEEDBACK_PAUSED #TRANSFORM_FEEDBACK_ACTIVE"), Check(1)..ReturnParam..GLint.p("param", "the buffer in which to return the parameter value") ) void( "GetTransformFeedbacki_v", "Returns information about a transform feedback object.", GLuint("xfb", "zero or the name of an existing transform feedback object"), GLenum("pname", "the parameter to query", "#TRANSFORM_FEEDBACK_BUFFER_BINDING"), GLuint("index", "the transform feedback stream index"), Check(1)..ReturnParam..GLint.p("param", "the buffer in which to return the parameter value") ) void( "GetTransformFeedbacki64_v", "Returns information about a transform feedback object.", GLuint("xfb", "zero or the name of an existing transform feedback object"), GLenum("pname", "the parameter to query", "#TRANSFORM_FEEDBACK_BUFFER_START #TRANSFORM_FEEDBACK_BUFFER_SIZE"), GLuint("index", "the transform feedback stream index"), Check(1)..ReturnParam..GLint64.p("param", "the buffer in which to return the parameter value") ) void( "CreateBuffers", """ Returns {@code n} previously unused buffer names in {@code buffers}, each representing a new buffer object initialized as if it had been bound to an unspecified target. """, AutoSize("buffers")..GLsizei("n", "the number of buffer names to create"), ReturnParam..GLuint.p("buffers", "the buffer in which to return the names") ) var src = GL44["BufferStorage"] void( "NamedBufferStorage", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name"), src["size"], src["data"], src["flags"] ) src = GL15["BufferData"] void( "NamedBufferData", "DSA version of ${src.javaDocLink}.", GLuint("buffer", ""), src["size"], src["data"], src["usage"] ) src = GL15["BufferSubData"] void( "NamedBufferSubData", "DSA version of ${src.javaDocLink}.", GLuint("buffer", ""), src["offset"], src["size"], src["data"] ) src = GL31["CopyBufferSubData"] void( "CopyNamedBufferSubData", "DSA version of ${src.javaDocLink}.", GLuint("readBuffer", "the source buffer object name"), GLuint("writeBuffer", "the destination buffer object name"), src["readOffset"], src["writeOffset"], src["size"] ) src = GL43["ClearBufferData"] void( "ClearNamedBufferData", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name"), src["internalformat"], src["format"], src["type"], src["data"] ) src = GL43["ClearBufferSubData"] void( "ClearNamedBufferSubData", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name"), src["internalformat"], src["offset"], src["size"], src["format"], src["type"], src["data"] ) src = GL15["MapBuffer"] MapPointer("glGetNamedBufferParameteri(buffer, GL15.GL_BUFFER_SIZE)", oldBufferOverloads = true)..void.p( "MapNamedBuffer", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name"), src["access"] ) src = GL30["MapBufferRange"] MapPointer("length", oldBufferOverloads = true)..void.p( "MapNamedBufferRange", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name"), src["offset"], src["length"], src["access"] ) src = GL15["UnmapBuffer"] GLboolean( "UnmapNamedBuffer", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name") ) src = GL30["FlushMappedBufferRange"] void( "FlushMappedNamedBufferRange", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name"), src["offset"], src["length"] ) src = GL15["GetBufferParameteriv"] void( "GetNamedBufferParameteriv", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name"), src["pname"], src["params"] ) src = GL32["GetBufferParameteri64v"] void( "GetNamedBufferParameteri64v", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name"), src["pname"], src["params"] ) src = GL15["GetBufferPointerv"] void( "GetNamedBufferPointerv", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name"), src["pname"], src["params"] ) src = GL15["GetBufferSubData"] void( "GetNamedBufferSubData", "DSA version of ${src.javaDocLink}.", GLuint("buffer", "the buffer object name"), src["offset"], src["size"], src["data"] ) void( "CreateFramebuffers", "Returns {@code n} previously unused framebuffer names in {@code framebuffers}, each representing a new framebuffer object.", AutoSize("framebuffers")..GLsizei("n", "the number of framebuffer names to create"), ReturnParam..GLuint.p("framebuffers", "the buffer in which to store the framebuffer names") ) val FRAMEBUFFER = GLuint("framebuffer", "the framebuffer name") src = GL30["FramebufferRenderbuffer"] void( "NamedFramebufferRenderbuffer", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["attachment"], src["renderbuffertarget"], src["renderbuffer"] ) src = GL43["FramebufferParameteri"] void( "NamedFramebufferParameteri", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["pname"], src["param"] ) src = GL32["FramebufferTexture"] void( "NamedFramebufferTexture", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["attachment"], src["texture"], src["level"] ) src = GL30["FramebufferTextureLayer"] void( "NamedFramebufferTextureLayer", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["attachment"], src["texture"], src["level"], src["layer"] ) src = GL11C["DrawBuffer"] void( "NamedFramebufferDrawBuffer", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["buf"] ) src = GL20["DrawBuffers"] void( "NamedFramebufferDrawBuffers", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["n"], src["bufs"] ) src = GL11C["ReadBuffer"] void( "NamedFramebufferReadBuffer", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["src"] ) src = GL43["InvalidateFramebuffer"] void( "InvalidateNamedFramebufferData", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["numAttachments"], src["attachments"] ) src = GL43["InvalidateSubFramebuffer"] void( "InvalidateNamedFramebufferSubData", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["numAttachments"], src["attachments"], src["x"], src["y"], src["width"], src["height"] ) src = GL30["ClearBufferiv"] void( "ClearNamedFramebufferiv", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["buffer"], src["drawbuffer"], src["value"] ) src = GL30["ClearBufferuiv"] void( "ClearNamedFramebufferuiv", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["buffer"], src["drawbuffer"], src["value"] ) src = GL30["ClearBufferfv"] void( "ClearNamedFramebufferfv", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["buffer"], src["drawbuffer"], src["value"] ) src = GL30["ClearBufferfi"] void( "ClearNamedFramebufferfi", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["buffer"], src["drawbuffer"], src["depth"], src["stencil"] ) src = GL30["BlitFramebuffer"] void( "BlitNamedFramebuffer", "DSA version of ${src.javaDocLink}.", GLuint("readFramebuffer", "the source framebuffer name"), GLuint("drawFramebuffer", "the destination framebuffer name"), src["srcX0"], src["srcY0"], src["srcX1"], src["srcY1"], src["dstX0"], src["dstY0"], src["dstX1"], src["dstY1"], src["mask"], src["filter"] ) src = GL30["CheckFramebufferStatus"] GLenum( "CheckNamedFramebufferStatus", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["target"] ) src = GL43["GetFramebufferParameteriv"] void( "GetNamedFramebufferParameteriv", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["pname"], src["params"] ) src = GL30["GetFramebufferAttachmentParameteriv"] void( "GetNamedFramebufferAttachmentParameteriv", "DSA version of ${src.javaDocLink}.", FRAMEBUFFER, src["attachment"], src["pname"], src["params"] ) void( "CreateRenderbuffers", "Returns {@code n} previously unused renderbuffer names in {@code renderbuffers}, each representing a new renderbuffer object.", AutoSize("renderbuffers")..GLsizei("n", "the number of renderbuffer names to create"), ReturnParam..GLuint.p("renderbuffers", "the buffer in which to store the created renderbuffer names") ) src = GL30["RenderbufferStorage"] void( "NamedRenderbufferStorage", "DSA version of ${src.javaDocLink}.", GLuint("renderbuffer", ""), src["internalformat"], src["width"], src["height"] ) src = GL30["RenderbufferStorageMultisample"] void( "NamedRenderbufferStorageMultisample", "DSA version of ${src.javaDocLink}.", GLuint("renderbuffer", ""), src["samples"], src["internalformat"], src["width"], src["height"] ) src = GL30["GetRenderbufferParameteriv"] void( "GetNamedRenderbufferParameteriv", "DSA version of ${src.javaDocLink}.", GLuint("renderbuffer", ""), src["pname"], src["params"] ) void( "CreateTextures", "Returns {@code n} previously unused texture names in {@code textures}, each representing a new texture object.", GLenum( "target", "the texture target", "#TEXTURE_1D $TEXTURE_2D_TARGETS $TEXTURE_3D_TARGETS #TEXTURE_BUFFER #TEXTURE_2D_MULTISAMPLE #TEXTURE_2D_MULTISAMPLE_ARRAY" ), AutoSize("textures")..GLsizei("n", "the number of texture names to create"), ReturnParam..GLuint.p("textures", "the buffer in which to store the created texture names") ) val TEXTURE = GLuint("texture", "the texture name") src = GL31["TexBuffer"] void( "TextureBuffer", "DSA version of ${src.javaDocLink}.", TEXTURE, src["internalformat"], src["buffer"] ) src = GL43["TexBufferRange"] void( "TextureBufferRange", "DSA version of ${src.javaDocLink}.", TEXTURE, src["internalformat"], src["buffer"], src["offset"], src["size"] ) src = GL42["TexStorage1D"] void( "TextureStorage1D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["levels"], src["internalformat"], src["width"] ) src = GL42["TexStorage2D"] void( "TextureStorage2D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["levels"], src["internalformat"], src["width"], src["height"] ) src = GL42["TexStorage3D"] void( "TextureStorage3D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["levels"], src["internalformat"], src["width"], src["height"], src["depth"] ) src = GL43["TexStorage2DMultisample"] void( "TextureStorage2DMultisample", "DSA version of ${src.javaDocLink}.", TEXTURE, src["samples"], src["internalformat"], src["width"], src["height"], src["fixedsamplelocations"] ) src = GL43["TexStorage3DMultisample"] void( "TextureStorage3DMultisample", "DSA version of ${src.javaDocLink}.", TEXTURE, src["samples"], src["internalformat"], src["width"], src["height"], src["depth"], src["fixedsamplelocations"] ) src = GL11C["TexSubImage1D"] void( "TextureSubImage1D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["xoffset"], src["width"], src["format"], src["type"], src["pixels"] ) src = GL11C["TexSubImage2D"] void( "TextureSubImage2D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["xoffset"], src["yoffset"], src["width"], src["height"], src["format"], src["type"], src["pixels"] ) src = GL12C["TexSubImage3D"] void( "TextureSubImage3D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["xoffset"], src["yoffset"], src["zoffset"], src["width"], src["height"], src["depth"], src["format"], src["type"], src["pixels"] ) src = GL13C["CompressedTexSubImage1D"] void( "CompressedTextureSubImage1D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["xoffset"], src["width"], src["format"], src["imageSize"], src["data"] ) src = GL13C["CompressedTexSubImage2D"] void( "CompressedTextureSubImage2D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["xoffset"], src["yoffset"], src["width"], src["height"], src["format"], src["imageSize"], src["data"] ) src = GL13C["CompressedTexSubImage3D"] void( "CompressedTextureSubImage3D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["xoffset"], src["yoffset"], src["zoffset"], src["width"], src["height"], src["depth"], src["format"], src["imageSize"], src["data"] ) src = GL11C["CopyTexSubImage1D"] void( "CopyTextureSubImage1D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["xoffset"], src["x"], src["y"], src["width"] ) src = GL11C["CopyTexSubImage2D"] void( "CopyTextureSubImage2D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["xoffset"], src["yoffset"], src["x"], src["y"], src["width"], src["height"] ) src = GL12C["CopyTexSubImage3D"] void( "CopyTextureSubImage3D", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["xoffset"], src["yoffset"], src["zoffset"], src["x"], src["y"], src["width"], src["height"] ) src = GL11C["TexParameterf"] void( "TextureParameterf", "DSA version of ${src.javaDocLink}.", TEXTURE, src["pname"], src["param"] ) src = GL11C["TexParameterfv"] void( "TextureParameterfv", "DSA version of ${src.javaDocLink}.", TEXTURE, src["pname"], src["params"] ) src = GL11C["TexParameteri"] void( "TextureParameteri", "DSA version of ${src.javaDocLink}.", TEXTURE, src["pname"], src["param"] ) src = GL30["TexParameterIiv"] void( "TextureParameterIiv", "DSA version of ${src.javaDocLink}.", TEXTURE, src["pname"], src["params"] ) src = GL30["TexParameterIuiv"] void( "TextureParameterIuiv", "DSA version of ${src.javaDocLink}.", TEXTURE, src["pname"], src["params"] ) src = GL11C["TexParameteriv"] void( "TextureParameteriv", "DSA version of ${src.javaDocLink}.", TEXTURE, src["pname"], src["params"] ) src = GL30["GenerateMipmap"] void( "GenerateTextureMipmap", "DSA version of ${src.javaDocLink}.", TEXTURE ) void( "BindTextureUnit", """ Binds an existing texture object to the texture unit numbered {@code unit}. {@code texture} must be zero or the name of an existing texture object. When {@code texture} is the name of an existing texture object, that object is bound to the target, in the corresponding texture unit, that was specified when the object was created. When {@code texture} is zero, each of the targets enumerated at the beginning of this section is reset to its default texture for the corresponding texture image unit. """, GLuint("unit", "the texture unit number"), TEXTURE ) src = GL11C["GetTexImage"] void( "GetTextureImage", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["format"], src["type"], AutoSize("pixels")..GLsizei("bufSize", "the size of the buffer to receive the retrieved pixel data"), src["pixels"] ) src = GL13C["GetCompressedTexImage"] void( "GetCompressedTextureImage", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], AutoSize("pixels")..GLsizei("bufSize", "the size of the buffer to receive the retrieved pixel data"), Check( expression = "glGetTextureLevelParameteri(texture, level, GL13.GL_TEXTURE_COMPRESSED_IMAGE_SIZE)", debug = true )..RawPointer..void.p("pixels", "a buffer in which to return the compressed texture image") ) src = GL11C["GetTexLevelParameterfv"] void( "GetTextureLevelParameterfv", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["pname"], src["params"] ) src = GL11C["GetTexLevelParameteriv"] void( "GetTextureLevelParameteriv", "DSA version of ${src.javaDocLink}.", TEXTURE, src["level"], src["pname"], src["params"] ) src = GL11C["GetTexParameterfv"] void( "GetTextureParameterfv", "DSA version of ${src.javaDocLink}.", TEXTURE, src["pname"], src["params"] ) src = GL30["GetTexParameterIiv"] void( "GetTextureParameterIiv", "DSA version of ${src.javaDocLink}.", TEXTURE, src["pname"], src["params"] ) src = GL30["GetTexParameterIuiv"] void( "GetTextureParameterIuiv", "DSA version of ${src.javaDocLink}.", TEXTURE, src["pname"], src["params"] ) src = GL11C["GetTexParameteriv"] void( "GetTextureParameteriv", "DSA version of ${src.javaDocLink}.", TEXTURE, src["pname"], src["params"] ) void( "CreateVertexArrays", "Returns {@code n} previously unused vertex array object names in {@code arrays}.", AutoSize("arrays")..GLsizei("n", "the number of vertex array object names to create"), ReturnParam..GLuint.p("arrays", "the buffer in which to return the created vertex array object names") ) src = GL20["DisableVertexAttribArray"] void( "DisableVertexArrayAttrib", "DSA version of ${src.javaDocLink}.", GLuint("vaobj", "the vertex array object name"), src["index"] ) src = GL20["EnableVertexAttribArray"] void( "EnableVertexArrayAttrib", "DSA version of ${src.javaDocLink}.", GLuint("vaobj", "the vertex array object name"), src["index"] ) void( "VertexArrayElementBuffer", "Binds a buffer object to the element array buffer bind point of a vertex array object.", GLuint("vaobj", "the vertex array object name"), GLuint("buffer", "the buffer object name. If {@code buffer} is zero, any existing element array buffer binding to {@code vaobj} is removed.") ) src = GL43["BindVertexBuffer"] void( "VertexArrayVertexBuffer", "DSA version of ${src.javaDocLink}.", GLuint("vaobj", "the vertex array object name"), src["bindingindex"], src["buffer"], src["offset"], src["stride"] ) src = GL44["BindVertexBuffers"] void( "VertexArrayVertexBuffers", "DSA version of ${src.javaDocLink}.", GLuint("vaobj", "the vertex array object name"), src["first"], src["count"], src["buffers"], src["offsets"], src["strides"] ) src = GL43["VertexAttribFormat"] void( "VertexArrayAttribFormat", "DSA version of ${src.javaDocLink}.", GLuint("vaobj", "the vertex array object name"), src["attribindex"], src["size"], src["type"], src["normalized"], src["relativeoffset"] ) src = GL43["VertexAttribIFormat"] void( "VertexArrayAttribIFormat", "DSA version of ${src.javaDocLink}.", GLuint("vaobj", "the vertex array object name"), src["attribindex"], src["size"], src["type"], src["relativeoffset"] ) src = GL43["VertexAttribLFormat"] void( "VertexArrayAttribLFormat", "DSA version of ${src.javaDocLink}.", GLuint("vaobj", "the vertex array object name"), src["attribindex"], src["size"], src["type"], src["relativeoffset"] ) src = GL43["VertexAttribBinding"] void( "VertexArrayAttribBinding", "DSA version of ${src.javaDocLink}.", GLuint("vaobj", "the vertex array object name"), src["attribindex"], src["bindingindex"] ) src = GL43["VertexBindingDivisor"] void( "VertexArrayBindingDivisor", "DSA version of ${src.javaDocLink}.", GLuint("vaobj", "the vertex array object name"), src["bindingindex"], src["divisor"] ) void( "GetVertexArrayiv", "Queries parameters of a vertex array object.", GLuint("vaobj", "the vertex array object name"), GLenum("pname", "the parameter to query", "#ELEMENT_ARRAY_BUFFER_BINDING"), Check(1)..ReturnParam..GLint.p("param", "the buffer in which to return the parameter values") ) void( "GetVertexArrayIndexediv", "Queries parameters of an attribute of a vertex array object.", GLuint("vaobj", "the vertex array object name"), GLuint("index", "the attribute to query"), GLenum( "pname", "the parameter to query", """ #VERTEX_ATTRIB_ARRAY_ENABLED #VERTEX_ATTRIB_ARRAY_SIZE, #VERTEX_ATTRIB_ARRAY_STRIDE #VERTEX_ATTRIB_ARRAY_TYPE #VERTEX_ATTRIB_ARRAY_NORMALIZED #VERTEX_ATTRIB_ARRAY_INTEGER #VERTEX_ATTRIB_ARRAY_DIVISOR #VERTEX_ATTRIB_ARRAY_LONG #VERTEX_ATTRIB_RELATIVE_OFFSET """ ), Check(1)..ReturnParam..GLint.p("param", "the buffer in which to return the parameter values") ) void( "GetVertexArrayIndexed64iv", "Queries parameters of an attribute of a vertex array object.", GLuint("vaobj", "the vertex array object name"), GLuint("index", "the attribute to query"), GLenum("pname", "the parameter to query", "#VERTEX_BINDING_OFFSET"), Check(1)..ReturnParam..GLint64.p("param", "the buffer in which to return the parameter values") ) void( "CreateSamplers", "Returns {@code n} previously unused sampler names in {@code samplers}, each representing a new sampler object.", AutoSize("samplers")..GLsizei("n", "the number of sampler object names to create"), ReturnParam..GLuint.p("samplers", "the buffer in which to return the created sampler object names") ) void( "CreateProgramPipelines", "Returns {@code n} previously unused program pipeline names in {@code pipelines}, each representing a new program pipeline object.", AutoSize("pipelines")..GLsizei("n", "the number of program pipeline names to create"), ReturnParam..GLuint.p("pipelines", "the buffer in which to return the created program pipeline names") ) void( "CreateQueries", "Returns {@code n} previously unused query object names in {@code ids}, each representing a new query object with the specified {@code target}.", GLenum("target", "the query target", QUERY_TARGETS), AutoSize("ids")..GLsizei("n", "the number of query object names to create"), ReturnParam..GLuint.p("ids", "the buffer in which to return the created query object names") ) void( "GetQueryBufferObjectiv", "Queries the state of a query object.", GLuint("id", "the name of a query object"), GLuint("buffer", "the name of a buffer object"), GLenum("pname", "the state to query"), GLintptr("offset", "the offset into {@code buffer} at which the queried value is written") ) void( "GetQueryBufferObjectuiv", "Unsigned version of #GetQueryBufferObjectiv().", this["GetQueryBufferObjectiv"]["id"], this["GetQueryBufferObjectiv"]["buffer"], this["GetQueryBufferObjectiv"]["pname"], this["GetQueryBufferObjectiv"]["offset"] ) void( "GetQueryBufferObjecti64v", "64bit version of #GetQueryBufferObjectiv().", this["GetQueryBufferObjectiv"]["id"], this["GetQueryBufferObjectiv"]["buffer"], this["GetQueryBufferObjectiv"]["pname"], this["GetQueryBufferObjectiv"]["offset"] ) void( "GetQueryBufferObjectui64v", "64bit version of #GetQueryBufferObjectuiv().", this["GetQueryBufferObjectiv"]["id"], this["GetQueryBufferObjectiv"]["buffer"], this["GetQueryBufferObjectiv"]["pname"], this["GetQueryBufferObjectiv"]["offset"] ) // ARB_ES3_1_compatibility void( "MemoryBarrierByRegion", """ Behaves like #MemoryBarrier(), with two differences: First, it narrows the region under consideration so that only reads/writes of prior fragment shaders that are invoked for a smaller region of the framebuffer will be completed/reflected prior to subsequent reads/write of following fragment shaders. The size of the region is implementation dependent and may be as small as one framebuffer pixel. Second, it only applies to memory transactions that may be read by or written by a fragment shader. When barriers is #ALL_BARRIER_BITS, shader memory accesses will be synchronized relative to all these barrier bits, but not to other barrier bits specific to #MemoryBarrier(). This implies that reads/writes for scatter/gather-like algorithms may or may not be completed/reflected after a MemoryBarrierByRegion command. However, for uses such as deferred shading, where a linked list of visible surfaces with the head at a framebuffer address may be constructed, and the entirety of the list is only dependent on previous executions at that framebuffer address, MemoryBarrierByRegion may be significantly more efficient than #MemoryBarrier(). """, GLbitfield( "barriers", "the barriers to insert", """ #ATOMIC_COUNTER_BARRIER_BIT #FRAMEBUFFER_BARRIER_BIT #SHADER_IMAGE_ACCESS_BARRIER_BIT #SHADER_STORAGE_BARRIER_BIT #TEXTURE_FETCH_BARRIER_BIT #UNIFORM_BARRIER_BIT """, LinkMode.BITFIELD ) ) // ARB_get_texture_sub_image void( "GetTextureSubImage", "Obtains sub-regions of a texture image from a texture object.", GLuint("texture", "the source texture object name"), GLint("level", "the level-of-detail number"), GLint("xoffset", "the x-position of the subregion"), GLint("yoffset", "the y-position of the subregion"), GLint("zoffset", "the z-position of the subregion"), GLsizei("width", "the subregion width"), GLsizei("height", "the subregion height"), GLsizei("depth", "the subregion depth"), GLenum("format", "the pixel format", PIXEL_DATA_FORMATS), GLenum("type", "the pixel type", PIXEL_DATA_TYPES), AutoSize("pixels")..GLsizei("bufSize", "the size of the buffer to receive the retrieved pixel data"), MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE)..RawPointer..void.p("pixels", "the buffer in which to place the returned data") ) void( "GetCompressedTextureSubImage", "Obtains a sub-region of a compressed texture image.", GLuint("texture", "the source texture object name"), GLint("level", "the level-of-detail number"), GLint("xoffset", "the x-position of the subregion"), GLint("yoffset", "the y-position of the subregion"), GLint("zoffset", "the z-position of the subregion"), GLsizei("width", "the subregion width"), GLsizei("height", "the subregion height"), GLsizei("depth", "the subregion depth"), AutoSize("pixels")..GLsizei("bufSize", "the size of the buffer to receive the retrieved pixel data"), MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE)..RawPointer..void.p("pixels", "the buffer in which to place the returned data") ) // ARB_texture_barrier void( "TextureBarrier", "Guarantees that writes have completed and caches have been invalidated before subsequent Draws are executed." ) // KHR_context_flush_control IntConstant( "Accepted by the {@code pname} parameter of GetIntegerv, GetFloatv, GetBooleanv GetDoublev and GetInteger64v.", "CONTEXT_RELEASE_BEHAVIOR"..0x82FB ) IntConstant( "Returned in {@code data} by GetIntegerv, GetFloatv, GetBooleanv GetDoublev and GetInteger64v when {@code pname} is #CONTEXT_RELEASE_BEHAVIOR.", "CONTEXT_RELEASE_BEHAVIOR_FLUSH"..0x82FC ) // KHR_robustness IntConstant( "Returned by #GetGraphicsResetStatus().", "GUILTY_CONTEXT_RESET"..0x8253, "INNOCENT_CONTEXT_RESET"..0x8254, "UNKNOWN_CONTEXT_RESET"..0x8255 ) IntConstant( "Accepted by the {@code value} parameter of GetBooleanv, GetIntegerv, and GetFloatv.", "RESET_NOTIFICATION_STRATEGY"..0x8256 ) IntConstant( "Returned by GetIntegerv and related simple queries when {@code value} is #RESET_NOTIFICATION_STRATEGY.", "LOSE_CONTEXT_ON_RESET"..0x8252, "NO_RESET_NOTIFICATION"..0x8261 ) IntConstant( "Returned by GetIntegerv when {@code pname} is CONTEXT_FLAGS.", "CONTEXT_FLAG_ROBUST_ACCESS_BIT"..0x00000004 ) IntConstant( "Returned by #GetError().", "CONTEXT_LOST"..0x0507 ) GLenum( "GetGraphicsResetStatus", """ Indicates if the GL context has been in a reset state at any point since the last call to GetGraphicsResetStatus: ${ul( "#NO_ERROR indicates that the GL context has not been in a reset state since the last call.", "#GUILTY_CONTEXT_RESET indicates that a reset has been detected that is attributable to the current GL context.", "#INNOCENT_CONTEXT_RESET indicates a reset has been detected that is not attributable to the current GL context.", "#UNKNOWN_CONTEXT_RESET indicates a detected graphics reset whose cause is unknown." )} If a reset status other than NO_ERROR is returned and subsequent calls return NO_ERROR, the context reset was encountered and completed. If a reset status is repeatedly returned, the context may be in the process of resetting. Reset notification behavior is determined at context creation time, and may be queried by calling GetIntegerv with the symbolic constant #RESET_NOTIFICATION_STRATEGY. If the reset notification behavior is #NO_RESET_NOTIFICATION, then the implementation will never deliver notification of reset events, and GetGraphicsResetStatus will always return NO_ERROR. If the behavior is #LOSE_CONTEXT_ON_RESET, a graphics reset will result in a lost context and require creating a new context as described above. In this case GetGraphicsResetStatus will return an appropriate value from those described above. If a graphics reset notification occurs in a context, a notification must also occur in all other contexts which share objects with that context. After a graphics reset has occurred on a context, subsequent GL commands on that context (or any context which shares with that context) will generate a #CONTEXT_LOST error. Such commands will not have side effects (in particular, they will not modify memory passed by pointer for query results, and may not block indefinitely or cause termination of the application. Exceptions to this behavior include: ${ul( """ #GetError() and GetGraphicsResetStatus behave normally following a graphics reset, so that the application can determine a reset has occurred, and when it is safe to destroy and recreate the context. """, """ Any commands which might cause a polling application to block indefinitely will generate a CONTEXT_LOST error, but will also return a value indicating completion to the application. """ )} """, void() ) src = GL11C["GetTexImage"] IgnoreMissing..void( "GetnTexImage", "Robust version of ${src.javaDocLink}", src["tex"], src["level"], src["format"], src["type"], AutoSize("img")..GLsizei("bufSize", "the maximum number of bytes to write into {@code img}"), MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE)..RawPointer..void.p("img", "a buffer in which to place the returned data") ) void( "ReadnPixels", "Behaves identically to #ReadPixels() except that it does not write more than {@code bufSize} bytes into {@code data}", GLint("x", "the left pixel coordinate"), GLint("y", "the lower pixel coordinate"), GLsizei("width", "the number of pixels to read in the x-dimension"), GLsizei("height", "the number of pixels to read in the y-dimension"), GLenum("format", "the pixel format", PIXEL_DATA_FORMATS), GLenum("type", "the pixel type", PIXEL_DATA_TYPES), AutoSize("pixels")..GLsizei("bufSize", "the maximum number of bytes to write into {@code data}"), MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT)..RawPointer..void.p("pixels", "a buffer in which to place the returned pixel data") ) src = GL13C["GetCompressedTexImage"] IgnoreMissing..void( "GetnCompressedTexImage", "Robust version of ${src.javaDocLink}", src["target"], src["level"], AutoSize("img")..GLsizei("bufSize", "the maximum number of bytes to write into {@code img}"), Check( expression = "GL11.glGetTexLevelParameteri(target, level, GL13.GL_TEXTURE_COMPRESSED_IMAGE_SIZE)", debug = true )..RawPointer..void.p("img", "a buffer in which to place the returned data") ) void( "GetnUniformfv", "Returns the value or values of a uniform of the default uniform block.", GLuint("program", "the program object"), GLint("location", "the uniform location"), AutoSize("params")..GLsizei("bufSize", "the maximum number of bytes to write to {@code params}"), ReturnParam..GLfloat.p("params", "the buffer in which to place the returned data") ) IgnoreMissing..void( "GetnUniformdv", "Double version of #GetnUniformfv().", GLuint("program", "the program object"), GLint("location", "the uniform location"), AutoSize("params")..GLsizei("bufSize", "the maximum number of bytes to write to {@code params}"), ReturnParam..GLdouble.p("params", "the buffer in which to place the returned data") ) void( "GetnUniformiv", "Integer version of #GetnUniformfv().", GLuint("program", "the program object"), GLint("location", "the uniform location"), AutoSize("params")..GLsizei("bufSize", "the maximum number of bytes to write to {@code params}"), ReturnParam..GLint.p("params", "the buffer in which to place the returned data") ) void( "GetnUniformuiv", "Unsigned version of #GetnUniformiv().", GLuint("program", "the program object"), GLint("location", "the uniform location"), AutoSize("params")..GLsizei("bufSize", "the maximum number of bytes to write to {@code params}"), ReturnParam..GLuint.p("params", "the buffer in which to place the returned data") ) }
bsd-3-clause
9b0ecf64f61aa48e8eb54a2fbb679485
29.148847
204
0.596518
4.708797
false
false
false
false
iSoron/uhabits
uhabits-android/src/main/java/org/isoron/uhabits/receivers/WidgetReceiver.kt
1
4977
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.receivers import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import dagger.Component import org.isoron.uhabits.HabitsApplication import org.isoron.uhabits.core.ui.widgets.WidgetBehavior import org.isoron.uhabits.inject.HabitsApplicationComponent import org.isoron.uhabits.intents.IntentParser.CheckmarkIntentData /** * The Android BroadcastReceiver for Loop Habit Tracker. * * * All broadcast messages are received and processed by this class. */ class WidgetReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val app = context.applicationContext as HabitsApplication val component = DaggerWidgetReceiver_WidgetComponent .builder() .habitsApplicationComponent(app.component) .build() val parser = app.component.intentParser val controller = component.widgetController val prefs = app.component.preferences val widgetUpdater = app.component.widgetUpdater Log.i(TAG, String.format("Received intent: %s", intent.toString())) lastReceivedIntent = intent try { var data: CheckmarkIntentData? = null if (intent.action !== ACTION_UPDATE_WIDGETS_VALUE) { data = parser.parseCheckmarkIntent(intent) } when (intent.action) { ACTION_ADD_REPETITION -> { Log.d( TAG, String.format( "onAddRepetition habit=%d timestamp=%d", data!!.habit.id, data.timestamp.unixTime ) ) controller.onAddRepetition( data.habit, data.timestamp ) } ACTION_TOGGLE_REPETITION -> { Log.d( TAG, String.format( "onToggleRepetition habit=%d timestamp=%d", data!!.habit.id, data.timestamp.unixTime ) ) controller.onToggleRepetition( data.habit, data.timestamp ) } ACTION_REMOVE_REPETITION -> { Log.d( TAG, String.format( "onRemoveRepetition habit=%d timestamp=%d", data!!.habit.id, data.timestamp.unixTime ) ) controller.onRemoveRepetition( data.habit, data.timestamp ) } ACTION_UPDATE_WIDGETS_VALUE -> { widgetUpdater.updateWidgets() widgetUpdater.scheduleStartDayWidgetUpdate() } } } catch (e: RuntimeException) { Log.e("WidgetReceiver", "could not process intent", e) } } @ReceiverScope @Component(dependencies = [HabitsApplicationComponent::class]) internal interface WidgetComponent { val widgetController: WidgetBehavior } companion object { const val ACTION_ADD_REPETITION = "org.isoron.uhabits.ACTION_ADD_REPETITION" const val ACTION_DISMISS_REMINDER = "org.isoron.uhabits.ACTION_DISMISS_REMINDER" const val ACTION_REMOVE_REPETITION = "org.isoron.uhabits.ACTION_REMOVE_REPETITION" const val ACTION_TOGGLE_REPETITION = "org.isoron.uhabits.ACTION_TOGGLE_REPETITION" const val ACTION_UPDATE_WIDGETS_VALUE = "org.isoron.uhabits.ACTION_UPDATE_WIDGETS_VALUE" private const val TAG = "WidgetReceiver" var lastReceivedIntent: Intent? = null private set fun clearLastReceivedIntent() { lastReceivedIntent = null } } }
gpl-3.0
19d83f47d09c30784da4b0c92ec9b3d2
37.875
96
0.568127
5.299255
false
false
false
false
jguerinet/MyMartlet-Android
parser/src/main/kotlin/com/guerinet/mymartlet/parser/Ebill.kt
2
2685
/* * Copyright 2014-2019 Julien Guerinet * * 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.guerinet.mymartlet.parser import com.guerinet.mymartlet.model.Statement import org.jsoup.nodes.Element /** * Parses student ebill * Data found through paths * https://horizon.mcgill.ca/pban1/bztkcbil.pm_viewbills * * @author Allan Wang * @since 2.3.2 */ internal fun Element.parseEbill(debugger: ParseDebugger = ParseDebuggerNoOp): List<Statement> { fun notFound(message: String): List<Statement> { debugger.notFound("parseEbill: $message") return emptyList() } val table = selectFirst(DISPLAY_TABLE_QUERY) ?: return notFound(DISPLAY_TABLE_QUERY) // Drop first element as it is the header; avoids unnecessary debugger logs return table.getElementsByTag("tr").asSequence().drop(1).mapNotNull { it.parseStatement(debugger) }.toList() } private fun Element.parseStatement(debugger: ParseDebugger = ParseDebuggerNoOp): Statement? { fun notFound(message: String): Statement? { debugger.notFound("parseStatement: $message") return null } if (tagName() != "tr") { return notFound("Invalid tag ${tagName()}") } val tds = getElementsByTag("td") .map { it.text() } .filter { it.isNotBlank() } if (tds.isEmpty()) { // Every other row is empty, so this is expected return null } val dates = tds.mapNotNull { it.parseDateAbbrev() } if (dates.size != 2) { return notFound("Invalid date count ${dates.size}") } val amount = tds.asSequence().mapNotNull { it.parseAmount() }.firstOrNull() ?: return notFound("No dollar amount found") return Statement(dates[0], dates[1], amount) } private fun String.parseAmount(): Double? { if (!contains('$')) { return null } val negative = endsWith('-') // Instead of filtering for numbers, // We will explicitly remove characters that we know should be in the string // to avoid over trimming val value = filter { it != ',' && it != '$' && it != '-' } .toDoubleOrNull() ?: return null return if (negative) -value else value }
apache-2.0
56a8415593fbeb370b811e9b91cc594c
31.743902
112
0.670764
4.118098
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/ui/movie/detail/MovieDetailPresenter.kt
1
4647
package com.ashish.movieguide.ui.movie.detail import com.ashish.movieguide.R import com.ashish.movieguide.data.interactors.MovieInteractor import com.ashish.movieguide.data.models.FullDetailContent import com.ashish.movieguide.data.models.MovieDetail import com.ashish.movieguide.di.scopes.ActivityScope import com.ashish.movieguide.ui.base.detail.fulldetail.FullDetailContentPresenter import com.ashish.movieguide.ui.common.personalcontent.PersonalContentManager import com.ashish.movieguide.ui.common.rating.RatingManager import com.ashish.movieguide.utils.Constants.MEDIA_TYPE_MOVIE import com.ashish.movieguide.utils.extensions.convertListToCommaSeparatedText import com.ashish.movieguide.utils.extensions.getFormattedCurrency import com.ashish.movieguide.utils.extensions.getFormattedMediumDate import com.ashish.movieguide.utils.extensions.getFormattedRuntime import com.ashish.movieguide.utils.extensions.getRatingValue import com.ashish.movieguide.utils.schedulers.BaseSchedulerProvider import java.util.ArrayList import javax.inject.Inject /** * Created by Ashish on Dec 31. */ @ActivityScope class MovieDetailPresenter @Inject constructor( private val movieInteractor: MovieInteractor, private val personalContentManager: PersonalContentManager, private val ratingManager: RatingManager, schedulerProvider: BaseSchedulerProvider ) : FullDetailContentPresenter<MovieDetail, MovieDetailView>(schedulerProvider) { override fun attachView(view: MovieDetailView) { super.attachView(view) ratingManager.setView(view) personalContentManager.setView(view) } override fun getDetailContent(id: Long) = movieInteractor.getFullMovieDetail(id) override fun showDetailContent(fullDetailContent: FullDetailContent<MovieDetail>) { super.showDetailContent(fullDetailContent) getView()?.apply { hideProgress() val movieDetail = fullDetailContent.detailContent val accountState = movieDetail?.movieRatings personalContentManager.setAccountState(accountState) showSavedRating(accountState?.getRatingValue()) setTMDbRating(movieDetail?.voteAverage) showItemList(movieDetail?.similarMovieResults?.results) { showSimilarMoviesList(it) } } } override fun getContentList(fullDetailContent: FullDetailContent<MovieDetail>): List<String> { val contentList = ArrayList<String>() fullDetailContent.detailContent?.apply { val omdbDetail = fullDetailContent.omdbDetail contentList.apply { add(overview ?: "") add(tagline ?: "") add(genres.convertListToCommaSeparatedText { it.name.toString() }) add(omdbDetail?.Rated ?: "") add(status ?: "") add(omdbDetail?.Awards ?: "") add(omdbDetail?.Production ?: "") add(omdbDetail?.Country ?: "") add(omdbDetail?.Language ?: "") add(releaseDate.getFormattedMediumDate()) add(runtime.getFormattedRuntime()) add(budget.getFormattedCurrency()) add(revenue.getFormattedCurrency()) } } return contentList } override fun getBackdropImages(detailContent: MovieDetail) = detailContent.images?.backdrops override fun getPosterImages(detailContent: MovieDetail) = detailContent.images?.posters override fun getVideos(detailContent: MovieDetail) = detailContent.videos override fun getCredits(detailContent: MovieDetail) = detailContent.creditsResults override fun getErrorMessageId() = R.string.error_load_movie_detail fun markAsFavorite() { personalContentManager.markAsFavorite(getMovieId(), MEDIA_TYPE_MOVIE) } fun addToWatchlist() { personalContentManager.addToWatchlist(getMovieId(), MEDIA_TYPE_MOVIE) } fun saveRating(rating: Double) { val movieId = getMovieId() ratingManager.saveRating(movieInteractor.rateMovie(movieId, rating), movieId, rating) } fun deleteRating() { val movieId = getMovieId() ratingManager.deleteRating(movieInteractor.deleteMovieRating(movieId), movieId) } private fun getMovieId() = fullDetailContent?.detailContent?.id!! override fun detachView() { super.detachView() ratingManager.setView(null) personalContentManager.setView(null) } override fun onDestroy() { super.onDestroy() ratingManager.unsubscribe() personalContentManager.unsubscribe() } }
apache-2.0
b98de41c44ab942fd03e8d611fe6893e
38.058824
98
0.7153
5.117841
false
false
false
false
sys1yagi/DroiDon
app/src/test/java/com/sys1yagi/mastodon/android/ui/auth/setinstancename/SetInstanceNameInteractorTest.kt
1
3676
package com.sys1yagi.mastodon.android.ui.auth.setinstancename import com.sys1yagi.kmockito.mock import com.sys1yagi.kmockito.verify import com.sys1yagi.mastodon.android.data.database.Credential import com.sys1yagi.mastodon.android.data.database.OrmaDatabase import com.sys1yagi.mastodon.android.data.database.OrmaDatabaseProvider import com.sys1yagi.mastodon.android.testtool.RxTestSchedulerRule import com.sys1yagi.mastodon.android.testtool.given import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE) class SetInstanceNameInteractorTest { @get:Rule val rule = RxTestSchedulerRule() lateinit var interactor: SetInstanceNameInteractor lateinit var output: SetInstanceNameContract.InteractorOutput lateinit var database: OrmaDatabase @Before fun setUp() { output = mock() database = OrmaDatabase.Builder(RuntimeEnvironment.application).name(null).build() interactor = SetInstanceNameInteractor(OrmaDatabaseProvider(database)) } @After fun tearDown() { database.deleteAll() } @Test fun saveInstanceNameEmpty() { given("the credential records is empty") { assertThat(database.selectFromCredential().count()).isEqualTo(0) interactor.startInteraction(output) on("add instance name") { interactor.saveInstanceName("mstdn.jp") rule.triggerActions() it("onInstanceNameSaved() is called") { output.verify().onInstanceNameSaved() } it("credential record is inserted") { assertThat(database.selectFromCredential().count()).isEqualTo(1) } } } } @Test fun saveInstanceNameDuplicated(){ given("there is a credential record") { database.insertIntoCredential(Credential().apply { instanceName = "mstdn.jp" }) assertThat(database.selectFromCredential().count()).isEqualTo(1) interactor.startInteraction(output) on("insert same instance name credential") { interactor.saveInstanceName("mstdn.jp") rule.triggerActions() it("onInstanceNameSaved() is called") { output.verify().onInstanceNameSaved() } it("credential record count is 1") { assertThat(database.selectFromCredential().count()).isEqualTo(1) } } } } @Test fun saveInstanceNameMulti(){ given("there is a credential record") { database.insertIntoCredential(Credential().apply { instanceName = "mstdn.jp" }) assertThat(database.selectFromCredential().count()).isEqualTo(1) interactor.startInteraction(output) on("insert other instance name credential") { interactor.saveInstanceName("pawoo.net") rule.triggerActions() it("onInstanceNameSaved() is called") { output.verify().onInstanceNameSaved() } it("credential record count is 2") { assertThat(database.selectFromCredential().count()).isEqualTo(2) } } } } }
mit
48a7b1468c5021d167f3dbeb3212a398
31.821429
90
0.629761
5.199434
false
true
false
false
spotify/heroic
aggregation/cardinality/src/main/java/com/spotify/heroic/aggregation/cardinality/ExactCardinalityBucket.kt
1
2519
/* * Copyright (c) 2019 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.aggregation.cardinality import com.google.common.base.Charsets import com.google.common.collect.Ordering import com.google.common.hash.HashCode import com.google.common.hash.Hashing import com.spotify.heroic.metric.Metric import java.util.Collections import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger import kotlin.Boolean import kotlin.ByteArray import kotlin.Comparator import kotlin.Long import kotlin.RuntimeException import kotlin.String /** * Bucket that counts the number of seen events. * * @author udoprog */ data class ExactCardinalityBucket( override val timestamp: Long, private val includeKey: Boolean ) : CardinalityBucket { private val count = AtomicInteger(0) private val seen = Collections.newSetFromMap(ConcurrentHashMap<HashCode, Boolean>()) override fun update(key: Map<String, String>, d: Metric) { val hasher = HASH_FUNCTION.newHasher() if (includeKey) { for (k in KEY_ORDER.sortedCopy(key.keys)) { hasher.putString(k, Charsets.UTF_8).putString(key[k].orEmpty(), Charsets.UTF_8) } } d.hash(hasher) if (seen.add(hasher.hash())) { count.incrementAndGet() } } override fun count(): Long { return count.get().toLong() } override fun state(): ByteArray { throw RuntimeException("Bucket does not support state persisting") } companion object { private val HASH_FUNCTION = Hashing.goodFastHash(128) private val KEY_ORDER = Ordering.from(Comparator<String> { obj, s -> obj.compareTo(s) }) } }
apache-2.0
e7a7f76c78543a44c5b1be20a547e6a9
30.4875
96
0.711393
4.191348
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/gradle/AndroidIR.kt
3
3273
// 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.tools.projectWizard.ir.buildsystem.gradle import org.jetbrains.kotlin.tools.projectWizard.core.asStringWithUnixSlashes import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.FreeIR import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter import org.jetbrains.kotlin.tools.projectWizard.settings.JavaPackage import java.nio.file.Path interface AndroidIR : GradleIR //TODO parameterize data class AndroidConfigIR( val javaPackage: JavaPackage?, val newManifestPath: Path?, val printVersionCode: Boolean, val printBuildTypes: Boolean, var androidSdkVersion: String = "31" ) : AndroidIR, FreeIR { override fun GradlePrinter.renderGradle() { sectionCall("android", needIndent = true) { call("compileSdkVersion") { +androidSdkVersion }; nlIndented() if (newManifestPath != null) { when (dsl) { GradlePrinter.GradleDsl.KOTLIN -> { +"""sourceSets["main"].manifest.srcFile("${newManifestPath.asStringWithUnixSlashes()}")""" } GradlePrinter.GradleDsl.GROOVY -> { +"""sourceSets.main.manifest.srcFile('${newManifestPath.asStringWithUnixSlashes()}')""" } } nlIndented() } sectionCall("defaultConfig", needIndent = true) { if (javaPackage != null) { assignmentOrCall("applicationId") { +javaPackage.asCodePackage().quotified }; nlIndented() } call("minSdkVersion") { +"24" }; nlIndented() // TODO dehardcode call("targetSdkVersion") { +androidSdkVersion } if (printVersionCode) { nlIndented() assignmentOrCall("versionCode") { +"1" }; nlIndented() assignmentOrCall("versionName") { +"1.0".quotified } } } nlIndented() sectionCall("compileOptions", needIndent = true) { assignmentOrCall("sourceCompatibility") { +"JavaVersion.VERSION_1_8" }; nlIndented() assignmentOrCall("targetCompatibility") { +"JavaVersion.VERSION_1_8" } } if (printBuildTypes) { nlIndented() sectionCall("buildTypes", needIndent = true) { val sectionIdentifier = when (dsl) { GradlePrinter.GradleDsl.KOTLIN -> """getByName("release")""" GradlePrinter.GradleDsl.GROOVY -> "release".quotified } sectionCall(sectionIdentifier, needIndent = true) { val minifyCallName = when (dsl) { GradlePrinter.GradleDsl.KOTLIN -> "isMinifyEnabled" GradlePrinter.GradleDsl.GROOVY -> "minifyEnabled" } assignmentOrCall(minifyCallName) { +"false" } } } } } } }
apache-2.0
2c24364a26890c7c49100f8934fd266d
45.757143
158
0.56798
5.482412
false
false
false
false
DreierF/MyTargets
shared/src/main/java/de/dreier/mytargets/shared/models/TimerSettings.kt
1
1775
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.shared.models import android.os.Parcel import android.os.Parcelable data class TimerSettings( var enabled: Boolean = false, var sound: Boolean = false, var vibrate: Boolean = false, var waitTime: Int = 0, var shootTime: Int = 0, var warnTime: Int = 0) : Parcelable { constructor(source: Parcel) : this( 1 == source.readInt(), 1 == source.readInt(), 1 == source.readInt(), source.readInt(), source.readInt(), source.readInt() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeInt((if (enabled) 1 else 0)) writeInt((if (sound) 1 else 0)) writeInt((if (vibrate) 1 else 0)) writeInt(waitTime) writeInt(shootTime) writeInt(warnTime) } companion object { @JvmField val CREATOR: Parcelable.Creator<TimerSettings> = object : Parcelable.Creator<TimerSettings> { override fun createFromParcel(source: Parcel): TimerSettings = TimerSettings(source) override fun newArray(size: Int): Array<TimerSettings?> = arrayOfNulls(size) } } }
gpl-2.0
0db8276dcd2981c8f79a1cf1ea61c3c9
31.272727
101
0.642254
4.426434
false
false
false
false
ssseasonnn/RxDownload
rxdownload4/src/main/java/zlc/season/rxdownload4/downloader/NormalDownloader.kt
1
3253
package zlc.season.rxdownload4.downloader import io.reactivex.Emitter import io.reactivex.Flowable import io.reactivex.Flowable.generate import io.reactivex.functions.BiConsumer import io.reactivex.functions.Consumer import okhttp3.ResponseBody import okio.* import retrofit2.Response import zlc.season.rxdownload4.Progress import zlc.season.rxdownload4.task.TaskInfo import zlc.season.rxdownload4.utils.* import java.io.File import java.util.concurrent.Callable class NormalDownloader : Downloader { private var alreadyDownloaded = false private lateinit var file: File private lateinit var shadowFile: File override fun download(taskInfo: TaskInfo, response: Response<ResponseBody>): Flowable<Progress> { val body = response.body() ?: throw RuntimeException("Response body is NULL") file = taskInfo.task.getFile() shadowFile = file.shadow() beforeDownload(taskInfo, response) return if (alreadyDownloaded) { Flowable.just(Progress( downloadSize = response.contentLength(), totalSize = response.contentLength() )) } else { startDownload(body, Progress( totalSize = response.contentLength(), isChunked = response.isChunked() )) } } private fun beforeDownload(taskInfo: TaskInfo, response: Response<ResponseBody>) { //make sure dir is exists val fileDir = taskInfo.task.getDir() if (!fileDir.exists() || !fileDir.isDirectory) { fileDir.mkdirs() } if (file.exists()) { if (taskInfo.validator.validate(file, response)) { alreadyDownloaded = true } else { file.delete() shadowFile.recreate() } } else { shadowFile.recreate() } } private fun startDownload(body: ResponseBody, progress: Progress): Flowable<Progress> { return generate( Callable { InternalState( body.source(), shadowFile.sink().buffer() ) }, BiConsumer<InternalState, Emitter<Progress>> { internalState, emitter -> internalState.apply { val readLen = source.read(buffer, 8192L) if (readLen == -1L) { sink.flush() shadowFile.renameTo(file) emitter.onComplete() } else { sink.emit() emitter.onNext(progress.apply { downloadSize += readLen }) } } }, Consumer { it.apply { sink.closeQuietly() source.closeQuietly() } }) } class InternalState( val source: BufferedSource, val sink: BufferedSink, val buffer: Buffer = sink.buffer ) }
apache-2.0
0447536d1f4de19905bc1826a5621f16
31.217822
101
0.523209
5.647569
false
false
false
false
vladmm/intellij-community
plugins/settings-repository/src/settings/IcsConfigurable.kt
9
1810
/* * 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 org.jetbrains.settingsRepository import com.intellij.openapi.options.ConfigurableBase import com.intellij.openapi.options.ConfigurableUi import java.awt.BorderLayout class IcsConfigurable : ConfigurableBase<IcsConfigurableUi, IcsSettings>("ics", icsMessage("ics.settings"), "reference.settings.ics") { override fun getSettings() = icsManager.settings override fun createUi() = IcsConfigurableUi() } class IcsConfigurableUi : ConfigurableUi<IcsSettings> { private val panel = IcsConfigurableForm() private val readOnlyEditor = createReadOnlySourcesEditor() init { panel.readOnlySourcesPanel.add(readOnlyEditor.component, BorderLayout.CENTER) } override fun reset(settings: IcsSettings) { panel.autoSyncCheckBox.isSelected = settings.autoSync readOnlyEditor.reset(settings) } override fun isModified(settings: IcsSettings) = panel.autoSyncCheckBox.isSelected != settings.autoSync || readOnlyEditor.isModified(settings) override fun apply(settings: IcsSettings) { settings.autoSync = panel.autoSyncCheckBox.isSelected readOnlyEditor.apply(settings) saveSettings(settings, icsManager.settingsFile) } override fun getComponent() = panel.rootPanel }
apache-2.0
8e3cc738c315d3cc94d6899fe9d77a5f
34.509804
144
0.775691
4.547739
false
true
false
false
Bugfry/exercism
exercism/kotlin/luhn/src/main/kotlin/Luhn.kt
2
570
class Luhn(val number: Long) { val addends = mutableListOf<Int>() val checkDigit: Int get() = addends.last() val checksum: Int get() = addends.sum() val isValid: Boolean get() = checksum % 10 == 0 val create: Long get() = 10 * number + (9 - Luhn(10 * number + 9).checksum % 10) init { var x = number var i = 0 if (x == 0L) addends += 0 while (x > 0L) { var next = (x % 10).toInt() if (i++ % 2 > 0) next *= 2 if (next > 9) next -= 9 addends += next x /= 10 } addends.reverse() } }
mit
f685198cafd90ebb158158f308fa29f7
18
67
0.507018
3.294798
false
false
false
false
JetBrains/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/artifact.kt
1
24497
// 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.bridgeEntities import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.url.VirtualFileUrl import kotlin.jvm.JvmName import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child interface ArtifactEntity : WorkspaceEntityWithSymbolicId { val name: String val artifactType: String val includeInProjectBuild: Boolean val outputUrl: VirtualFileUrl? @Child val rootElement: CompositePackagingElementEntity? val customProperties: List<@Child ArtifactPropertiesEntity> @Child val artifactOutputPackagingElement: ArtifactOutputPackagingElementEntity? override val symbolicId: ArtifactId get() = ArtifactId(name) //region generated code @GeneratedCodeApiVersion(1) interface Builder : ArtifactEntity, WorkspaceEntity.Builder<ArtifactEntity>, ObjBuilder<ArtifactEntity> { override var entitySource: EntitySource override var name: String override var artifactType: String override var includeInProjectBuild: Boolean override var outputUrl: VirtualFileUrl? override var rootElement: CompositePackagingElementEntity? override var customProperties: List<ArtifactPropertiesEntity> override var artifactOutputPackagingElement: ArtifactOutputPackagingElementEntity? } companion object : Type<ArtifactEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(name: String, artifactType: String, includeInProjectBuild: Boolean, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArtifactEntity { val builder = builder() builder.name = name builder.artifactType = artifactType builder.includeInProjectBuild = includeInProjectBuild builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ArtifactEntity, modification: ArtifactEntity.Builder.() -> Unit) = modifyEntity( ArtifactEntity.Builder::class.java, entity, modification) var ArtifactEntity.Builder.artifactExternalSystemIdEntity: @Child ArtifactExternalSystemIdEntity? by WorkspaceEntity.extension() //endregion interface ArtifactPropertiesEntity : WorkspaceEntity { val artifact: ArtifactEntity val providerType: String val propertiesXmlTag: String? //region generated code @GeneratedCodeApiVersion(1) interface Builder : ArtifactPropertiesEntity, WorkspaceEntity.Builder<ArtifactPropertiesEntity>, ObjBuilder<ArtifactPropertiesEntity> { override var entitySource: EntitySource override var artifact: ArtifactEntity override var providerType: String override var propertiesXmlTag: String? } companion object : Type<ArtifactPropertiesEntity, Builder>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(providerType: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArtifactPropertiesEntity { val builder = builder() builder.providerType = providerType builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ArtifactPropertiesEntity, modification: ArtifactPropertiesEntity.Builder.() -> Unit) = modifyEntity( ArtifactPropertiesEntity.Builder::class.java, entity, modification) //endregion @Abstract interface PackagingElementEntity : WorkspaceEntity { val parentEntity: CompositePackagingElementEntity? //region generated code @GeneratedCodeApiVersion(1) interface Builder<T : PackagingElementEntity> : PackagingElementEntity, WorkspaceEntity.Builder<T>, ObjBuilder<T> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? } companion object : Type<PackagingElementEntity, Builder<PackagingElementEntity>>() { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(entitySource: EntitySource, init: (Builder<PackagingElementEntity>.() -> Unit)? = null): PackagingElementEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } @Abstract interface CompositePackagingElementEntity : PackagingElementEntity { val artifact: ArtifactEntity? val children: List<@Child PackagingElementEntity> //region generated code @GeneratedCodeApiVersion(1) interface Builder<T : CompositePackagingElementEntity> : CompositePackagingElementEntity, PackagingElementEntity.Builder<T>, WorkspaceEntity.Builder<T>, ObjBuilder<T> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var artifact: ArtifactEntity? override var children: List<PackagingElementEntity> } companion object : Type<CompositePackagingElementEntity, Builder<CompositePackagingElementEntity>>(PackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(entitySource: EntitySource, init: (Builder<CompositePackagingElementEntity>.() -> Unit)? = null): CompositePackagingElementEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } interface DirectoryPackagingElementEntity: CompositePackagingElementEntity { val directoryName: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : DirectoryPackagingElementEntity, CompositePackagingElementEntity.Builder<DirectoryPackagingElementEntity>, WorkspaceEntity.Builder<DirectoryPackagingElementEntity>, ObjBuilder<DirectoryPackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var artifact: ArtifactEntity? override var children: List<PackagingElementEntity> override var directoryName: String } companion object : Type<DirectoryPackagingElementEntity, Builder>(CompositePackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(directoryName: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): DirectoryPackagingElementEntity { val builder = builder() builder.directoryName = directoryName builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: DirectoryPackagingElementEntity, modification: DirectoryPackagingElementEntity.Builder.() -> Unit) = modifyEntity( DirectoryPackagingElementEntity.Builder::class.java, entity, modification) //endregion interface ArchivePackagingElementEntity: CompositePackagingElementEntity { val fileName: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : ArchivePackagingElementEntity, CompositePackagingElementEntity.Builder<ArchivePackagingElementEntity>, WorkspaceEntity.Builder<ArchivePackagingElementEntity>, ObjBuilder<ArchivePackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var artifact: ArtifactEntity? override var children: List<PackagingElementEntity> override var fileName: String } companion object : Type<ArchivePackagingElementEntity, Builder>(CompositePackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(fileName: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArchivePackagingElementEntity { val builder = builder() builder.fileName = fileName builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ArchivePackagingElementEntity, modification: ArchivePackagingElementEntity.Builder.() -> Unit) = modifyEntity( ArchivePackagingElementEntity.Builder::class.java, entity, modification) //endregion interface ArtifactRootElementEntity: CompositePackagingElementEntity { //region generated code @GeneratedCodeApiVersion(1) interface Builder : ArtifactRootElementEntity, CompositePackagingElementEntity.Builder<ArtifactRootElementEntity>, WorkspaceEntity.Builder<ArtifactRootElementEntity>, ObjBuilder<ArtifactRootElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var artifact: ArtifactEntity? override var children: List<PackagingElementEntity> } companion object : Type<ArtifactRootElementEntity, Builder>(CompositePackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArtifactRootElementEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ArtifactRootElementEntity, modification: ArtifactRootElementEntity.Builder.() -> Unit) = modifyEntity( ArtifactRootElementEntity.Builder::class.java, entity, modification) //endregion interface ArtifactOutputPackagingElementEntity: PackagingElementEntity { val artifact: ArtifactId? //region generated code @GeneratedCodeApiVersion(1) interface Builder : ArtifactOutputPackagingElementEntity, PackagingElementEntity.Builder<ArtifactOutputPackagingElementEntity>, WorkspaceEntity.Builder<ArtifactOutputPackagingElementEntity>, ObjBuilder<ArtifactOutputPackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var artifact: ArtifactId? } companion object : Type<ArtifactOutputPackagingElementEntity, Builder>(PackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ArtifactOutputPackagingElementEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ArtifactOutputPackagingElementEntity, modification: ArtifactOutputPackagingElementEntity.Builder.() -> Unit) = modifyEntity( ArtifactOutputPackagingElementEntity.Builder::class.java, entity, modification) var ArtifactOutputPackagingElementEntity.Builder.artifactEntity: ArtifactEntity by WorkspaceEntity.extension() //endregion val ArtifactOutputPackagingElementEntity.artifactEntity: ArtifactEntity by WorkspaceEntity.extension() interface ModuleOutputPackagingElementEntity : PackagingElementEntity { val module: ModuleId? //region generated code @GeneratedCodeApiVersion(1) interface Builder : ModuleOutputPackagingElementEntity, PackagingElementEntity.Builder<ModuleOutputPackagingElementEntity>, WorkspaceEntity.Builder<ModuleOutputPackagingElementEntity>, ObjBuilder<ModuleOutputPackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var module: ModuleId? } companion object : Type<ModuleOutputPackagingElementEntity, Builder>(PackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleOutputPackagingElementEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ModuleOutputPackagingElementEntity, modification: ModuleOutputPackagingElementEntity.Builder.() -> Unit) = modifyEntity( ModuleOutputPackagingElementEntity.Builder::class.java, entity, modification) //endregion interface LibraryFilesPackagingElementEntity : PackagingElementEntity { val library: LibraryId? //region generated code @GeneratedCodeApiVersion(1) interface Builder : LibraryFilesPackagingElementEntity, PackagingElementEntity.Builder<LibraryFilesPackagingElementEntity>, WorkspaceEntity.Builder<LibraryFilesPackagingElementEntity>, ObjBuilder<LibraryFilesPackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var library: LibraryId? } companion object : Type<LibraryFilesPackagingElementEntity, Builder>(PackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): LibraryFilesPackagingElementEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: LibraryFilesPackagingElementEntity, modification: LibraryFilesPackagingElementEntity.Builder.() -> Unit) = modifyEntity( LibraryFilesPackagingElementEntity.Builder::class.java, entity, modification) var LibraryFilesPackagingElementEntity.Builder.libraryEntity: LibraryEntity by WorkspaceEntity.extension() //endregion val LibraryFilesPackagingElementEntity.libraryEntity: LibraryEntity by WorkspaceEntity.extension() interface ModuleSourcePackagingElementEntity : PackagingElementEntity { val module: ModuleId? //region generated code @GeneratedCodeApiVersion(1) interface Builder : ModuleSourcePackagingElementEntity, PackagingElementEntity.Builder<ModuleSourcePackagingElementEntity>, WorkspaceEntity.Builder<ModuleSourcePackagingElementEntity>, ObjBuilder<ModuleSourcePackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var module: ModuleId? } companion object : Type<ModuleSourcePackagingElementEntity, Builder>(PackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleSourcePackagingElementEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ModuleSourcePackagingElementEntity, modification: ModuleSourcePackagingElementEntity.Builder.() -> Unit) = modifyEntity( ModuleSourcePackagingElementEntity.Builder::class.java, entity, modification) //endregion interface ModuleTestOutputPackagingElementEntity : PackagingElementEntity { val module: ModuleId? //region generated code @GeneratedCodeApiVersion(1) interface Builder : ModuleTestOutputPackagingElementEntity, PackagingElementEntity.Builder<ModuleTestOutputPackagingElementEntity>, WorkspaceEntity.Builder<ModuleTestOutputPackagingElementEntity>, ObjBuilder<ModuleTestOutputPackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var module: ModuleId? } companion object : Type<ModuleTestOutputPackagingElementEntity, Builder>(PackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleTestOutputPackagingElementEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ModuleTestOutputPackagingElementEntity, modification: ModuleTestOutputPackagingElementEntity.Builder.() -> Unit) = modifyEntity( ModuleTestOutputPackagingElementEntity.Builder::class.java, entity, modification) //endregion @Abstract interface FileOrDirectoryPackagingElementEntity : PackagingElementEntity { val filePath: VirtualFileUrl //region generated code @GeneratedCodeApiVersion(1) interface Builder<T : FileOrDirectoryPackagingElementEntity> : FileOrDirectoryPackagingElementEntity, PackagingElementEntity.Builder<T>, WorkspaceEntity.Builder<T>, ObjBuilder<T> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var filePath: VirtualFileUrl } companion object : Type<FileOrDirectoryPackagingElementEntity, Builder<FileOrDirectoryPackagingElementEntity>>(PackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(filePath: VirtualFileUrl, entitySource: EntitySource, init: (Builder<FileOrDirectoryPackagingElementEntity>.() -> Unit)? = null): FileOrDirectoryPackagingElementEntity { val builder = builder() builder.filePath = filePath builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } interface DirectoryCopyPackagingElementEntity : FileOrDirectoryPackagingElementEntity { //region generated code @GeneratedCodeApiVersion(1) interface Builder : DirectoryCopyPackagingElementEntity, FileOrDirectoryPackagingElementEntity.Builder<DirectoryCopyPackagingElementEntity>, WorkspaceEntity.Builder<DirectoryCopyPackagingElementEntity>, ObjBuilder<DirectoryCopyPackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var filePath: VirtualFileUrl } companion object : Type<DirectoryCopyPackagingElementEntity, Builder>(FileOrDirectoryPackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(filePath: VirtualFileUrl, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): DirectoryCopyPackagingElementEntity { val builder = builder() builder.filePath = filePath builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: DirectoryCopyPackagingElementEntity, modification: DirectoryCopyPackagingElementEntity.Builder.() -> Unit) = modifyEntity( DirectoryCopyPackagingElementEntity.Builder::class.java, entity, modification) //endregion interface ExtractedDirectoryPackagingElementEntity: FileOrDirectoryPackagingElementEntity { val pathInArchive: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : ExtractedDirectoryPackagingElementEntity, FileOrDirectoryPackagingElementEntity.Builder<ExtractedDirectoryPackagingElementEntity>, WorkspaceEntity.Builder<ExtractedDirectoryPackagingElementEntity>, ObjBuilder<ExtractedDirectoryPackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var filePath: VirtualFileUrl override var pathInArchive: String } companion object : Type<ExtractedDirectoryPackagingElementEntity, Builder>(FileOrDirectoryPackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(filePath: VirtualFileUrl, pathInArchive: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ExtractedDirectoryPackagingElementEntity { val builder = builder() builder.filePath = filePath builder.pathInArchive = pathInArchive builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ExtractedDirectoryPackagingElementEntity, modification: ExtractedDirectoryPackagingElementEntity.Builder.() -> Unit) = modifyEntity( ExtractedDirectoryPackagingElementEntity.Builder::class.java, entity, modification) //endregion interface FileCopyPackagingElementEntity : FileOrDirectoryPackagingElementEntity { val renamedOutputFileName: String? //region generated code @GeneratedCodeApiVersion(1) interface Builder : FileCopyPackagingElementEntity, FileOrDirectoryPackagingElementEntity.Builder<FileCopyPackagingElementEntity>, WorkspaceEntity.Builder<FileCopyPackagingElementEntity>, ObjBuilder<FileCopyPackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var filePath: VirtualFileUrl override var renamedOutputFileName: String? } companion object : Type<FileCopyPackagingElementEntity, Builder>(FileOrDirectoryPackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(filePath: VirtualFileUrl, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): FileCopyPackagingElementEntity { val builder = builder() builder.filePath = filePath builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: FileCopyPackagingElementEntity, modification: FileCopyPackagingElementEntity.Builder.() -> Unit) = modifyEntity( FileCopyPackagingElementEntity.Builder::class.java, entity, modification) //endregion interface CustomPackagingElementEntity : CompositePackagingElementEntity { val typeId: String val propertiesXmlTag: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : CustomPackagingElementEntity, CompositePackagingElementEntity.Builder<CustomPackagingElementEntity>, WorkspaceEntity.Builder<CustomPackagingElementEntity>, ObjBuilder<CustomPackagingElementEntity> { override var entitySource: EntitySource override var parentEntity: CompositePackagingElementEntity? override var artifact: ArtifactEntity? override var children: List<PackagingElementEntity> override var typeId: String override var propertiesXmlTag: String } companion object : Type<CustomPackagingElementEntity, Builder>(CompositePackagingElementEntity) { @JvmOverloads @JvmStatic @JvmName("create") operator fun invoke(typeId: String, propertiesXmlTag: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): CustomPackagingElementEntity { val builder = builder() builder.typeId = typeId builder.propertiesXmlTag = propertiesXmlTag builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: CustomPackagingElementEntity, modification: CustomPackagingElementEntity.Builder.() -> Unit) = modifyEntity( CustomPackagingElementEntity.Builder::class.java, entity, modification) //endregion
apache-2.0
bead918d6cf905417384ab84d82000ce
38.767857
274
0.758664
6.564041
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/uast/uast-kotlin-fir/src/org/jetbrains/uast/kotlin/FirKotlinUastResolveProviderService.kt
1
26742
// 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.uast.kotlin import com.intellij.psi.* import com.intellij.psi.impl.compiled.ClsMemberImpl import com.intellij.psi.impl.file.PsiPackageImpl import com.intellij.util.SmartList import org.jetbrains.kotlin.analysis.api.base.KtConstantValue import org.jetbrains.kotlin.analysis.api.calls.* import org.jetbrains.kotlin.analysis.api.components.KtConstantEvaluationMode import org.jetbrains.kotlin.analysis.api.components.buildClassType import org.jetbrains.kotlin.analysis.api.components.buildTypeParameterType import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol import org.jetbrains.kotlin.analysis.api.types.* import org.jetbrains.kotlin.analysis.project.structure.KtLibraryModule import org.jetbrains.kotlin.analysis.project.structure.KtSourceModule import org.jetbrains.kotlin.analysis.project.structure.getKtModule import org.jetbrains.kotlin.asJava.toLightAnnotation import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.name.SpecialNames import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.types.typeUtil.TypeNullability import org.jetbrains.uast.* import org.jetbrains.uast.analysis.KotlinExtensionConstants.LAMBDA_THIS_PARAMETER_NAME import org.jetbrains.uast.kotlin.internal.* import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameterBase interface FirKotlinUastResolveProviderService : BaseKotlinUastResolveProviderService { override val languagePlugin: UastLanguagePlugin get() = firKotlinUastPlugin override val baseKotlinConverter: BaseKotlinConverter get() = FirKotlinConverter private val KtExpression.parentValueArgument: ValueArgument? get() = parents.firstOrNull { it is ValueArgument } as? ValueArgument override fun convertToPsiAnnotation(ktElement: KtElement): PsiAnnotation? { return ktElement.toLightAnnotation() } override fun convertValueArguments(ktCallElement: KtCallElement, parent: UElement): List<UNamedExpression>? { analyzeForUast(ktCallElement) { val argumentMapping = ktCallElement.resolveCall().singleFunctionCallOrNull()?.argumentMapping ?: return null val handledParameters = mutableSetOf<KtValueParameterSymbol>() val valueArguments = SmartList<UNamedExpression>() // NB: we need a loop over call element's value arguments to preserve their order. ktCallElement.valueArguments.forEach { val parameter = argumentMapping[it.getArgumentExpression()]?.symbol ?: return@forEach if (!handledParameters.add(parameter)) return@forEach val arguments = argumentMapping.entries .filter { (_, param) -> param.symbol == parameter } .mapNotNull { (arg, _) -> arg.parentValueArgument } val name = parameter.name.asString() when { arguments.size == 1 -> KotlinUNamedExpression.create(name, arguments.first(), parent) arguments.size > 1 -> KotlinUNamedExpression.create(name, arguments, parent) else -> null }?.let { valueArgument -> valueArguments.add(valueArgument) } } return valueArguments.ifEmpty { null } } } override fun findAttributeValueExpression(uAnnotation: KotlinUAnnotation, arg: ValueArgument): UExpression? { val annotationEntry = uAnnotation.sourcePsi analyzeForUast(annotationEntry) { val resolvedAnnotationCall = annotationEntry.resolveCall().singleCallOrNull<KtAnnotationCall>() ?: return null val parameter = resolvedAnnotationCall.argumentMapping[arg.getArgumentExpression()]?.symbol ?: return null val namedExpression = uAnnotation.attributeValues.find { it.name == parameter.name.asString() } return namedExpression?.expression as? KotlinUVarargExpression ?: namedExpression } } override fun findDefaultValueForAnnotationAttribute(ktCallElement: KtCallElement, name: String): KtExpression? { analyzeForUast(ktCallElement) { val resolvedAnnotationConstructorSymbol = ktCallElement.resolveCall().singleConstructorCallOrNull()?.symbol ?: return null val parameter = resolvedAnnotationConstructorSymbol.valueParameters.find { it.name.asString() == name } ?: return null return (parameter.psi as? KtParameter)?.defaultValue } } override fun getArgumentForParameter(ktCallElement: KtCallElement, index: Int, parent: UElement): UExpression? { analyzeForUast(ktCallElement) { val resolvedFunctionCall = ktCallElement.resolveCall().singleFunctionCallOrNull() val resolvedFunctionLikeSymbol = resolvedFunctionCall?.symbol ?: return null val parameter = resolvedFunctionLikeSymbol.valueParameters.getOrNull(index) ?: return null val arguments = resolvedFunctionCall.argumentMapping.entries .filter { (_, param) -> param.symbol == parameter } .mapNotNull { (arg, _) -> arg.parentValueArgument } return when { arguments.isEmpty() -> null arguments.size == 1 -> { val argument = arguments.single() if (parameter.isVararg && argument.getSpreadElement() == null) baseKotlinConverter.createVarargsHolder(arguments, parent) else baseKotlinConverter.convertOrEmpty(argument.getArgumentExpression(), parent) } else -> baseKotlinConverter.createVarargsHolder(arguments, parent) } } } override fun getImplicitReturn(ktLambdaExpression: KtLambdaExpression, parent: UElement): KotlinUImplicitReturnExpression? { val lastExpression = ktLambdaExpression.bodyExpression?.statements?.lastOrNull() ?: return null // Skip _explicit_ return. if (lastExpression is KtReturnExpression) return null analyzeForUast(ktLambdaExpression) { // TODO: Should check an explicit, expected return type as well // e.g., val y: () -> Unit = { 1 } // the lambda return type is Int, but we won't add an implicit return here. val returnType = ktLambdaExpression.functionLiteral.getAnonymousFunctionSymbol().returnType val returnUnitOrNothing = returnType.isUnit || returnType.isNothing return if (returnUnitOrNothing) null else KotlinUImplicitReturnExpression(parent).apply { returnExpression = baseKotlinConverter.convertOrEmpty(lastExpression, this) } } } override fun getImplicitParameters( ktLambdaExpression: KtLambdaExpression, parent: UElement, includeExplicitParameters: Boolean ): List<KotlinUParameter> { analyzeForUast(ktLambdaExpression) { val valueParameters = ktLambdaExpression.functionLiteral.getAnonymousFunctionSymbol().valueParameters if (includeExplicitParameters && valueParameters.isEmpty()) { val expectedType = ktLambdaExpression.getExpectedType() as? KtFunctionalType val lambdaImplicitReceiverType = expectedType?.ownTypeArguments?.get(0)?.type?.asPsiType( ktLambdaExpression, KtTypeMappingMode.DEFAULT_UAST, isAnnotationMethod = false ) ?: UastErrorType return listOf( KotlinUParameter( UastKotlinPsiParameterBase( name = LAMBDA_THIS_PARAMETER_NAME, type = lambdaImplicitReceiverType, parent = ktLambdaExpression, ktOrigin = ktLambdaExpression, language = ktLambdaExpression.language, isVarArgs = false, ktDefaultValue = null ), sourcePsi = null, parent ) ) } return valueParameters.map { p -> val psiType = p.returnType.asPsiType( ktLambdaExpression, KtTypeMappingMode.DEFAULT_UAST, isAnnotationMethod = false ) ?: UastErrorType KotlinUParameter( UastKotlinPsiParameterBase( name = p.name.asString(), type = psiType, parent = ktLambdaExpression, ktOrigin = ktLambdaExpression, language = ktLambdaExpression.language, isVarArgs = p.isVararg, ktDefaultValue = null ), null, parent ) } } } override fun getPsiAnnotations(psiElement: PsiModifierListOwner): Array<PsiAnnotation> { return psiElement.annotations } override fun getReferenceVariants(ktExpression: KtExpression, nameHint: String): Sequence<PsiElement> { analyzeForUast(ktExpression) { return ktExpression.collectCallCandidates().asSequence().mapNotNull { when (val candidate = it.candidate) { is KtFunctionCall<*> -> { toPsiMethod(candidate.partiallyAppliedSymbol.symbol, ktExpression) } is KtCompoundAccessCall -> { toPsiMethod(candidate.compoundAccess.operationPartiallyAppliedSymbol.symbol, ktExpression) } else -> null } } } } override fun resolveBitwiseOperators(ktBinaryExpression: KtBinaryExpression): UastBinaryOperator { val other = UastBinaryOperator.OTHER analyzeForUast(ktBinaryExpression) { val resolvedCall = ktBinaryExpression.resolveCall()?.singleFunctionCallOrNull() ?: return other val operatorName = resolvedCall.symbol.callableIdIfNonLocal?.callableName?.asString() ?: return other return KotlinUBinaryExpression.BITWISE_OPERATORS[operatorName] ?: other } } override fun resolveCall(ktElement: KtElement): PsiMethod? { analyzeForUast(ktElement) { val ktCallInfo = ktElement.resolveCall() ?: return null ktCallInfo.singleFunctionCallOrNull() ?.symbol ?.let { return toPsiMethod(it, ktElement) } return when (ktElement) { is KtPrefixExpression, is KtPostfixExpression -> { ktCallInfo.singleCallOrNull<KtCompoundVariableAccessCall>() ?.compoundAccess ?.operationPartiallyAppliedSymbol ?.signature ?.symbol ?.let { toPsiMethod(it, ktElement) } } else -> null } } } override fun resolveSyntheticJavaPropertyAccessorCall(ktSimpleNameExpression: KtSimpleNameExpression): PsiMethod? { return analyzeForUast(ktSimpleNameExpression) { val variableAccessCall = ktSimpleNameExpression.resolveCall()?.singleCallOrNull<KtSimpleVariableAccessCall>() ?: return null val propertySymbol = variableAccessCall.symbol as? KtSyntheticJavaPropertySymbol?: return null when (variableAccessCall.simpleAccess) { is KtSimpleVariableAccess.Read -> toPsiMethod(propertySymbol.getter, ktSimpleNameExpression) is KtSimpleVariableAccess.Write -> toPsiMethod(propertySymbol.setter ?: return null, ktSimpleNameExpression) } } } override fun isResolvedToExtension(ktCallElement: KtCallElement): Boolean { analyzeForUast(ktCallElement) { val ktCall = ktCallElement.resolveCall().singleFunctionCallOrNull() ?: return false return isExtension(ktCall) } } override fun resolvedFunctionName(ktCallElement: KtCallElement): String? { analyzeForUast(ktCallElement) { val resolvedFunctionLikeSymbol = ktCallElement.resolveCall().singleFunctionCallOrNull()?.symbol ?: return null return (resolvedFunctionLikeSymbol as? KtNamedSymbol)?.name?.identifierOrNullIfSpecial ?: (resolvedFunctionLikeSymbol as? KtConstructorSymbol)?.let { SpecialNames.INIT.asString() } } } override fun qualifiedAnnotationName(ktCallElement: KtCallElement): String? { analyzeForUast(ktCallElement) { val resolvedAnnotationConstructorSymbol = ktCallElement.resolveCall().singleConstructorCallOrNull()?.symbol ?: return null return resolvedAnnotationConstructorSymbol.containingClassIdIfNonLocal ?.asSingleFqName() ?.toString() } } override fun callKind(ktCallElement: KtCallElement): UastCallKind { analyzeForUast(ktCallElement) { val resolvedFunctionLikeSymbol = ktCallElement.resolveCall().singleFunctionCallOrNull()?.symbol ?: return UastCallKind.METHOD_CALL val fqName = resolvedFunctionLikeSymbol.callableIdIfNonLocal?.asSingleFqName() return when { resolvedFunctionLikeSymbol is KtSamConstructorSymbol || resolvedFunctionLikeSymbol is KtConstructorSymbol -> UastCallKind.CONSTRUCTOR_CALL fqName != null && isAnnotationArgumentArrayInitializer(ktCallElement, fqName) -> UastCallKind.NESTED_ARRAY_INITIALIZER else -> UastCallKind.METHOD_CALL } } } override fun isAnnotationConstructorCall(ktCallElement: KtCallElement): Boolean { analyzeForUast(ktCallElement) { val resolvedAnnotationConstructorSymbol = ktCallElement.resolveCall().singleConstructorCallOrNull()?.symbol ?: return false val ktType = resolvedAnnotationConstructorSymbol.returnType val context = containingKtClass(resolvedAnnotationConstructorSymbol) ?: ktCallElement val psiClass = toPsiClass(ktType, null, context, ktCallElement.typeOwnerKind) ?: return false return psiClass.isAnnotationType } } override fun resolveToClassIfConstructorCall(ktCallElement: KtCallElement, source: UElement): PsiClass? { analyzeForUast(ktCallElement) { val resolvedFunctionLikeSymbol = ktCallElement.resolveCall().singleFunctionCallOrNull()?.symbol ?: return null return when (resolvedFunctionLikeSymbol) { is KtConstructorSymbol -> { val context = containingKtClass(resolvedFunctionLikeSymbol) ?: ktCallElement toPsiClass(resolvedFunctionLikeSymbol.returnType, source, context, ktCallElement.typeOwnerKind) } is KtSamConstructorSymbol -> { toPsiClass(resolvedFunctionLikeSymbol.returnType, source, ktCallElement, ktCallElement.typeOwnerKind) } else -> null } } } override fun resolveToClass(ktAnnotationEntry: KtAnnotationEntry, source: UElement): PsiClass? { analyzeForUast(ktAnnotationEntry) { val resolvedAnnotationCall = ktAnnotationEntry.resolveCall().singleCallOrNull<KtAnnotationCall>() ?: return null val resolvedAnnotationConstructorSymbol = resolvedAnnotationCall.symbol val ktType = resolvedAnnotationConstructorSymbol.returnType val context = containingKtClass(resolvedAnnotationConstructorSymbol) ?: ktAnnotationEntry return toPsiClass(ktType, source, context, ktAnnotationEntry.typeOwnerKind) } } override fun resolveToDeclaration(ktExpression: KtExpression): PsiElement? { val resolvedTargetSymbol = when (ktExpression) { is KtExpressionWithLabel -> { analyzeForUast(ktExpression) { ktExpression.getTargetLabel()?.mainReference?.resolveToSymbol() } } is KtCallExpression -> { resolveCall(ktExpression)?.let { return it } } is KtReferenceExpression -> { analyzeForUast(ktExpression) { ktExpression.mainReference.resolveToSymbol() } } else -> null } ?: return null if (resolvedTargetSymbol is KtSyntheticJavaPropertySymbol && ktExpression is KtSimpleNameExpression) { // No PSI for this synthetic Java property. Either corresponding getter or setter has PSI. return resolveSyntheticJavaPropertyAccessorCall(ktExpression) } val resolvedTargetElement = analyzeForUast(ktExpression) { psiForUast(resolvedTargetSymbol, ktExpression.project) } // Shortcut: if the resolution target is compiled class/member, package info, or pure Java declarations, // we can return it early here (to avoid expensive follow-up steps: module retrieval and light element conversion). if (resolvedTargetElement is ClsMemberImpl<*> || resolvedTargetElement is PsiPackageImpl || !isKotlin(resolvedTargetElement) ) { return resolvedTargetElement } when ((resolvedTargetElement as? KtDeclaration)?.getKtModule(ktExpression.project)) { is KtSourceModule -> { // `getMaybeLightElement` tries light element conversion first, and then something else for local declarations. resolvedTargetElement.getMaybeLightElement(ktExpression)?.let { return it } } is KtLibraryModule -> { // For decompiled declarations, we can try light element conversion (only). (resolvedTargetElement as? KtDeclaration)?.toLightElements()?.singleOrNull()?.let { return it } } else -> {} } fun resolveToPsiClassOrEnumEntry(classOrObject: KtClassOrObject): PsiElement? { analyzeForUast(ktExpression) { val ktType = when (classOrObject) { is KtEnumEntry -> classOrObject.getEnumEntrySymbol().callableIdIfNonLocal?.classId?.let { enumClassId -> buildClassType(enumClassId) } else -> classOrObject.getClassOrObjectSymbol()?.let(::buildClassType) } ?: return null val psiClass = toPsiClass(ktType, source = null, classOrObject, classOrObject.typeOwnerKind) return when (classOrObject) { is KtEnumEntry -> psiClass?.findFieldByName(classOrObject.name, false) else -> psiClass } } } if (analyzeForUast(ktExpression) { resolvedTargetElement?.canBeAnalysed() == false }) return null when (resolvedTargetElement) { is KtClassOrObject -> { resolveToPsiClassOrEnumEntry(resolvedTargetElement)?.let { return it } } is KtConstructor<*> -> { resolveToPsiClassOrEnumEntry(resolvedTargetElement.getContainingClassOrObject())?.let { return it } } is KtTypeAlias -> { analyzeForUast(ktExpression) { val ktType = resolvedTargetElement.getTypeAliasSymbol().expandedType toPsiClass( ktType, source = null, resolvedTargetElement, resolvedTargetElement.typeOwnerKind )?.let { return it } } } is KtTypeParameter -> { analyzeForUast(ktExpression) { val ktType = buildTypeParameterType(resolvedTargetElement.getTypeParameterSymbol()) toPsiClass( ktType, ktExpression.toUElement(), resolvedTargetElement, resolvedTargetElement.typeOwnerKind )?.let { return it } } } is KtFunctionLiteral -> { // Implicit lambda parameter `it` if ((resolvedTargetSymbol as? KtValueParameterSymbol)?.isImplicitLambdaParameter == true) { // From its containing lambda (of function literal), build ULambdaExpression val lambda = resolvedTargetElement.toUElementOfType<ULambdaExpression>() // and return javaPsi of the corresponding lambda implicit parameter lambda?.valueParameters?.singleOrNull()?.javaPsi?.let { return it } } } } // TODO: need to handle resolved target to library source return resolvedTargetElement } override fun resolveToType(ktTypeReference: KtTypeReference, source: UElement, boxed: Boolean): PsiType? { analyzeForUast(ktTypeReference) { val ktType = ktTypeReference.getKtType() if (ktType is KtErrorType) return null return toPsiType(ktType, source, ktTypeReference, ktTypeReference.typeOwnerKind, boxed) } } override fun resolveToType(ktTypeReference: KtTypeReference, containingLightDeclaration: PsiModifierListOwner?): PsiType? { analyzeForUast(ktTypeReference) { val ktType = ktTypeReference.getKtType() if (ktType is KtErrorType) return null return toPsiType(ktType, containingLightDeclaration, ktTypeReference, ktTypeReference.typeOwnerKind) } } override fun getReceiverType(ktCallElement: KtCallElement, source: UElement): PsiType? { analyzeForUast(ktCallElement) { val ktCall = ktCallElement.resolveCall().singleFunctionCallOrNull() ?: return null return receiverType(ktCall, source, ktCallElement) } } override fun getAccessorReceiverType(ktSimpleNameExpression: KtSimpleNameExpression, source: UElement): PsiType? { analyzeForUast(ktSimpleNameExpression) { val ktCall = ktSimpleNameExpression.resolveCall()?.singleCallOrNull<KtVariableAccessCall>() ?: return null return receiverType(ktCall, source, ktSimpleNameExpression) } } override fun getDoubleColonReceiverType(ktDoubleColonExpression: KtDoubleColonExpression, source: UElement): PsiType? { analyzeForUast(ktDoubleColonExpression) { val receiverKtType = ktDoubleColonExpression.getReceiverKtType() ?: return null return toPsiType(receiverKtType, source, ktDoubleColonExpression, ktDoubleColonExpression.typeOwnerKind, boxed = true) } } override fun getCommonSupertype(left: KtExpression, right: KtExpression, uExpression: UExpression): PsiType? { val ktElement = uExpression.sourcePsi as? KtExpression ?: return null analyzeForUast(ktElement) { val leftType = left.getKtType() ?: return null val rightType = right.getKtType() ?: return null val commonSuperType = commonSuperType(listOf(leftType, rightType)) ?: return null return toPsiType(commonSuperType, uExpression, ktElement, ktElement.typeOwnerKind) } } override fun getType(ktExpression: KtExpression, source: UElement): PsiType? { analyzeForUast(ktExpression) { val ktType = ktExpression.getKtType() ?: return null return toPsiType(ktType, source, ktExpression, ktExpression.typeOwnerKind) } } override fun getType(ktDeclaration: KtDeclaration, source: UElement): PsiType? { analyzeForUast(ktDeclaration) { return toPsiType(ktDeclaration.getReturnKtType(), source, ktDeclaration, ktDeclaration.typeOwnerKind) } } override fun getType(ktDeclaration: KtDeclaration, containingLightDeclaration: PsiModifierListOwner?): PsiType? { analyzeForUast(ktDeclaration) { return toPsiType(ktDeclaration.getReturnKtType(), containingLightDeclaration, ktDeclaration, ktDeclaration.typeOwnerKind) } } override fun getFunctionType(ktFunction: KtFunction, source: UElement?): PsiType? { if (ktFunction is KtConstructor<*>) return null analyzeForUast(ktFunction) { return toPsiType(ktFunction.getFunctionalType(), source, ktFunction, ktFunction.typeOwnerKind) } } override fun getFunctionalInterfaceType(uLambdaExpression: KotlinULambdaExpression): PsiType? { val sourcePsi = uLambdaExpression.sourcePsi analyzeForUast(sourcePsi) { val samType = sourcePsi.getExpectedType() ?.takeIf { it !is KtErrorType && it.isFunctionalInterfaceType } ?.lowerBoundIfFlexible() ?: return null return toPsiType(samType, uLambdaExpression, sourcePsi, sourcePsi.typeOwnerKind) } } override fun nullability(psiElement: PsiElement): TypeNullability? { if (psiElement is KtTypeReference) { analyzeForUast(psiElement) { nullability(psiElement.getKtType())?.let { return it } } } if (psiElement is KtCallableDeclaration) { analyzeForUast(psiElement) { nullability(psiElement)?.let { return it } } } if (psiElement is KtDestructuringDeclaration) { analyzeForUast(psiElement) { nullability(psiElement)?.let { return it } } } return null } override fun evaluate(uExpression: UExpression): Any? { val ktExpression = uExpression.sourcePsi as? KtExpression ?: return null analyzeForUast(ktExpression) { return ktExpression.evaluate(KtConstantEvaluationMode.CONSTANT_LIKE_EXPRESSION_EVALUATION) ?.takeUnless { it is KtConstantValue.KtErrorConstantValue }?.value } } }
apache-2.0
9a15faf14892f952b92c377da858162e
48.06789
136
0.638284
6.522439
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/utils/src/org/jetbrains/kotlin/idea/codeinsight/utils/ExpressionSimplificationUtils.kt
1
3643
// 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.utils import com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* object NegatedBinaryExpressionSimplificationUtils { fun simplifyNegatedBinaryExpressionIfNeeded(expression: KtPrefixExpression) { if (expression.canBeSimplifiedWithoutChangingSemantics()) expression.simplify() } fun KtPrefixExpression.canBeSimplifiedWithoutChangingSemantics(): Boolean { if (!canBeSimplified()) return false val expression = KtPsiUtil.deparenthesize(baseExpression) as? KtBinaryExpression ?: return true val operation = expression.operationReference.getReferencedNameElementType() if (operation != KtTokens.LT && operation != KtTokens.LTEQ && operation != KtTokens.GT && operation != KtTokens.GTEQ) return true @OptIn(KtAllowAnalysisOnEdt::class) allowAnalysisOnEdt { analyze(expression) { fun KtType?.isFloatingPoint() = this != null && (isFloat || isDouble) return !expression.left?.getKtType().isFloatingPoint() && !expression.right?.getKtType().isFloatingPoint() } } } fun KtPrefixExpression.canBeSimplified(): Boolean { if (operationToken != KtTokens.EXCL) return false val expression = KtPsiUtil.deparenthesize(baseExpression) as? KtOperationExpression ?: return false when (expression) { is KtIsExpression -> if (expression.typeReference == null) return false is KtBinaryExpression -> if (expression.left == null || expression.right == null) return false else -> return false } return (expression.operationReference.getReferencedNameElementType() as? KtSingleValueToken)?.negate() != null } fun KtPrefixExpression.simplify() { val expression = KtPsiUtil.deparenthesize(baseExpression) ?: return val operation = (expression as KtOperationExpression).operationReference.getReferencedNameElementType().negate()?.value ?: return val psiFactory = KtPsiFactory(project) val newExpression = when (expression) { is KtIsExpression -> psiFactory.createExpressionByPattern("$0 $1 $2", expression.leftHandSide, operation, expression.typeReference!!) is KtBinaryExpression -> psiFactory.createExpressionByPattern("$0 $1 $2", expression.left ?: return, operation, expression.right ?: return) else -> throw IllegalArgumentException() } replace(newExpression) } fun IElementType.negate(): KtSingleValueToken? = when (this) { KtTokens.IN_KEYWORD -> KtTokens.NOT_IN KtTokens.NOT_IN -> KtTokens.IN_KEYWORD KtTokens.IS_KEYWORD -> KtTokens.NOT_IS KtTokens.NOT_IS -> KtTokens.IS_KEYWORD KtTokens.EQEQ -> KtTokens.EXCLEQ KtTokens.EXCLEQ -> KtTokens.EQEQ KtTokens.EQEQEQ -> KtTokens.EXCLEQEQEQ KtTokens.EXCLEQEQEQ -> KtTokens.EQEQEQ KtTokens.LT -> KtTokens.GTEQ KtTokens.GTEQ -> KtTokens.LT KtTokens.GT -> KtTokens.LTEQ KtTokens.LTEQ -> KtTokens.GT else -> null } }
apache-2.0
b3099cf6362bb0d8b11280f4501cec84
42.903614
137
0.692287
5.421131
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/feature/azure/AzureFeature.kt
1
4399
package no.skatteetaten.aurora.boober.feature.azure import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.stereotype.Service import no.skatteetaten.aurora.boober.feature.AbstractResolveTagFeature import no.skatteetaten.aurora.boober.feature.FeatureContext import no.skatteetaten.aurora.boober.feature.isJob import no.skatteetaten.aurora.boober.model.AuroraConfigFieldHandler import no.skatteetaten.aurora.boober.model.AuroraContextCommand import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec import no.skatteetaten.aurora.boober.model.AuroraResource import no.skatteetaten.aurora.boober.service.CantusService import no.skatteetaten.aurora.boober.utils.boolean /** * Azure feature collects several azure related items. These are: * <ul> * <li>JwtToStsConverter: Clinger sidecar converts JWT token to webseal header</li> * <li>AuroraAzureAppSubPart: Control migration away from webseal to azure ad JWT token</li> * <li>AuroraAzureApimSubPart: Registration of openapi-spec in Azure API Management. Notice * that you also need to enable the azure shard and create a dns entry in Azure AD</li> * </ul> * * @see no.skatteetaten.aurora.boober.feature.RouteFeature */ @ConditionalOnProperty("clinger.sidecar.default.ldapurl") @Service class AzureFeature( cantusService: CantusService, @Value("\${clinger.sidecar.default.version:0}") val sidecarVersion: String, @Value("\${clinger.sidecar.default.ldapurl}") val defaultLdapUrl: String, @Value("\${clinger.sidecar.default.jwks}") val defaultAzureJwks: String ) : AbstractResolveTagFeature(cantusService) { private val jwtToStsConverter = JwtToStsConverterSubPart() private val auroraAzureApp = AuroraAzureAppSubPart() private val auroraApim = AuroraAzureApimSubPart() object ConfigPath { const val azure = "azure" } override fun isActive(spec: AuroraDeploymentSpec): Boolean { return !isAzureSpecificallyDisabled(spec) && (spec.isJwtToStsConverterEnabled || spec.isAzureAppFqdnEnabled || spec.isApimEnabled) } private fun isAzureSpecificallyDisabled(spec: AuroraDeploymentSpec): Boolean = spec.isSimplifiedAndDisabled(ConfigPath.azure) override fun enable(header: AuroraDeploymentSpec): Boolean { return !header.isJob } override fun handlers(header: AuroraDeploymentSpec, cmd: AuroraContextCommand): Set<AuroraConfigFieldHandler> { return setOf( AuroraConfigFieldHandler( "azure", validator = { it.boolean(required = false) }, defaultValue = false, canBeSimplifiedConfig = true ), ) + jwtToStsConverter.handlers(sidecarVersion, defaultLdapUrl, defaultAzureJwks) + auroraAzureApp.handlers() + auroraApim.handlers(cmd.applicationFiles) } override fun createContext( spec: AuroraDeploymentSpec, cmd: AuroraContextCommand, validationContext: Boolean ): Map<String, Any> { val clingerTag = spec.getOrNull<String>(JwtToStsConverterSubPart.ConfigPath.version) if (validationContext || clingerTag == null) { return emptyMap() } return createImageMetadataContext( repo = "no_skatteetaten_aurora", name = "clinger", tag = clingerTag ) } override fun modify( adc: AuroraDeploymentSpec, resources: Set<AuroraResource>, context: FeatureContext ) { if (isActive(adc)) { jwtToStsConverter.modify(adc, resources, context.imageMetadata, this) } } override fun generate(adc: AuroraDeploymentSpec, context: FeatureContext): Set<AuroraResource> { return auroraAzureApp.generate(adc, this) + auroraApim.generate(adc, this) } override fun validate( adc: AuroraDeploymentSpec, fullValidation: Boolean, context: FeatureContext ): List<Exception> { return if (isActive(adc)) auroraAzureApp.validate(adc) + auroraApim.validate(adc) + jwtToStsConverter.validate(adc) else listOf() } fun getDeprecations(adc: AuroraDeploymentSpec): List<String>? { return auroraAzureApp.getDeprecations(adc) } }
apache-2.0
e2bf9a47304488b18438be7d22813ea2
37.587719
115
0.708797
4.679787
false
true
false
false
zpao/buck
src/com/facebook/buck/multitenant/service/InputSource.kt
1
4090
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.buck.multitenant.service import java.io.Closeable import java.io.InputStream import java.net.HttpURLConnection import java.net.URI import java.net.URL import kotlin.math.ln import kotlin.math.pow private const val KB_IN_BYTES = 1024 /** * Abstracts away physical source of index data, like file or network. */ sealed class InputSource : Closeable { /** * @return Stream to read index data from. Client is not required to close the stream, but * client is required to call [close] on current instance of [InputSource] */ abstract fun getInputStream(): InputStream /** * Size of index data in bytes, if available, otherwise -1 */ abstract fun getSize(): Long /** * @return human readable representation of index data size * *[Copied_from](https://programming.guide/java/formatting-byte-size-to-human-readable-format.html) */ fun getHumanReadableSize(): String { val bytes = getSize() if (bytes < KB_IN_BYTES) return "$bytes B" val unit = KB_IN_BYTES.toDouble() val exp = (ln(bytes.toDouble()) / ln(unit)).toInt() val pre = "KMGTPE"[exp - 1].toString() return String.format("%.1f %sB", bytes / unit.pow(exp.toDouble()), pre) } companion object { fun from(uri: URI): InputSource { return when { uri.scheme == "http" || uri.scheme == "https" -> Http( uri.toURL()) uri.scheme == "file" || uri.scheme.isNullOrEmpty() -> File( uri.path) else -> throw IllegalArgumentException( "schema ${uri.scheme} is not supported") } } } /** * Reads index data from a file on the machine */ data class File(val path: String) : InputSource() { private val javaFile: java.io.File = java.io.File(path) private var stream: InputStream? = null private fun ensureOpened() { if (stream != null) { return } stream = javaFile.inputStream() } override fun getInputStream(): InputStream { ensureOpened() return checkNotNull(stream) } override fun getSize() = javaFile.length() override fun close() { stream?.close() } } /** * Reads index data from HTTP url */ data class Http(val url: URL, val readTimeout: Int? = null, val connectTimeout: Int? = null) : InputSource() { private val connection: HttpURLConnection private var connected = false init { @Suppress("UnsafeCast") connection = url.openConnection() as HttpURLConnection connectTimeout?.let { connection.connectTimeout = it } readTimeout?.let { connection.readTimeout = it } } private fun ensureConnected() { if (connected) { return } connection.connect() connected = true } override fun getInputStream(): InputStream { ensureConnected() return connection.inputStream } override fun getSize(): Long { ensureConnected() return connection.contentLengthLong } override fun close() { if (connected) { connection.disconnect() } } } }
apache-2.0
6d47ba85d5d6638aba6edff114442685
29.073529
114
0.591443
4.679634
false
false
false
false
DmytroTroynikov/aemtools
lang/src/main/kotlin/com/aemtools/lang/htl/psi/pattern/HtlPatterns.kt
1
9635
package com.aemtools.lang.htl.psi.pattern import com.aemtools.common.constant.const import com.aemtools.common.constant.const.htl.DATA_SLY_CALL import com.aemtools.common.constant.const.htl.DATA_SLY_INCLUDE import com.aemtools.common.constant.const.htl.DATA_SLY_LIST import com.aemtools.common.constant.const.htl.DATA_SLY_REPEAT import com.aemtools.common.constant.const.htl.DATA_SLY_RESOURCE import com.aemtools.common.constant.const.htl.DATA_SLY_TEMPLATE import com.aemtools.common.constant.const.htl.DATA_SLY_TEST import com.aemtools.common.constant.const.htl.DATA_SLY_USE import com.aemtools.common.constant.const.htl.HTL_ATTRIBUTES import com.aemtools.lang.htl.psi.HtlExpression import com.aemtools.lang.htl.psi.HtlHtlEl import com.aemtools.lang.htl.psi.HtlTypes.ACCESS_IDENTIFIER import com.aemtools.lang.htl.psi.HtlTypes.ARRAY_LIKE_ACCESS import com.aemtools.lang.htl.psi.HtlTypes.ASSIGNMENT import com.aemtools.lang.htl.psi.HtlTypes.ASSIGNMENT_VALUE import com.aemtools.lang.htl.psi.HtlTypes.CONTEXT_EXPRESSION import com.aemtools.lang.htl.psi.HtlTypes.EL_START import com.aemtools.lang.htl.psi.HtlTypes.STRING_LITERAL import com.aemtools.lang.htl.psi.HtlTypes.VARIABLE_NAME import com.aemtools.lang.htl.psi.HtlTypes.VAR_NAME import com.intellij.patterns.ElementPattern import com.intellij.patterns.PlatformPatterns.and import com.intellij.patterns.PlatformPatterns.or import com.intellij.patterns.PlatformPatterns.psiElement import com.intellij.patterns.PlatformPatterns.psiFile import com.intellij.patterns.PlatformPatterns.string import com.intellij.patterns.PsiElementPattern import com.intellij.patterns.XmlPatterns.xmlAttribute import com.intellij.patterns.XmlPatterns.xmlAttributeValue import com.intellij.psi.PsiElement import com.intellij.psi.TokenType import com.intellij.psi.xml.XmlTokenType.XML_NAME /** * @author Dmytro Troynikov */ object HtlPatterns { /** * Matches the following: * * ``` * ${@ <caret>} * ``` */ val optionName: ElementPattern<PsiElement> = or( psiElement() .withParent(psiElement(VARIABLE_NAME) .withParent(psiElement(CONTEXT_EXPRESSION))), psiElement() .withParent(psiElement(VARIABLE_NAME) .withParent(psiElement(ASSIGNMENT) .withParent(psiElement(CONTEXT_EXPRESSION)))) ) /** * Matches option inside of data-sly-call, e.g.: * * ``` * <div data-sly-call="${@ <caret>}" * ``` */ val dataSlyCallOption: ElementPattern<PsiElement> = and( optionName, psiElement() .inside(psiElement() .with(HtlTemplatePattern(DATA_SLY_CALL))) ) /** * Matches option inside of data-sly-template, e.g.: * * ``` * <div data-sly-template="${@ <caret>}" * ``` */ val dataSlyTemplateOption: ElementPattern<PsiElement> = optionInsideAttribute(DATA_SLY_TEMPLATE) /** * Matches option inside of data-sly-resource, e.g.: * * ``` * <div data-sly-resource="${@ <caret>}" * ``` */ val dataSlyResourceOption: ElementPattern<PsiElement> = optionInsideAttribute(DATA_SLY_RESOURCE) /** * Matches the following: * * ``` * ${<caret>} * ${@ option=<caret>} * ${ [<caret>, ...] } * ${variable[<caret>]} * ``` */ val variableName: ElementPattern<PsiElement> = or<PsiElement>( psiElement(VAR_NAME) .andNot(psiElement().inside(psiElement(ACCESS_IDENTIFIER))) .andNot(optionName), psiElement(VAR_NAME) .inside(psiElement(ARRAY_LIKE_ACCESS)) .andNot(optionName) ) /** * Matches the following: * * ``` * ${'<caret>'} * ${"<caret>"} * ${@ option='<caret>'} * ``` */ val stringLiteralValue: ElementPattern<PsiElement> = psiElement().inside(psiElement(STRING_LITERAL)) /** * Matches the following: * * ``` * ${@ context='<caret>'} * ``` */ val contextOptionAssignment: ElementPattern<PsiElement> = namedOptionAssignment(const.htl.options.CONTEXT) /** * Matches the following: * * ``` * ${@ resourceType='<caret>'} * ``` */ val resourceTypeOptionAssignment: ElementPattern<PsiElement> = namedOptionAssignment(const.htl.options.RESOURCE_TYPE) /** * Matches the following: * * ``` * ${object.<caret>} * ``` */ val memberAccess: ElementPattern<PsiElement> = or( psiElement().inside(psiElement(STRING_LITERAL)) .inside(psiElement(ARRAY_LIKE_ACCESS)), psiElement(VAR_NAME).inside(psiElement(ACCESS_IDENTIFIER)) ) /** * Matches the following: * * ``` * data-sly-use="<caret>" * data-sly-use.bean="<caret>" * ``` */ val dataSlyUseNoEl: ElementPattern<PsiElement> = psiElement() .inside(xmlAttributeValue().withLocalName( or( string().equalTo(DATA_SLY_USE), string().startsWith("$DATA_SLY_USE.") ) )) .inFile(psiFile().with(HtlFilePattern)) /** * Matches the following: * * ``` * data-sly-include="<caret>" * ``` */ val dataSlyIncludeNoEl: ElementPattern<PsiElement> = psiElement() .inside(xmlAttributeValue() .withLocalName(string().equalTo(DATA_SLY_INCLUDE))) .inFile(psiFile().with(HtlFilePattern)) /** * Matches Htl xml attribute */ val htlAttribute: ElementPattern<PsiElement> = psiElement(XML_NAME).withParent(xmlAttribute().withName( or( string().oneOfIgnoreCase(*HTL_ATTRIBUTES.toTypedArray()), string().startsWith("$DATA_SLY_USE."), string().startsWith("$DATA_SLY_TEST."), string().startsWith("$DATA_SLY_LIST."), string().startsWith("$DATA_SLY_REPEAT."), string().startsWith("$DATA_SLY_TEMPLATE.") ) )) /** * Matches the following: * * ``` * data-sly-call="${<caret>}" * ``` */ val mainVariableInsideOfDataSlyCall: ElementPattern<PsiElement> = mainVariable() .inside(psiElement().with(HtlTemplatePattern(DATA_SLY_CALL))) /** * Matches: * * ``` * data-sly-list="${<caret>}" * ``` */ val mainVariableInsideOfDataSlyList: ElementPattern<PsiElement> = mainVariable() .inside(psiElement().with(HtlTemplatePattern(DATA_SLY_LIST))) /** * Matches: * * ``` * data-sly-repeat="${<caret>}" * ``` */ val mainVariableInsideOfDataSlyRepeat: ElementPattern<PsiElement> = mainVariable() .inside(psiElement().with(HtlTemplatePattern(DATA_SLY_REPEAT))) /** * Matches the following: * * ``` * data-sly-include="${'<caret>'}" * ``` */ val dataSlyIncludeMainString: ElementPattern<PsiElement> = mainStringInAttribute(DATA_SLY_INCLUDE) /** * Matches the following: * * ``` * data-sly-use="${'<caret>'}" * data-sly-use.bean="${'<caret>'}" * ``` */ val dataSlyUseMainString: ElementPattern<PsiElement> = mainStringInAttribute(DATA_SLY_USE) /** * Matches the following: * * ``` * ${'<caret' @ i18n} * ``` */ val localizationMainString: ElementPattern<PsiElement> = and( stringLiteralValue, psiElement().withParent(psiElement().afterLeafSkipping( psiElement(TokenType.WHITE_SPACE), psiElement(EL_START))), psiElement().withAncestor(7, psiElement(HtlHtlEl::class.java) .withChild(psiElement() .withText(const.htl.options.I18N)) ) ) /** * Create pattern which will match main string in given htl attribute. * * @param attribute the name of attribute * @return new element pattern */ private fun mainStringInAttribute(attribute: String): ElementPattern<PsiElement> = and( stringLiteralValue, psiElement().withParent(psiElement().afterLeafSkipping( psiElement(TokenType.WHITE_SPACE), psiElement(EL_START)) .inside(psiElement().with(HtlTemplatePattern(attribute))) )) /** * Create pattern which will match option name inside of given htl attribute. * * @param attribute the name of attribute * @return new element pattern */ private fun optionInsideAttribute(attribute: String): ElementPattern<PsiElement> = and( optionName, psiElement() .inside(psiElement() .with(HtlTemplatePattern(attribute))) ) /** * Create matcher for assignment of option with given name. * e.g.: * * ``` * namedOptionAssignment("context") -> * will create pattern that will match: * ${@ context='<caret>'} * ``` * * @param option option name * @return new element pattern */ private fun namedOptionAssignment(option: String): ElementPattern<PsiElement> = and( stringLiteralValue, psiElement().inside(psiElement(CONTEXT_EXPRESSION)), psiElement().inside( psiElement(ASSIGNMENT_VALUE) .afterSibling(psiElement(VARIABLE_NAME).withText(option)) ) ) private fun mainVariable(): PsiElementPattern.Capture<PsiElement> { return psiElement().inside(psiElement(HtlExpression::class.java)) .afterLeafSkipping( psiElement(TokenType.WHITE_SPACE), psiElement(EL_START)) } }
gpl-3.0
20a18e91550687e51b731a480cda033a
27.255132
84
0.619927
4.231445
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/model/psi/impl/declarations.kt
2
2575
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("Declarations") package com.intellij.model.psi.impl import com.intellij.model.psi.PsiSymbolDeclaration import com.intellij.model.psi.PsiSymbolDeclarationProvider import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiRecursiveElementWalkingVisitor import com.intellij.psi.util.elementsAroundOffsetUp import com.intellij.util.SmartList import org.jetbrains.annotations.TestOnly /** * @return collection of declarations found around the given [offset][offsetInFile] in [file][this] */ fun PsiFile.allDeclarationsAround(offsetInFile: Int): Collection<PsiSymbolDeclaration> { for ((element: PsiElement, offsetInElement: Int) in elementsAroundOffsetUp(offsetInFile)) { ProgressManager.checkCanceled() val declarations: Collection<PsiSymbolDeclaration> = declarationsInElement(element, offsetInElement) if (declarations.isNotEmpty()) { return declarations } } return emptyList() } fun hasDeclarationsInElement(element: PsiElement, offsetInElement: Int): Boolean { return declarationsInElement(element, offsetInElement).isNotEmpty() } private val declarationProviderEP = ExtensionPointName<PsiSymbolDeclarationProvider>("com.intellij.psi.declarationProvider") private fun declarationsInElement(element: PsiElement, offsetInElement: Int): Collection<PsiSymbolDeclaration> { val result = SmartList<PsiSymbolDeclaration>() result.addAll(element.ownDeclarations) for (extension: PsiSymbolDeclarationProvider in declarationProviderEP.iterable) { ProgressManager.checkCanceled() result.addAll(extension.getDeclarations(element, offsetInElement)) } return result.filterTo(SmartList()) { element === it.declaringElement && (offsetInElement < 0 || it.rangeInDeclaringElement.containsOffset(offsetInElement)) } } @TestOnly fun PsiFile.allDeclarations(): Collection<PsiSymbolDeclaration> { val declarations = ArrayList<PsiSymbolDeclaration>() accept(DeclarationCollectingVisitor(declarations)) return declarations } private class DeclarationCollectingVisitor( private val declarations: MutableList<PsiSymbolDeclaration> ) : PsiRecursiveElementWalkingVisitor(true) { override fun visitElement(element: PsiElement) { super.visitElement(element) declarations.addAll(declarationsInElement(element, -1)) } }
apache-2.0
d95308adf194927dd87c7105c8da2b87
39.234375
140
0.807767
4.867675
false
false
false
false
leafclick/intellij-community
java/java-impl/src/com/intellij/lang/java/request/CreateExecutableFromJavaUsageRequest.kt
1
2201
// 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.lang.java.request import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.getTargetSubstitutor import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.* import com.intellij.openapi.components.service import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.util.createSmartPointer import com.intellij.psi.util.parentOfTypes import com.intellij.refactoring.util.RefactoringUtil internal abstract class CreateExecutableFromJavaUsageRequest<out T : PsiCall>( call: T, private val modifiers: Collection<JvmModifier> ) : CreateExecutableRequest { private val psiManager = call.manager private val project = psiManager.project private val callPointer: SmartPsiElementPointer<T> = call.createSmartPointer(project) protected val call: T get() = callPointer.element ?: error("dead pointer") override fun isValid() = callPointer.element != null override fun getAnnotations() = emptyList<AnnotationRequest>() override fun getModifiers() = modifiers override fun getTargetSubstitutor() = PsiJvmSubstitutor(project, getTargetSubstitutor(call)) override fun getExpectedParameters(): List<ExpectedParameter> { val argumentList = call.argumentList ?: return emptyList() val scope = call.resolveScope val codeStyleManager: JavaCodeStyleManager = project.service() return argumentList.expressions.map { expression -> val argType: PsiType? = RefactoringUtil.getTypeByExpression(expression) val type = CreateFromUsageUtils.getParameterTypeByArgumentType(argType, psiManager, scope) val names = codeStyleManager.suggestSemanticNames(expression) val expectedTypes = expectedTypes(type, ExpectedType.Kind.SUPERTYPE) expectedParameter(expectedTypes, names) } } override fun getParameters() = getParameters(expectedParameters, project) val context get() = call.parentOfTypes(PsiMethod::class, PsiClass::class) }
apache-2.0
fbf25c4e4f72e3fbaeb0fdfa079530df
43.918367
140
0.795547
4.979638
false
false
false
false
moko256/twicalico
app/src/main/java/com/github/moko256/twitlatte/widget/ImagesTableView.kt
1
12884
/* * Copyright 2015-2019 The twitlatte 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 com.github.moko256.twitlatte.widget import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.View import android.view.View.OnLongClickListener import android.view.ViewGroup import android.widget.ImageView import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.AppCompatImageView import com.bumptech.glide.RequestManager import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.github.moko256.latte.client.base.CLIENT_TYPE_NOTHING import com.github.moko256.latte.client.base.entity.Media import com.github.moko256.twitlatte.R import com.github.moko256.twitlatte.ShowMediasActivity import com.github.moko256.twitlatte.text.TwitterStringUtils import com.github.moko256.twitlatte.view.dpToPx import jp.wasabeef.glide.transformations.BlurTransformation import kotlin.math.min /** * Created by moko256 on 2019/01/21. */ class ImagesTableView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ViewGroup(context, attrs, defStyleAttr) { private companion object { private val a0000 = intArrayOf(0, 0, 0, 0) private val a0111 = intArrayOf(0, 1, 1, 1) private val a1111 = intArrayOf(1, 1, 1, 1) private val a0021 = intArrayOf(0, 0, 2, 1) private val a0022 = intArrayOf(0, 0, 2, 2) private val a0121 = intArrayOf(0, 1, 2, 1) private val a0011 = intArrayOf(0, 0, 1, 1) private val a1011 = intArrayOf(1, 0, 1, 1) /* {row,column,rowSpan,colSpan} */ private val params = arrayOf( arrayOf(a0022, a0000, a0000, a0000), arrayOf(a0021, a0121, a0000, a0000), arrayOf(a0021, a0111, a1111, a0000), arrayOf(a0011, a0111, a1011, a1111) ) private const val maxMediaSize = 4 private val imageFilter = PorterDuffColorFilter(0x33000000, PorterDuff.Mode.SRC_ATOP) } private val dp = context.resources.displayMetrics.density private val dividerSize = dpToPx(4, dp) private val markSize = dpToPx(48, dp) private val drawable = AppCompatResources.getDrawable(context, R.drawable.ic_play_arrow_white_24dp)!! .apply { setBounds(0, 0, markSize, markSize) } private val gifMark = AppCompatResources.getDrawable(context, R.drawable.ic_gif_white_24dp)!! .apply { setBounds(0, 0, markSize, markSize) } private var clientType = CLIENT_TYPE_NOTHING private var isOpen = true private lateinit var imageLoadMode: String private var imageTableData: ImageTableData? = null private var displayingMediaSize = 0 private val longClickListener = OnLongClickListener { this.performLongClick() } private var containerViews = arrayOfNulls<ImageTableImageView>(maxMediaSize) private fun getContainer(index: Int): ImageTableImageView { return containerViews[index] ?: generateChild(index) .also { containerViews[index] = it addViewInLayout(it, index, generateDefaultLayoutParams()) } } private fun generateChild(index: Int): ImageTableImageView { val imageView = ImageTableImageView( context, drawable, gifMark, markSize ) imageView.scaleType = ImageView.ScaleType.CENTER_CROP imageView.setOnLongClickListener(longClickListener) imageView.setOnClickListener { imageTableData?.let { imageTableData -> if (isOpen) { context.startActivity(ShowMediasActivity.getIntent(context, imageTableData.medias, clientType, index)) } else { isOpen = true updateImages(imageTableData) } } } return imageView } fun setMedias( requestManager: RequestManager, newMedias: Array<Media>, clientType: Int, sensitive: Boolean, imageLoadMode: String, isHideSensitiveMedia: Boolean ) { this.imageLoadMode = imageLoadMode this.clientType = clientType isOpen = imageLoadMode != "none" && !(sensitive && isHideSensitiveMedia) val oldSize = displayingMediaSize val newSize = newMedias.size if (oldSize < newSize) { for (i in oldSize until newSize) { getContainer(i).visibility = View.VISIBLE } } else if (newSize < oldSize) { for (i in newSize until oldSize) { getContainer(i).visibility = View.GONE } } val data = ImageTableData(newMedias, requestManager) imageTableData = data displayingMediaSize = min(newSize, maxMediaSize) invalidate() updateImages(data) } private fun updateImages(imageTableData: ImageTableData) { imageTableData.medias.forEachIndexed { index, media -> setMediaToView(media, getContainer(index), imageTableData.requestManager) } } private fun setMediaToView(media: Media, imageView: ImageTableImageView, requestManager: RequestManager) { val thumbnailUrl = media.thumbnailUrl val originalUrl = media.originalUrl val url = thumbnailUrl ?: originalUrl if (isOpen) { requestManager .load( if (imageLoadMode == "normal") TwitterStringUtils.convertSmallImageUrl(clientType, url) else TwitterStringUtils.convertThumbImageUrl(clientType, url) ) .transition(DrawableTransitionOptions.withCrossFade()) .into(imageView) when (media.mediaType) { "audio", "video_one", "video_multi" -> { imageView.setFilterIfNotExist() imageView.drawPlay = true imageView.drawGif = false } "gif" -> { imageView.setFilterIfNotExist() imageView.drawPlay = true imageView.drawGif = true } else -> { imageView.removeFilterIfExist() imageView.drawPlay = false imageView.drawGif = false } } } else { val timelineImageLoadMode = imageLoadMode if (timelineImageLoadMode != "none") { requestManager .load( if (timelineImageLoadMode == "normal") TwitterStringUtils.convertSmallImageUrl(clientType, url) else TwitterStringUtils.convertThumbImageUrl(clientType, url) ) .transform(BlurTransformation()) .transition(DrawableTransitionOptions.withCrossFade()) .into(imageView) } else { imageView.setImageResource(R.drawable.border_frame) } imageView.removeFilterIfExist() imageView.drawPlay = false imageView.drawGif = false } } private fun ImageView.setFilterIfNotExist() { if (colorFilter == null) { colorFilter = imageFilter } } private fun ImageView.removeFilterIfExist() { if (colorFilter != null) { colorFilter = null } } fun clearImages() { imageTableData?.requestManager?.apply { repeat(displayingMediaSize) { clear(getContainer(it)) } imageTableData = null } } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { imageTableData?.medias?.let { medias -> repeat(displayingMediaSize) { i -> val view = getContainer(i) val param = params[medias.size - 1][i] val width = measuredWidth val height = measuredHeight val childWidth = view.measuredWidth val childHeight = view.measuredHeight val left = generateChildPosition(width, childWidth, param[1]) val top = generateChildPosition(height, childHeight, param[0]) view.layout(left, top, left + childWidth, top + childHeight) } } } private fun generateChildPosition(parentSize: Int, childSize: Int, positionId: Int): Int { return if (positionId == 0) { 0 } else { parentSize - childSize } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var widthSize = MeasureSpec.getSize(widthMeasureSpec) var heightSize = MeasureSpec.getSize(heightMeasureSpec) val widthMode = MeasureSpec.getMode(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) if (widthMode != MeasureSpec.EXACTLY) { widthSize = heightSize / 9 * 16 } else if (heightMode != MeasureSpec.EXACTLY) { heightSize = widthSize / 16 * 9 } setMeasuredDimension( MeasureSpec.makeMeasureSpec(widthSize + paddingLeft + paddingRight, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize + paddingTop + paddingBottom, MeasureSpec.EXACTLY) ) imageTableData?.medias?.let { medias -> val mediasSizesParams = params[medias.size - 1] repeat(displayingMediaSize) { i -> val param = mediasSizesParams[i] val view = getContainer(i) view.measure(generateChildSpec(widthSize, param[3]), generateChildSpec(heightSize, param[2])) } } } private fun generateChildSpec(parentSize: Int, spanSize: Int): Int { return MeasureSpec.makeMeasureSpec( if (spanSize == 1) { (parentSize - dividerSize) / 2 } else { parentSize }, MeasureSpec.EXACTLY ) } class ImageTableData( val medias: Array<Media>, val requestManager: RequestManager ) @SuppressLint("ViewConstructor") class ImageTableImageView( context: Context, private val play: Drawable, private val gif: Drawable, private val drawableSize: Int ) : AppCompatImageView(context) { var drawPlay = false var drawGif = false private var playWidth = 0f private var playHeight = 0f private var gifHeight = 0f override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (drawGif) { canvas.translate(0f, gifHeight) gif.draw(canvas) canvas.translate(0f, -gifHeight) } if (drawPlay) { canvas.translate(playWidth, playHeight) play.draw(canvas) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val width = measuredWidth val height = measuredHeight val diffWidthAndSize = width - drawableSize val diffHeightAndSize = height - drawableSize val halfDiffWidthAndSize = diffWidthAndSize / 2 val halfDiffHeightAndSize = diffHeightAndSize / 2 playWidth = halfDiffWidthAndSize.toFloat() playHeight = halfDiffHeightAndSize.toFloat() gifHeight = diffHeightAndSize.toFloat() } } }
apache-2.0
15e5c7ec5a3a4b7a9c9c15348e14645f
34.30137
122
0.593294
5.258776
false
false
false
false
zdary/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/actions/BrowseRepositoryAction.kt
12
2244
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn.actions import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.wm.RegisterToolWindowTask import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowManager import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.annotations.NonNls import org.jetbrains.idea.svn.SvnBundle.messagePointer import org.jetbrains.idea.svn.dialogs.RepositoryBrowserDialog @NonNls private const val REPOSITORY_BROWSER_TOOLWINDOW_ID = "SVN Repositories" private fun getRepositoryBrowserToolWindow(project: Project): ToolWindow? = ToolWindowManager.getInstance(project).getToolWindow(REPOSITORY_BROWSER_TOOLWINDOW_ID) class BrowseRepositoryAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project if (project == null) { RepositoryBrowserDialog(ProjectManager.getInstance().defaultProject).show() } else { val toolWindow = getRepositoryBrowserToolWindow(project) ?: registerRepositoryBrowserToolWindow(project) toolWindow.activate(null) } } private fun registerRepositoryBrowserToolWindow(project: Project): ToolWindow = ToolWindowManager.getInstance(project).registerToolWindow(RegisterToolWindowTask( id = REPOSITORY_BROWSER_TOOLWINDOW_ID, component = RepositoryToolWindowPanel(project), stripeTitle = messagePointer("toolwindow.stripe.SVN_Repositories") )).apply { helpId = "reference.svn.repository" } } private class RepositoryToolWindowPanel(private val project: Project) : BorderLayoutPanel(), Disposable { private val dialog = RepositoryBrowserDialog(project) init { addToCenter(dialog.createBrowserComponent(true)) addToLeft(dialog.createToolbar(false)) } override fun dispose() { dialog.disposeRepositoryBrowser() getRepositoryBrowserToolWindow(project)?.remove() } }
apache-2.0
e27b60f8c840d888361036b8ea9cef08
38.368421
140
0.793672
4.794872
false
false
false
false
leafclick/intellij-community
plugins/git4idea/src/git4idea/light/LightGitUtil.kt
1
2628
// 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 git4idea.light import com.intellij.diff.DiffContentFactoryImpl import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcsUtil.VcsUtil import git4idea.GitUtil import git4idea.commands.Git import git4idea.commands.GitBinaryHandler import git4idea.commands.GitCommand import git4idea.commands.GitLineHandler import git4idea.config.GitExecutableManager import git4idea.util.GitFileUtils.addTextConvParameters import java.nio.charset.Charset @Throws(VcsException::class) fun getLocation(directory: VirtualFile, executable: String): String { val name = Git.getInstance().runCommand(createRevParseHandler(directory, executable)).getOutputOrThrow() if (name != "HEAD") return name val hash = Git.getInstance().runCommand(createRevParseHandler(directory, executable, abbrev = false)).getOutputOrThrow() if (VcsLogUtil.HASH_REGEX.matcher(hash).matches()) { return VcsLogUtil.getShortHash(hash) } throw VcsException("Could not find current revision for " + directory.path) } private fun createRevParseHandler(directory: VirtualFile, executable: String, abbrev: Boolean = true): GitLineHandler { val handler = GitLineHandler(null, VfsUtilCore.virtualToIoFile(directory), executable, GitCommand.REV_PARSE, emptyList()) if (abbrev) handler.addParameters("--abbrev-ref") handler.addParameters("HEAD") handler.setSilent(true) return handler } @Throws(VcsException::class) fun getFileContent(directory: VirtualFile, repositoryPath: String, executable: String, revisionOrBranch: String): ByteArray { val h = GitBinaryHandler(VfsUtilCore.virtualToIoFile(directory), executable, GitCommand.CAT_FILE) addTextConvParameters(GitExecutableManager.getInstance().getVersion(executable), h, true) h.addParameters("$revisionOrBranch:$repositoryPath") return h.run() } @Throws(VcsException::class) fun getFileContentAsString(file: VirtualFile, repositoryPath: String, executable: String, revisionOrBranch: String = GitUtil.HEAD): String { val vcsContent = getFileContent(file.parent, repositoryPath, executable, revisionOrBranch) val charset: Charset = DiffContentFactoryImpl.guessCharset(vcsContent, VcsUtil.getFilePath(file)) return CharsetToolkit.decodeString(vcsContent, charset) }
apache-2.0
79bbc8f9d6728fb5e52d8a5cf5272a50
45.122807
140
0.783486
4.492308
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/casts/mutableCollections/reifiedAsWithMutable.kt
2
5805
// IGNORE_BACKEND: NATIVE // WITH_RUNTIME class Itr : Iterator<String> by ArrayList<String>().iterator() class MItr : MutableIterator<String> by ArrayList<String>().iterator() class LItr : ListIterator<String> by ArrayList<String>().listIterator() class MLItr : MutableListIterator<String> by ArrayList<String>().listIterator() class It : Iterable<String> by ArrayList<String>() class MIt : MutableIterable<String> by ArrayList<String>() class C : Collection<String> by ArrayList<String>() class MC : MutableCollection<String> by ArrayList<String>() class L : List<String> by ArrayList<String>() class ML : MutableList<String> by ArrayList<String>() class S : Set<String> by HashSet<String>() class MS : MutableSet<String> by HashSet<String>() class M : Map<String, String> by HashMap<String, String>() class MM : MutableMap<String, String> by HashMap<String, String>() class ME : Map.Entry<String, String> { override val key: String get() = throw UnsupportedOperationException() override val value: String get() = throw UnsupportedOperationException() } class MME : MutableMap.MutableEntry<String, String> { override val key: String get() = throw UnsupportedOperationException() override val value: String get() = throw UnsupportedOperationException() override fun setValue(value: String): String = throw UnsupportedOperationException() } inline fun <reified T> reifiedAsSucceeds(x: Any, operation: String) { try { x as T } catch (e: Throwable) { throw AssertionError("$operation: should not throw exceptions, got $e") } } inline fun <reified T> reifiedAsFailsWithCCE(x: Any, operation: String) { try { x as T } catch (e: ClassCastException) { return } catch (e: Throwable) { throw AssertionError("$operation: should throw ClassCastException, got $e") } throw AssertionError("$operation: should fail with CCE, no exception thrown") } fun box(): String { val itr = Itr() as Any val mitr = MItr() reifiedAsFailsWithCCE<MutableIterator<*>>(itr, "reifiedAs<MutableIterator<*>>(itr)") reifiedAsSucceeds<MutableIterator<*>>(mitr, "reifiedAs<MutableIterator<*>>(mitr)") val litr = LItr() as Any val mlitr = MLItr() reifiedAsFailsWithCCE<MutableIterator<*>>(litr, "reifiedAs<MutableIterator<*>>(litr)") reifiedAsFailsWithCCE<MutableListIterator<*>>(litr, "reifiedAs<MutableListIterator<*>>(litr)") reifiedAsSucceeds<MutableListIterator<*>>(mlitr, "reifiedAs<MutableListIterator<*>>(mlitr)") val it = It() as Any val mit = MIt() val arrayList = ArrayList<String>() reifiedAsFailsWithCCE<MutableIterable<*>>(it, "reifiedAs<MutableIterable<*>>(it)") reifiedAsSucceeds<MutableIterable<*>>(mit, "reifiedAs<MutableIterable<*>>(mit)") reifiedAsSucceeds<MutableIterable<*>>(arrayList, "reifiedAs<MutableIterable<*>>(arrayList)") val coll = C() as Any val mcoll = MC() reifiedAsFailsWithCCE<MutableCollection<*>>(coll, "reifiedAs<MutableCollection<*>>(coll)") reifiedAsFailsWithCCE<MutableIterable<*>>(coll, "reifiedAs<MutableIterable<*>>(coll)") reifiedAsSucceeds<MutableCollection<*>>(mcoll, "reifiedAs<MutableCollection<*>>(mcoll)") reifiedAsSucceeds<MutableIterable<*>>(mcoll, "reifiedAs<MutableIterable<*>>(mcoll)") reifiedAsSucceeds<MutableCollection<*>>(arrayList, "reifiedAs<MutableCollection<*>>(arrayList)") val list = L() as Any val mlist = ML() reifiedAsFailsWithCCE<MutableList<*>>(list, "reifiedAs<MutableList<*>>(list)") reifiedAsFailsWithCCE<MutableCollection<*>>(list, "reifiedAs<MutableCollection<*>>(list)") reifiedAsFailsWithCCE<MutableIterable<*>>(list, "reifiedAs<MutableIterable<*>>(list)") reifiedAsSucceeds<MutableList<*>>(mlist, "reifiedAs<MutableList<*>>(mlist)") reifiedAsSucceeds<MutableCollection<*>>(mlist, "reifiedAs<MutableCollection<*>>(mlist)") reifiedAsSucceeds<MutableIterable<*>>(mlist, "reifiedAs<MutableIterable<*>>(mlist)") reifiedAsSucceeds<MutableList<*>>(arrayList, "reifiedAs<MutableList<*>>(arrayList)") val set = S() as Any val mset = MS() val hashSet = HashSet<String>() reifiedAsFailsWithCCE<MutableSet<*>>(set, "reifiedAs<MutableSet<*>>(set)") reifiedAsFailsWithCCE<MutableCollection<*>>(set, "reifiedAs<MutableCollection<*>>(set)") reifiedAsFailsWithCCE<MutableIterable<*>>(set, "reifiedAs<MutableIterable<*>>(set)") reifiedAsSucceeds<MutableSet<*>>(mset, "reifiedAs<MutableSet<*>>(mset)") reifiedAsSucceeds<MutableCollection<*>>(mset, "reifiedAs<MutableCollection<*>>(mset)") reifiedAsSucceeds<MutableIterable<*>>(mset, "reifiedAs<MutableIterable<*>>(mset)") reifiedAsSucceeds<MutableSet<*>>(hashSet, "reifiedAs<MutableSet<*>>(hashSet)") reifiedAsSucceeds<MutableCollection<*>>(hashSet, "reifiedAs<MutableCollection<*>>(hashSet)") reifiedAsSucceeds<MutableIterable<*>>(hashSet, "reifiedAs<MutableIterable<*>>(hashSet)") val map = M() as Any val mmap = MM() val hashMap = HashMap<String, String>() reifiedAsFailsWithCCE<MutableMap<*, *>>(map, "reifiedAs<MutableMap<*, *>>(map)") reifiedAsSucceeds<MutableMap<*, *>>(mmap, "reifiedAs<MutableMap<*, *>>(mmap)") reifiedAsSucceeds<MutableMap<*, *>>(hashMap, "reifiedAs<MutableMap<*, *>>(hashMap)") val entry = ME() as Any val mentry = MME() hashMap[""] = "" val hashMapEntry = hashMap.entries.first() reifiedAsFailsWithCCE<MutableMap.MutableEntry<*, *>>(entry, "reifiedAs<MutableMap.MutableEntry<*, *>>(entry)") reifiedAsSucceeds<MutableMap.MutableEntry<*, *>>(mentry, "reifiedAs<MutableMap.MutableEntry<*, *>>(mentry)") reifiedAsSucceeds<MutableMap.MutableEntry<*, *>>(hashMapEntry, "reifiedAs<MutableMap.MutableEntry<*, *>>(hashMapEntry)") return "OK" }
apache-2.0
ee180bdd60c2829544d32318afca7082
44
124
0.705254
4.982833
false
false
false
false
android/compose-samples
Jetsnack/app/src/main/java/com/example/jetsnack/ui/components/Snacks.kt
1
10401
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetsnack.ui.components import android.content.res.Configuration.UI_MODE_NIGHT_YES import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.ArrowBack import androidx.compose.material.icons.outlined.ArrowForward import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.example.jetsnack.R import com.example.jetsnack.model.CollectionType import com.example.jetsnack.model.Snack import com.example.jetsnack.model.SnackCollection import com.example.jetsnack.model.snacks import com.example.jetsnack.ui.theme.JetsnackTheme import com.example.jetsnack.ui.utils.mirroringIcon private val HighlightCardWidth = 170.dp private val HighlightCardPadding = 16.dp // The Cards show a gradient which spans 3 cards and scrolls with parallax. private val gradientWidth @Composable get() = with(LocalDensity.current) { (3 * (HighlightCardWidth + HighlightCardPadding).toPx()) } @Composable fun SnackCollection( snackCollection: SnackCollection, onSnackClick: (Long) -> Unit, modifier: Modifier = Modifier, index: Int = 0, highlight: Boolean = true ) { Column(modifier = modifier) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .heightIn(min = 56.dp) .padding(start = 24.dp) ) { Text( text = snackCollection.name, style = MaterialTheme.typography.h6, color = JetsnackTheme.colors.brand, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier .weight(1f) .wrapContentWidth(Alignment.Start) ) IconButton( onClick = { /* todo */ }, modifier = Modifier.align(Alignment.CenterVertically) ) { Icon( imageVector = mirroringIcon( ltrIcon = Icons.Outlined.ArrowForward, rtlIcon = Icons.Outlined.ArrowBack ), tint = JetsnackTheme.colors.brand, contentDescription = null ) } } if (highlight && snackCollection.type == CollectionType.Highlight) { HighlightedSnacks(index, snackCollection.snacks, onSnackClick) } else { Snacks(snackCollection.snacks, onSnackClick) } } } @Composable private fun HighlightedSnacks( index: Int, snacks: List<Snack>, onSnackClick: (Long) -> Unit, modifier: Modifier = Modifier ) { val scroll = rememberScrollState(0) val gradient = when ((index / 2) % 2) { 0 -> JetsnackTheme.colors.gradient6_1 else -> JetsnackTheme.colors.gradient6_2 } // The Cards show a gradient which spans 3 cards and scrolls with parallax. val gradientWidth = with(LocalDensity.current) { (6 * (HighlightCardWidth + HighlightCardPadding).toPx()) } LazyRow( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(16.dp), contentPadding = PaddingValues(start = 24.dp, end = 24.dp) ) { itemsIndexed(snacks) { index, snack -> HighlightSnackItem( snack, onSnackClick, index, gradient, gradientWidth, scroll.value ) } } } @Composable private fun Snacks( snacks: List<Snack>, onSnackClick: (Long) -> Unit, modifier: Modifier = Modifier ) { LazyRow( modifier = modifier, contentPadding = PaddingValues(start = 12.dp, end = 12.dp) ) { items(snacks) { snack -> SnackItem(snack, onSnackClick) } } } @Composable fun SnackItem( snack: Snack, onSnackClick: (Long) -> Unit, modifier: Modifier = Modifier ) { JetsnackSurface( shape = MaterialTheme.shapes.medium, modifier = modifier.padding( start = 4.dp, end = 4.dp, bottom = 8.dp ) ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .clickable(onClick = { onSnackClick(snack.id) }) .padding(8.dp) ) { SnackImage( imageUrl = snack.imageUrl, elevation = 4.dp, contentDescription = null, modifier = Modifier.size(120.dp) ) Text( text = snack.name, style = MaterialTheme.typography.subtitle1, color = JetsnackTheme.colors.textSecondary, modifier = Modifier.padding(top = 8.dp) ) } } } @Composable private fun HighlightSnackItem( snack: Snack, onSnackClick: (Long) -> Unit, index: Int, gradient: List<Color>, gradientWidth: Float, scroll: Int, modifier: Modifier = Modifier ) { val left = index * with(LocalDensity.current) { (HighlightCardWidth + HighlightCardPadding).toPx() } JetsnackCard( modifier = modifier .size( width = 170.dp, height = 250.dp ) .padding(bottom = 16.dp) ) { Column( modifier = Modifier .clickable(onClick = { onSnackClick(snack.id) }) .fillMaxSize() ) { Box( modifier = Modifier .height(160.dp) .fillMaxWidth() ) { val gradientOffset = left - (scroll / 3f) Box( modifier = Modifier .height(100.dp) .fillMaxWidth() .offsetGradientBackground(gradient, gradientWidth, gradientOffset) ) SnackImage( imageUrl = snack.imageUrl, contentDescription = null, modifier = Modifier .size(120.dp) .align(Alignment.BottomCenter) ) } Spacer(modifier = Modifier.height(8.dp)) Text( text = snack.name, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.h6, color = JetsnackTheme.colors.textSecondary, modifier = Modifier.padding(horizontal = 16.dp) ) Spacer(modifier = Modifier.height(4.dp)) Text( text = snack.tagline, style = MaterialTheme.typography.body1, color = JetsnackTheme.colors.textHelp, modifier = Modifier.padding(horizontal = 16.dp) ) } } } @Composable fun SnackImage( imageUrl: String, contentDescription: String?, modifier: Modifier = Modifier, elevation: Dp = 0.dp ) { JetsnackSurface( color = Color.LightGray, elevation = elevation, shape = CircleShape, modifier = modifier ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(imageUrl) .crossfade(true) .build(), contentDescription = contentDescription, placeholder = painterResource(R.drawable.placeholder), modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop, ) } } @Preview("default") @Preview("dark theme", uiMode = UI_MODE_NIGHT_YES) @Preview("large font", fontScale = 2f) @Composable fun SnackCardPreview() { JetsnackTheme { val snack = snacks.first() HighlightSnackItem( snack = snack, onSnackClick = { }, index = 0, gradient = JetsnackTheme.colors.gradient6_1, gradientWidth = gradientWidth, scroll = 0 ) } }
apache-2.0
d8dcca89acba201bd2a0abede51af64b
31.605016
90
0.611191
4.817508
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/accounts/GHAccountManager.kt
2
2737
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.accounts import com.intellij.collaboration.auth.AccountManagerBase import com.intellij.collaboration.auth.AccountsListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.util.messages.Topic import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.util.GithubUtil internal val GithubAccount.isGHAccount: Boolean get() = server.isGithubDotCom /** * Handles application-level Github accounts */ @Service internal class GHAccountManager : AccountManagerBase<GithubAccount, String>(GithubUtil.SERVICE_DISPLAY_NAME) { override fun accountsRepository() = service<GHPersistentAccounts>() override fun serializeCredentials(credentials: String): String = credentials override fun deserializeCredentials(credentials: String): String = credentials init { @Suppress("DEPRECATION") addListener(this, object : AccountsListener<GithubAccount> { override fun onAccountListChanged(old: Collection<GithubAccount>, new: Collection<GithubAccount>) { val removedPublisher = ApplicationManager.getApplication().messageBus.syncPublisher(ACCOUNT_REMOVED_TOPIC) for (account in (old - new)) { removedPublisher.accountRemoved(account) } val tokenPublisher = ApplicationManager.getApplication().messageBus.syncPublisher(ACCOUNT_TOKEN_CHANGED_TOPIC) for (account in (new - old)) { tokenPublisher.tokenChanged(account) } } override fun onAccountCredentialsChanged(account: GithubAccount) = ApplicationManager.getApplication().messageBus.syncPublisher(ACCOUNT_TOKEN_CHANGED_TOPIC).tokenChanged(account) }) } companion object { @Deprecated("Use TOPIC") @Suppress("DEPRECATION") @JvmStatic val ACCOUNT_REMOVED_TOPIC = Topic("GITHUB_ACCOUNT_REMOVED", AccountRemovedListener::class.java) @Deprecated("Use TOPIC") @Suppress("DEPRECATION") @JvmStatic val ACCOUNT_TOKEN_CHANGED_TOPIC = Topic("GITHUB_ACCOUNT_TOKEN_CHANGED", AccountTokenChangedListener::class.java) fun createAccount(name: String, server: GithubServerPath) = GithubAccount(name, server) } } @Deprecated("Use GithubAuthenticationManager.addListener") interface AccountRemovedListener { fun accountRemoved(removedAccount: GithubAccount) } @Deprecated("Use GithubAuthenticationManager.addListener") interface AccountTokenChangedListener { fun tokenChanged(account: GithubAccount) }
apache-2.0
adbd8001e8705002122a3e3516a13f9f
38.681159
140
0.775667
4.8875
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnAsymmetricallyIntention.kt
2
2034
// 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.intentions.branchedTransformations.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils import org.jetbrains.kotlin.psi.* class FoldIfToReturnAsymmetricallyIntention : SelfTargetingRangeIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("replace.if.expression.with.return") ) { override fun applicabilityRange(element: KtIfExpression): TextRange? { if (BranchedFoldingUtils.getFoldableBranchedReturn(element.then) == null || element.`else` != null) { return null } val nextElement = KtPsiUtil.skipTrailingWhitespacesAndComments(element) as? KtReturnExpression if (nextElement?.returnedExpression == null) return null return element.ifKeyword.textRange } override fun applyTo(element: KtIfExpression, editor: Editor?) { val condition = element.condition!! val thenBranch = element.then!! val elseBranch = KtPsiUtil.skipTrailingWhitespacesAndComments(element) as KtReturnExpression val psiFactory = KtPsiFactory(element) val newIfExpression = psiFactory.createIf(condition, thenBranch, elseBranch) val thenReturn = BranchedFoldingUtils.getFoldableBranchedReturn(newIfExpression.then!!)!! val elseReturn = BranchedFoldingUtils.getFoldableBranchedReturn(newIfExpression.`else`!!)!! thenReturn.replace(thenReturn.returnedExpression!!) elseReturn.replace(elseReturn.returnedExpression!!) element.replace(psiFactory.createExpressionByPattern("return $0", newIfExpression)) elseBranch.delete() } }
apache-2.0
84c77eac45555327886c0aa10b4962b0
46.325581
158
0.76647
5.467742
false
false
false
false
ianhanniballake/muzei
wearable/src/main/java/com/google/android/apps/muzei/util/PanView.kt
1
16817
/* * Copyright 2014 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.apps.muzei.util import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.os.Parcel import android.os.Parcelable import android.util.AttributeSet import android.util.Log import android.view.GestureDetector import android.view.MotionEvent import android.view.View import android.widget.EdgeEffect import android.widget.OverScroller import androidx.annotation.Keep import kotlin.math.max import kotlin.math.min /** * View which supports panning around an image larger than the screen size. Supports both scrolling * and flinging */ class PanView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : View(context, attrs, defStyle) { companion object { private const val TAG = "PanView" } private var image: Bitmap? = null private var scaledImage: Bitmap? = null private var blurredImage: Bitmap? = null private var blurAmount = 0f private val drawBlurredPaint = Paint().apply { isDither = true } /** * Horizontal offset for painting the image. As this is used in a canvas.drawBitmap it ranges * from a negative value currentWidth-image.getWidth() (remember the view is smaller than the image) * to zero. If it is zero that means the offsetX side of the image is visible otherwise it is * off screen and we are farther to the right. */ private var offsetX: Float = 0f /** * Vertical offset for painting the image. As this is used in a canvas.drawBitmap it ranges * from a negative value currentHeight-image.getHeight() (remember the view is smaller than the image) * to zero. If it is zero that means the offsetY side of the image is visible otherwise it is * off screen and we are farther down. */ private var offsetY: Float = 0f /** * View width */ private var currentWidth = 1 /** * View height */ private var currentHeight = 1 // State objects and values related to gesture tracking. private val gestureDetector = GestureDetector(context, ScrollFlingGestureListener()) private val scroller = OverScroller(context) // Edge effect / overscroll tracking objects. private val edgeEffectTop = EdgeEffect(context) private val edgeEffectBottom = EdgeEffect(context) private val edgeEffectLeft = EdgeEffect(context) private val edgeEffectRight = EdgeEffect(context) private var edgeEffectTopActive = false private var edgeEffectBottomActive = false private var edgeEffectLeftActive = false private var edgeEffectRightActive = false private val animateTickRunnable = Runnable { val scaledImage = scaledImage ?: return@Runnable if (scroller.computeScrollOffset()) { // The scroller isn't finished, meaning a fling is currently active. setOffset(scroller.currX.toFloat(), scroller.currY.toFloat()) if (currentWidth != scaledImage.width && offsetX < scroller.currX && edgeEffectLeft.isFinished && !edgeEffectLeftActive) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Left edge absorbing ${scroller.currVelocity}") } edgeEffectLeft.onAbsorb(scroller.currVelocity.toInt()) edgeEffectLeftActive = true } else if (currentWidth != scaledImage.width && offsetX > scroller.currX && edgeEffectRight.isFinished && !edgeEffectRightActive) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Right edge absorbing ${scroller.currVelocity}") } edgeEffectRight.onAbsorb(scroller.currVelocity.toInt()) edgeEffectRightActive = true } if (currentHeight != scaledImage.height && offsetY < scroller.currY && edgeEffectTop.isFinished && !edgeEffectTopActive) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Top edge absorbing ${scroller.currVelocity}") } edgeEffectTop.onAbsorb(scroller.currVelocity.toInt()) edgeEffectTopActive = true } else if (currentHeight != scaledImage.height && offsetY > scroller.currY && edgeEffectBottom.isFinished && !edgeEffectBottomActive) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Bottom edge absorbing ${scroller.currVelocity}") } edgeEffectBottom.onAbsorb(scroller.currVelocity.toInt()) edgeEffectBottomActive = true } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Flinging to $offsetX, $offsetY") } invalidate() postAnimateTick() } } /** * Sets an image to be displayed. Preferably this image should be larger than this view's size * to allow scrolling. Note that the image will be centered on first display * @param image Image to display */ fun setImage(image: Bitmap?) { this.image = image updateScaledImage() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) currentWidth = max(1, w) currentHeight = max(1, h) updateScaledImage() } private fun updateScaledImage() { val image = image?.takeUnless { it.width == 0 || it.height == 0 } ?: return val width = image.width val height = image.height val scaleHeightFactor = currentHeight * 1f / height val scaleWidthFactor = currentWidth * 1f / width // Use the larger scale factor to ensure that we center crop and don't show any // black bars (rather than use the minimum and scale down to see the whole image) val scalingFactor = max(scaleHeightFactor, scaleWidthFactor) scaledImage = Bitmap.createScaledBitmap( image, (scalingFactor * width).toInt(), (scalingFactor * height).toInt(), true /* filter */) blurredImage = scaledImage.blur(context) scaledImage?.let { // Center the image offsetX = ((currentWidth - it.width) / 2).toFloat() offsetY = ((currentHeight - it.height) / 2).toFloat() } invalidate() } @Suppress("unused") @Keep fun setBlurAmount(blurAmount: Float) { this.blurAmount = blurAmount postInvalidateOnAnimation() } override fun onDraw(canvas: Canvas) { if (blurAmount < 1f) { scaledImage?.run { canvas.drawBitmap(this, offsetX, offsetY, null) } } if (blurAmount > 0f) { blurredImage?.run { drawBlurredPaint.alpha = (blurAmount * 255).toInt() canvas.drawBitmap(this, offsetX, offsetY, drawBlurredPaint) } } drawEdgeEffects(canvas) } /** * Draws the overscroll "glow" at the four edges, if necessary * * @see EdgeEffect */ private fun drawEdgeEffects(canvas: Canvas) { // The methods below rotate and translate the canvas as needed before drawing the glow, // since EdgeEffect always draws a top-glow at 0,0. var needsInvalidate = false if (!edgeEffectTop.isFinished) { val restoreCount = canvas.save() edgeEffectTop.setSize(currentWidth, currentHeight) if (edgeEffectTop.draw(canvas)) { needsInvalidate = true } canvas.restoreToCount(restoreCount) } if (!edgeEffectBottom.isFinished) { val restoreCount = canvas.save() canvas.translate((-currentWidth).toFloat(), currentHeight.toFloat()) canvas.rotate(180f, currentWidth.toFloat(), 0f) edgeEffectBottom.setSize(currentWidth, currentHeight) if (edgeEffectBottom.draw(canvas)) { needsInvalidate = true } canvas.restoreToCount(restoreCount) } if (!edgeEffectLeft.isFinished) { val restoreCount = canvas.save() canvas.translate(0f, currentHeight.toFloat()) canvas.rotate(-90f, 0f, 0f) edgeEffectLeft.setSize(currentHeight, currentWidth) if (edgeEffectLeft.draw(canvas)) { needsInvalidate = true } canvas.restoreToCount(restoreCount) } if (!edgeEffectRight.isFinished) { val restoreCount = canvas.save() canvas.translate(currentWidth.toFloat(), 0f) canvas.rotate(90f, 0f, 0f) edgeEffectRight.setSize(currentHeight, currentWidth) if (edgeEffectRight.draw(canvas)) { needsInvalidate = true } canvas.restoreToCount(restoreCount) } if (needsInvalidate) { invalidate() } } //////////////////////////////////////////////////////////////////////////////////////////////// // // Methods and objects related to gesture handling // //////////////////////////////////////////////////////////////////////////////////////////////// @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { return gestureDetector.onTouchEvent(event) || super.onTouchEvent(event) } private fun setOffset(offsetX: Float, offsetY: Float) { val scaledImage = scaledImage ?: return // Constrain between currentWidth - scaledImage.getWidth() and 0 // currentWidth - scaledImage.getWidth() -> right edge visible // 0 -> left edge visible this.offsetX = min(0f, max((currentWidth - scaledImage.width).toFloat(), offsetX)) // Constrain between currentHeight - scaledImage.getHeight() and 0 // currentHeight - scaledImage.getHeight() -> bottom edge visible // 0 -> top edge visible this.offsetY = min(0f, max((currentHeight - scaledImage.height).toFloat(), offsetY)) } /** * The gesture listener, used for handling simple gestures such as scrolls and flings. */ private inner class ScrollFlingGestureListener : GestureDetector.SimpleOnGestureListener() { override fun onDown(e: MotionEvent): Boolean { releaseEdgeEffects() scroller.forceFinished(true) invalidate() return true } override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { val scaledImage = scaledImage ?: return true val oldOffsetX = offsetX val oldOffsetY = offsetY setOffset(offsetX - distanceX, offsetY - distanceY) if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Scrolling to $offsetX, $offsetY") } if (currentWidth != scaledImage.width && offsetX < oldOffsetX - distanceX) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Left edge pulled " + -distanceX) } edgeEffectLeft.onPull(-distanceX * 1f / currentWidth) edgeEffectLeftActive = true } if (currentHeight != scaledImage.height && offsetY < oldOffsetY - distanceY) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Top edge pulled $distanceY") } edgeEffectTop.onPull(-distanceY * 1f / currentHeight) edgeEffectTopActive = true } if (currentHeight != scaledImage.height && offsetY > oldOffsetY - distanceY) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Bottom edge pulled " + -distanceY) } edgeEffectBottom.onPull(distanceY * 1f / currentHeight) edgeEffectBottomActive = true } if (currentWidth != scaledImage.width && offsetX > oldOffsetX - distanceX) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Right edge pulled $distanceX") } edgeEffectRight.onPull(distanceX * 1f / currentWidth) edgeEffectRightActive = true } invalidate() return true } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { val scaledImage = scaledImage ?: return true releaseEdgeEffects() scroller.forceFinished(true) scroller.fling( offsetX.toInt(), offsetY.toInt(), velocityX.toInt(), velocityY.toInt(), currentWidth - scaledImage.width, 0, // currentWidth - scaledImage.getWidth() is negative currentHeight - scaledImage.height, 0, // currentHeight - scaledImage.getHeight() is negative scaledImage.width / 2, scaledImage.height / 2) postAnimateTick() invalidate() return true } private fun releaseEdgeEffects() { edgeEffectBottomActive = false edgeEffectRightActive = edgeEffectBottomActive edgeEffectTopActive = edgeEffectRightActive edgeEffectLeftActive = edgeEffectTopActive edgeEffectLeft.onRelease() edgeEffectTop.onRelease() edgeEffectRight.onRelease() edgeEffectBottom.onRelease() } } private fun postAnimateTick() { handler?.run { removeCallbacks(animateTickRunnable) post(animateTickRunnable) } } //////////////////////////////////////////////////////////////////////////////////////////////// // // Methods and classes related to view state persistence. // //////////////////////////////////////////////////////////////////////////////////////////////// public override fun onSaveInstanceState(): Parcelable? { val superState = super.onSaveInstanceState() val ss = SavedState(superState) ss.offsetX = offsetX ss.offsetY = offsetY return ss } public override fun onRestoreInstanceState(state: Parcelable) { if (state !is SavedState) { super.onRestoreInstanceState(state) return } super.onRestoreInstanceState(state.superState) offsetX = state.offsetX offsetY = state.offsetY } /** * Persistent state that is saved by PanView. */ class SavedState : BaseSavedState { companion object { @Suppress("unused") @JvmField val CREATOR = object : Parcelable.Creator<SavedState> { override fun createFromParcel(source: Parcel): SavedState { return SavedState(source) } override fun newArray(size: Int): Array<SavedState?> { return arrayOfNulls(size) } } } var offsetX = 0f var offsetY = 0f constructor(superState: Parcelable?) : super(superState) internal constructor(source: Parcel) : super(source) { offsetX = source.readFloat() offsetY = source.readFloat() } override fun writeToParcel(out: Parcel, flags: Int) { super.writeToParcel(out, flags) out.writeFloat(offsetX) out.writeFloat(offsetY) } override fun toString(): String { return ("PanView.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " offset=$offsetX, $offsetY}") } } }
apache-2.0
f622f2f96e067dc87069a9a263f4f767
36.371111
113
0.585241
5.337036
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/utils/stats/TIR.kt
1
1288
package info.nightscout.androidaps.utils.stats import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlin.math.roundToInt class TIR(val date: Long, val lowThreshold: Double, val highThreshold: Double) { internal var below = 0 internal var inRange = 0 internal var above = 0 internal var error = 0 internal var count = 0 fun error() = run { error++ } fun below() = run { below++; count++ } fun inRange() = run { inRange++; count++ } fun above() = run { above++; count++ } fun belowPct() = if (count > 0) (below.toDouble() / count * 100.0).roundToInt() else 0 fun inRangePct() = if (count > 0) (inRange.toDouble() / count * 100.0).roundToInt() else 0 fun abovePct() = if (count > 0) (above.toDouble() / count * 100.0).roundToInt() else 0 fun toText(resourceHelper: ResourceHelper, dateUtil: DateUtil): String = resourceHelper.gs(R.string.tirformat, dateUtil.dateStringShort(date), belowPct(), inRangePct(), abovePct()) fun toText(resourceHelper: ResourceHelper, days: Int): String = resourceHelper.gs(R.string.tirformat, "%02d".format(days) + " " + resourceHelper.gs(R.string.days), belowPct(), inRangePct(), abovePct()) }
agpl-3.0
efc65c93472bf2d89fc734085490aaac
46.703704
205
0.694876
3.867868
false
false
false
false
kohesive/kohesive-iac
model-aws/src/test/kotlin/uy/kohesive/iac/model/aws/TestUseCase_EC2_Instance_1.kt
1
7556
package uy.kohesive.iac.model.aws import com.amazonaws.services.ec2.model.IpPermission import com.amazonaws.services.ec2.model.IpRange import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import junit.framework.TestCase import uy.kohesive.iac.model.aws.cloudformation.CloudFormationContext import uy.kohesive.iac.model.aws.cloudformation.TemplateBuilder import uy.kohesive.iac.model.aws.utils.CasePreservingJacksonNamingStrategy class TestUseCase_EC2_Instance_1 : TestCase() { fun `test launching EC2 instance using the SDK`() { val keyNameParam = ParameterizedValue.newTyped("KeyName", ParameterizedValueTypes.EC2KeyPairKeyName, constraintDescription = "KeyPair name from 1 to 255 ASCII characters.", description = "Name of an existing EC2 KeyPair to enable SSH access to the instance" ) val instanceTypeParam = ParameterizedValue.newTyped("InstanceType", ParameterizedValueTypes.String, defaultValue = "t2.small", description = "WebServer EC2 instance type", errorDescription = "Must be a valid Amazon EC2 instance type.", allowedValues = listOf( "t1.micro", "m1.small", "m1.medium", "m1.large", "m1.xlarge", "m3.medium", "m3.large", "m3.xlarge", "m3.2xlarge", "c1.medium", "c1.xlarge", "c3.large", "c3.xlarge", "c3.2xlarge", "c3.4xlarge", "c3.8xlarge", "cc2.8xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "r3.4xlarge", "r3.8xlarge", "cr1.8xlarge", "hi1.4xlarge", "hs1.8xlarge", "i2.xlarge", "i2.2xlarge", "i2.4xlarge", "i2.8xlarge" ) ) val sshLocationParam = ParameterizedValue.newString("SSHLocation", defaultValue = "0.0.0.0/0", description = "IP CIDR range for allowing SSH access to the instances", errorDescription = "Must be a valid IP CIDR range of the form x.x.x.x/x.", allowedLength = 8..18, allowedPattern = """(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})""".toRegex() ) val awsInstantType2ArchMap = MappedValues("AWSInstanceType2Arch", mapOf( "t1.micro" to mapOf("Arch" to "64"), "m1.small" to mapOf("Arch" to "64"), "m1.medium" to mapOf("Arch" to "64"), "m1.large" to mapOf("Arch" to "64"), "m1.xlarge" to mapOf("Arch" to "64"), "m3.medium" to mapOf("Arch" to "64"), "m3.large" to mapOf("Arch" to "64"), "m3.xlarge" to mapOf("Arch" to "64"), "m3.2xlarge" to mapOf("Arch" to "64"), "c1.medium" to mapOf("Arch" to "64"), "c1.xlarge" to mapOf("Arch" to "64"), "c3.large" to mapOf("Arch" to "64"), "c3.xlarge" to mapOf("Arch" to "64"), "c3.2xlarge" to mapOf("Arch" to "64"), "c3.4xlarge" to mapOf("Arch" to "64"), "c3.8xlarge" to mapOf("Arch" to "64"), "cc2.8xlarge" to mapOf("Arch" to "64HVM"), "m2.xlarge" to mapOf("Arch" to "64"), "m2.2xlarge" to mapOf("Arch" to "64"), "m2.4xlarge" to mapOf("Arch" to "64"), "r3.large" to mapOf("Arch" to "64HVM"), "r3.xlarge" to mapOf("Arch" to "64HVM"), "r3.2xlarge" to mapOf("Arch" to "64HVM"), "r3.4xlarge" to mapOf("Arch" to "64HVM"), "r3.8xlarge" to mapOf("Arch" to "64HVM"), "cr1.8xlarge" to mapOf("Arch" to "64HVM"), "hi1.4xlarge" to mapOf("Arch" to "64HVM"), "hs1.8xlarge" to mapOf("Arch" to "64HVM"), "i2.xlarge" to mapOf("Arch" to "64HVM"), "i2.2xlarge" to mapOf("Arch" to "64HVM"), "i2.4xlarge" to mapOf("Arch" to "64HVM"), "i2.8xlarge" to mapOf("Arch" to "64HVM") )) val awsRegionArchi2AmiMap = MappedValues("AWSRegionArch2AMI", mapOf( "us-east-1" to mapOf("64" to "ami-fb8e9292", "64HVM" to "ami-978d91fe"), "us-west-1" to mapOf("64" to "ami-7aba833f", "64HVM" to "ami-5aba831f"), "us-west-2" to mapOf("64" to "ami-043a5034", "64HVM" to "ami-383a5008"), "eu-west-1" to mapOf("64" to "ami-2918e35e", "64HVM" to "ami-4b18e33c"), "sa-east-1" to mapOf("64" to "ami-215dff3c", "64HVM" to "ami-635dff7e"), "ap-southeast-1" to mapOf("64" to "ami-b40d5ee6", "64HVM" to "ami-860d5ed4"), "ap-southeast-2" to mapOf("64" to "ami-3b4bd301", "64HVM" to "ami-cf4ad2f5"), "ap-northeast-1" to mapOf("64" to "ami-c9562fc8", "64HVM" to "ami-bb562fba") )) val context = CloudFormationContext("test", "ec2-instance-simple") { addVariables(keyNameParam, instanceTypeParam, sshLocationParam) addMappings(awsInstantType2ArchMap, awsRegionArchi2AmiMap) withEC2Context { val securityGroup = createSecurityGroup("InstanceSecurityGroup") { description = "Enable SSH access via port 22" } authorizeSecurityGroupIngress("InstanceSecurityGroup") { withIpPermissions( IpPermission() .withIpProtocol("tcp") .withFromPort(22) .withToPort(22) .withIpv4Ranges(IpRange().withCidrIp(sshLocationParam.value)) ) } val reservation = runInstances("EC2Instance") { instanceType = instanceTypeParam.value keyName = keyNameParam.value imageId = awsRegionArchi2AmiMap[ImplicitValues.Region.value][awsInstantType2ArchMap[instanceTypeParam.value]["Arch"]] setSecurityGroups(listOf(securityGroup)) } val instance = reservation.instances.first() modifyPlacement(instance.instanceId) { affinity = "host" tenancy = "host" hostId = "someHostId" } addAsOutput("InstanceId", instance.instanceId, "InstanceId of the newly created EC2 instance") addAsOutput("PublicDNS", instance.publicDnsName, "Public DNSName of the newly created EC2 instance") addAsOutput("PublicIP", instance.publicIpAddress, "Public IP address of the newly created EC2 instance") } } val JsonWriter = jacksonObjectMapper() .setPropertyNamingStrategy(CasePreservingJacksonNamingStrategy()) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) .writerWithDefaultPrettyPrinter() val cfTemplate = TemplateBuilder(context, description = "Create an Amazon EC2 instance running the Amazon Linux AMI.").build() println(JsonWriter.writeValueAsString(cfTemplate)) } }
mit
dc468e5e3d42dc96ebdfaebce17a92ad
45.073171
142
0.539174
3.843337
false
false
false
false
kohesive/kohesive-iac
cloudtrail-tool/src/main/kotlin/uy/kohesive/iac/model/aws/cloudtrail/preprocessing/PutBucketPolicyPreprocessor.kt
1
1557
package uy.kohesive.iac.model.aws.cloudtrail.preprocessing import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import uy.kohesive.iac.model.aws.cloudtrail.CloudTrailEvent import uy.kohesive.iac.model.aws.utils.CasePreservingJacksonNamingStrategy /** * This pre-processor fixes three things: * * 1) Event name changed to SetBucketPolicy to comply with AWS S3 API * 2) Misspelled 'buckeyPolicy' is changed to 'bucketPolicy' * 3) 'bucketPolicy' tree is converted to JSON string and put into 'policyText' * */ class PutBucketPolicyPreprocessor : CloudTrailEventPreprocessor { companion object { val JSON = jacksonObjectMapper() .setPropertyNamingStrategy(CasePreservingJacksonNamingStrategy()) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) } override val eventNames = listOf("PutBucketPolicy") override fun preprocess(event: CloudTrailEvent): CloudTrailEvent { return event.copy( eventName = "SetBucketPolicy", request = event.request?.let { requestMap -> val bucketPolicyAsJSON = ((requestMap["buckeyPolicy"] ?: requestMap["bucketPolicy"]) as? Map<String, Any?>)?.let { policyMap -> JSON.writeValueAsString(policyMap) } (requestMap - "buckeyPolicy" - "bucketPolicy" - "policy") + bucketPolicyAsJSON?.let { json -> mapOf("policyText" to json) }.orEmpty() } ) } }
mit
99429df68a78774641b1c2e3931a0557
37
143
0.680154
4.59292
false
false
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/kotlin/OrderFragmentActivity.kt
1
3380
package com.zhou.android.kotlin import android.graphics.Color import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.util.SparseArray import com.zhou.android.R import com.zhou.android.common.BaseActivity import kotlinx.android.synthetic.main.activity_order_fragemnt.* import java.util.* import kotlin.collections.ArrayList /** * 测试 ViewPager + Fragment 随机切换顺序 * Created by zhou on 2020/8/2. */ class OrderFragmentActivity : BaseActivity() { private val cache = SparseArray<TextFragment>() private val data = ArrayList<TextFragment>() private lateinit var adapter: Adapter private val random = Random() override fun setContentView() { setContentView(R.layout.activity_order_fragemnt) } override fun init() { cache.put(0, TextFragment().apply { setText("0") bg(Color.GREEN) }) cache.put(1, TextFragment().apply { setText("1") bg(Color.RED) }) cache.put(2, TextFragment().apply { setText("2") bg(Color.BLUE) }) cache.put(3, TextFragment().apply { setText("3") bg(Color.YELLOW) }) for (i in 0.until(4)) { val f = cache[i] f.mark = i data.add(f) } adapter = Adapter(supportFragmentManager, data) viewPager.adapter = adapter viewPager.offscreenPageLimit = 4 } override fun addListener() { btnChange.setOnClickListener { val array = IntArray(4) { it } val d = ArrayList<Int>() repeat(3) { var i = random.nextInt(4) while (-1 == array[i]) { i++ if (i >= 4) { i = 0 } } d.add(array[i]) array[i] = -1 } for (i in array) { if (i != -1) { d.add(i) } } data.clear() for (i in d) { data.add(cache[i]) } tvArray.text = d.joinToString() adapter.notifyDataSetChanged() viewPager.currentItem = 0 } } class Adapter(fragmentManager: FragmentManager, private val data: ArrayList<TextFragment>) : FragmentPagerAdapter(fragmentManager) { override fun getItem(position: Int): Fragment { return data[position] } override fun getCount() = data.size override fun getItemId(position: Int): Long { return data[position].hashCode().toLong() } override fun getItemPosition(obj: Any): Int { if (count == 0) return POSITION_UNCHANGED val hash = obj.hashCode() val i = (obj as TextFragment).mark if (hash == data[i].hashCode()) { return POSITION_UNCHANGED } else { for ((i, f) in data.withIndex()) { if (obj == f) { f.mark = i break } } return POSITION_NONE } } } }
mit
bcf0106087e9aac76533c92c6ee0891c
25.289063
94
0.504756
4.65928
false
false
false
false
androidx/androidx
room/room-compiler/src/test/kotlin/androidx/room/solver/TypeConverterStoreTest.kt
3
5765
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.solver import androidx.room.compiler.codegen.CodeLanguage import androidx.room.compiler.processing.util.Source import androidx.room.compiler.processing.util.runProcessorTest import androidx.room.processor.CustomConverterProcessor import androidx.room.solver.types.CompositeTypeConverter import androidx.room.solver.types.CustomTypeConverterWrapper import androidx.room.solver.types.TypeConverter import androidx.room.testing.context import androidx.room.vo.BuiltInConverterFlags import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class TypeConverterStoreTest { @Test fun multiStepTypeConverters() { val source = Source.kotlin( "Foo.kt", """ import androidx.room.* interface Type1_Super interface Type1 : Type1_Super interface Type1_Sub : Type1 interface Type2_Super interface Type2 : Type2_Super interface Type2_Sub : Type2 interface JumpType_1 interface JumpType_2 interface JumpType_3 class MyConverters { @TypeConverter fun t1_jump1(inp : Type1): JumpType_1 = TODO() @TypeConverter fun jump1_t2_Sub(inp : JumpType_1): Type2_Sub = TODO() @TypeConverter fun jump1_t2(inp : JumpType_1): Type2 = TODO() @TypeConverter fun t1_super_jump2(inp : Type1_Super): JumpType_2 = TODO() @TypeConverter fun jump2_jump3(inp : JumpType_2): JumpType_3 = TODO() @TypeConverter fun jump2_Type2_Sub(inp : JumpType_3): Type2_Sub = TODO() } """.trimIndent() ) runProcessorTest(sources = listOf(source)) { invocation -> val convertersElm = invocation.processingEnv.requireTypeElement("MyConverters") val converters = CustomConverterProcessor(invocation.context, convertersElm) .process() val store = TypeAdapterStore.create( invocation.context, BuiltInConverterFlags.DEFAULT, converters.map(::CustomTypeConverterWrapper) ).typeConverterStore fun findConverter(from: String, to: String): String? { val input = invocation.processingEnv.requireType(from) val output = invocation.processingEnv.requireType(to) return store.findTypeConverter( input = input, output = output )?.also { // validate that it makes sense to ensure test is correct assertThat(output.isAssignableFrom(it.to)).isTrue() assertThat(it.from.isAssignableFrom(input)).isTrue() }?.toSignature() } assertThat( findConverter("Type1", "Type2") ).isEqualTo( "Type1 -> JumpType_1 : JumpType_1 -> Type2" ) assertThat( findConverter("Type1", "Type2_Sub") ).isEqualTo( "Type1 -> JumpType_1 : JumpType_1 -> Type2_Sub" ) assertThat( findConverter("Type1_Super", "Type2_Super") ).isEqualTo( "Type1_Super -> JumpType_2 : JumpType_2 -> JumpType_3 : JumpType_3 -> Type2_Sub" .let { tillSub -> if (invocation.context.useNullAwareConverter) { // new type converter will have a step for upcasts too "$tillSub : Type2_Sub -> Type2_Super" } else { tillSub } } ) assertThat( findConverter("Type1", "Type2_Sub") ).isEqualTo( "Type1 -> JumpType_1 : JumpType_1 -> Type2_Sub" ) assertThat( findConverter("Type1_Sub", "Type2_Sub") ).isEqualTo( "Type1 -> JumpType_1 : JumpType_1 -> Type2_Sub".let { end -> if (invocation.context.useNullAwareConverter) { // new type converter will have a step for upcasts too "Type1_Sub -> Type1 : $end" } else { end } } ) assertThat( findConverter("Type2", "Type2_Sub") ).isNull() assertThat( findConverter("Type2", "Type1") ).isNull() } } private fun TypeConverter.toSignature(): String { return when (this) { is CompositeTypeConverter -> "${conv1.toSignature()} : ${conv2.toSignature()}" else -> from.asTypeName().toString(CodeLanguage.JAVA) + " -> " + to.asTypeName().toString(CodeLanguage.JAVA) } } }
apache-2.0
8333f4dfeb22e7180209f39325fd76ef
39.041667
96
0.555074
4.918942
false
false
false
false
holisticon/ranked
backend/application/src/main/kotlin/form/Form.kt
1
2909
@file:Suppress("PackageDirectoryMismatch", "unused") package de.holisticon.ranked.form import de.holisticon.ranked.command.api.CreateMatch import de.holisticon.ranked.model.MatchSet import de.holisticon.ranked.model.Player import de.holisticon.ranked.model.Team import de.holisticon.ranked.model.UserName import de.holisticon.ranked.view.player.PlayerViewService import org.axonframework.commandhandling.gateway.CommandGateway import org.springframework.stereotype.Controller import org.springframework.validation.BindingResult import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.ModelAttribute import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.servlet.config.annotation.WebMvcConfigurer import javax.validation.Valid @Controller class WebController(val commandGateway: CommandGateway, val playerViewService: PlayerViewService) : WebMvcConfigurer { @ModelAttribute("players") fun allPlayers(): List<Player> { return playerViewService.findAllPlayers() } @GetMapping("/") fun showForm(createMatchForm: CreateMatchForm): String = "create-match" @PostMapping("/") fun checkPersonInfo(@Valid form: CreateMatchForm, bindingResult: BindingResult): String { val sets = mutableListOf<MatchSet>() if (form.goalsBlue1 == 6 || form.goalsRed1 == 6) { sets.add(MatchSet( goalsRed = form.goalsRed1, goalsBlue = form.goalsBlue1, offenseRed = UserName(form.offenseRed1), offenseBlue = UserName(form.offenseBlue1) )) } if (form.goalsBlue2 == 6 || form.goalsRed2 == 6) { sets.add(MatchSet( goalsRed = form.goalsRed2, goalsBlue = form.goalsBlue2, offenseRed = UserName(form.offenseRed2), offenseBlue = UserName(form.offenseBlue2) )) } if (form.goalsBlue3 == 6 || form.goalsRed3 == 6) { sets.add(MatchSet( goalsRed = form.goalsRed3, goalsBlue = form.goalsBlue3, offenseRed = UserName(form.offenseRed3), offenseBlue = UserName(form.offenseBlue3) )) } val cmd = CreateMatch( teamRed = Team(UserName(form.red1), UserName(form.red2)), teamBlue = Team(UserName(form.blue1), UserName(form.blue2)), matchSets = sets ) commandGateway.send<CreateMatch>(cmd) return "redirect:/view/wall/matches" } } data class CreateMatchForm( var blue1: String = "", var blue2: String = "", var red1: String = "", var red2: String = "", // set 1 var goalsBlue1: Int = 0, var goalsRed1: Int = 0, var offenseBlue1: String = "", var offenseRed1: String = "", // set 2 var goalsBlue2: Int = 0, var goalsRed2: Int = 0, var offenseBlue2: String = "", var offenseRed2: String = "", // set 3 var goalsBlue3: Int = 0, var goalsRed3: Int = 0, var offenseBlue3: String = "", var offenseRed3: String = "" )
bsd-3-clause
7337a792b92327beebac3a86c8d58f14
29.302083
118
0.704022
3.963215
false
false
false
false
lnr0626/cfn-templates
aws/src/main/kotlin/com/lloydramey/cfn/model/aws/applicationautoscaling/StepScalingPolicyConfiguration.kt
1
1086
/* * Copyright 2017 Lloyd Ramey <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lloydramey.cfn.model.aws.applicationautoscaling import com.lloydramey.cfn.model.aws.autoscaling.AdjustmentType import com.lloydramey.cfn.model.aws.autoscaling.StepAdjustment data class StepScalingPolicyConfiguration( val adjustmentType: AdjustmentType? = null, val cooldown: Int? = null, val metricAggregationType: MetricAggregationType? = null, val minAdjustmentMagnitude: Int? = null, val stepAdjustments: List<StepAdjustment>? = null )
apache-2.0
d65b8f4a3cb0bf4265196ce983c8bebf
39.259259
75
0.764273
4.176923
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/lightClasses/LightClassSampleTest.kt
2
2700
// 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.lightClasses import com.intellij.psi.PsiClass import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration import org.jetbrains.kotlin.idea.lightClasses.LightClassEqualsTest.doTestEquals import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class LightClassSampleTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance() fun testDeprecationLevelHIDDEN() { // KT27243 myFixture.configureByText( "a.kt", """ interface A { @Deprecated(level = DeprecationLevel.HIDDEN, message = "nothing") fun foo() } """.trimMargin() ) myFixture.configureByText( "b.kt", """ class B : A { @Deprecated(level = DeprecationLevel.HIDDEN, message = "nothing") override fun foo() {} } """.trimIndent() ) doTestAndCheck("B", "foo", 0) } fun testJvmSynthetic() { // KT33561 myFixture.configureByText( "foo.kt", """ class Foo { @JvmSynthetic inline fun foo(crossinline getter: () -> String) = foo(getter()) fun foo(getter: String) = println(getter) } """.trimIndent() ) doTestAndCheck("Foo", "foo", 1) } @Suppress("SameParameterValue") private fun doTestAndCheck(className: String, methodName: String, methods: Int) { val theClass: PsiClass = myFixture.javaFacade.findClass(className) assertNotNull(theClass) UsefulTestCase.assertInstanceOf( theClass, KtLightClassForSourceDeclaration::class.java ) doTestEquals((theClass as KtLightClass).kotlinOrigin) assertEquals( methods, theClass.allMethods.plus(theClass.allMethods.flatMap { it.findSuperMethods().toList() }).count { it.name == methodName }, ) } }
apache-2.0
9b2e0038e711beb2deb63a864587df4d
35.5
133
0.637778
5.325444
false
true
false
false
siosio/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/filter/JvmDebuggerAddFilterStartupActivity.kt
1
968
// 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.debugger.filter import com.intellij.debugger.settings.DebuggerSettings import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.ui.classFilter.ClassFilter private const val KOTLIN_STDLIB_FILTER = "kotlin.*" class JvmDebuggerAddFilterStartupActivity : StartupActivity { override fun runActivity(project: Project) { addKotlinStdlibDebugFilterIfNeeded() } } fun addKotlinStdlibDebugFilterIfNeeded() { val settings = DebuggerSettings.getInstance() ?: return val existingFilters = settings.steppingFilters if (existingFilters.any { it.pattern == KOTLIN_STDLIB_FILTER }) { return } settings.steppingFilters = settings.steppingFilters + ClassFilter(KOTLIN_STDLIB_FILTER) }
apache-2.0
ab32fcd4f858186ef27253cccb5d17c7
34.888889
158
0.778926
4.440367
false
false
false
false
siosio/intellij-community
plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/GroovyGradleBuildScriptSupport.kt
2
22592
// 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.groovy import com.intellij.openapi.module.Module import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ExternalLibraryDescriptor import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.cli.common.arguments.CliArgumentStringBuilder.buildArgumentString import org.jetbrains.kotlin.cli.common.arguments.CliArgumentStringBuilder.replaceLanguageFeature import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.configuration.* import org.jetbrains.kotlin.idea.extensions.* import org.jetbrains.kotlin.idea.extensions.gradle.* import org.jetbrains.kotlin.idea.groovy.inspections.DifferentKotlinGradleVersionInspection import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.projectStructure.module import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.plugins.groovy.lang.psi.GroovyFile import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner object GroovyGradleBuildScriptSupport : GradleBuildScriptSupport { override fun createManipulator( file: PsiFile, preferNewSyntax: Boolean, versionProvider: GradleVersionProvider ): GroovyBuildScriptManipulator? { if (file !is GroovyFile) { return null } return GroovyBuildScriptManipulator(file, preferNewSyntax, versionProvider) } override fun createScriptBuilder(file: PsiFile): SettingsScriptBuilder<*>? { return if (file is GroovyFile) GroovySettingsScriptBuilder(file) else null } } class GroovyBuildScriptManipulator( override val scriptFile: GroovyFile, override val preferNewSyntax: Boolean, private val versionProvider: GradleVersionProvider ) : GradleBuildScriptManipulator<GroovyFile> { override fun isApplicable(file: PsiFile) = file is GroovyFile private val gradleVersion = versionProvider.fetchGradleVersion(scriptFile) override fun isConfiguredWithOldSyntax(kotlinPluginName: String): Boolean { val fileText = runReadAction { scriptFile.text } return containsDirective(fileText, getApplyPluginDirective(kotlinPluginName)) && fileText.contains("org.jetbrains.kotlin") && fileText.contains("kotlin-stdlib") } override fun isConfigured(kotlinPluginExpression: String): Boolean { val fileText = runReadAction { scriptFile.text } val pluginsBlockText = runReadAction { scriptFile.getBlockByName("plugins")?.text ?: "" } return (containsDirective(pluginsBlockText, kotlinPluginExpression)) && fileText.contains("org.jetbrains.kotlin") && fileText.contains("kotlin-stdlib") } override fun configureModuleBuildScript( kotlinPluginName: String, kotlinPluginExpression: String, stdlibArtifactName: String, version: String, jvmTarget: String? ): Boolean { val oldText = scriptFile.text val useNewSyntax = useNewSyntax(kotlinPluginName, gradleVersion, versionProvider) if (useNewSyntax) { scriptFile .getPluginsBlock() .addLastExpressionInBlockIfNeeded("$kotlinPluginExpression version '$version'") scriptFile.getRepositoriesBlock().apply { val repository = getRepositoryForVersion(version) val gradleFacade = KotlinGradleFacade.instance if (repository != null && gradleFacade != null) { scriptFile.module?.getBuildScriptSettingsPsiFile()?.let { with(gradleFacade.getManipulator(it)) { addPluginRepository(repository) addMavenCentralPluginRepository() addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY) } } } } } else { val applyPluginDirective = getGroovyApplyPluginDirective(kotlinPluginName) if (!containsDirective(scriptFile.text, applyPluginDirective)) { val apply = GroovyPsiElementFactory.getInstance(scriptFile.project).createExpressionFromText(applyPluginDirective) val applyStatement = getApplyStatement(scriptFile) if (applyStatement != null) { scriptFile.addAfter(apply, applyStatement) } else { val anchorBlock = scriptFile.getBlockByName("plugins") ?: scriptFile.getBlockByName("buildscript") if (anchorBlock != null) { scriptFile.addAfter(apply, anchorBlock.parent) } else { scriptFile.addAfter(apply, scriptFile.statements.lastOrNull() ?: scriptFile.firstChild) } } } } scriptFile.getRepositoriesBlock().apply { addRepository(version) addMavenCentralIfMissing() } scriptFile.getDependenciesBlock().apply { addExpressionOrStatementInBlockIfNeeded( getGroovyDependencySnippet(stdlibArtifactName, !useNewSyntax, gradleVersion), isStatement = false, isFirst = false ) } if (jvmTarget != null) { changeKotlinTaskParameter(scriptFile, "jvmTarget", jvmTarget, forTests = false) changeKotlinTaskParameter(scriptFile, "jvmTarget", jvmTarget, forTests = true) } return scriptFile.text != oldText } override fun configureProjectBuildScript(kotlinPluginName: String, version: String): Boolean { if (useNewSyntax(kotlinPluginName, gradleVersion, versionProvider)) return false val oldText = scriptFile.text scriptFile.apply { getBuildScriptBlock().apply { addFirstExpressionInBlockIfNeeded(VERSION.replace(VERSION_TEMPLATE, version)) } getBuildScriptRepositoriesBlock().apply { addRepository(version) addMavenCentralIfMissing() } getBuildScriptDependenciesBlock().apply { addLastExpressionInBlockIfNeeded(CLASSPATH) } } return oldText != scriptFile.text } override fun changeLanguageFeatureConfiguration( feature: LanguageFeature, state: LanguageFeature.State, forTests: Boolean ): PsiElement? { if (usesNewMultiplatform()) { state.assertApplicableInMultiplatform() val kotlinBlock = scriptFile.getKotlinBlock() val sourceSetsBlock = kotlinBlock.getSourceSetsBlock() val allBlock = sourceSetsBlock.getBlockOrCreate("all") allBlock.addLastExpressionInBlockIfNeeded("languageSettings.enableLanguageFeature(\"${feature.name}\")") return allBlock.statements.lastOrNull() } val kotlinVersion = DifferentKotlinGradleVersionInspection.getKotlinPluginVersion(scriptFile) val featureArgumentString = feature.buildArgumentString(state, kotlinVersion) val parameterName = "freeCompilerArgs" return addOrReplaceKotlinTaskParameter( scriptFile, parameterName, "[\"$featureArgumentString\"]", forTests ) { insideKotlinOptions -> val prefix = if (insideKotlinOptions) "kotlinOptions." else "" val newText = text.replaceLanguageFeature( feature, state, kotlinVersion, prefix = "$prefix$parameterName = [", postfix = "]" ) replaceWithStatementFromText(newText) } } override fun changeLanguageVersion(version: String, forTests: Boolean): PsiElement? = changeKotlinTaskParameter(scriptFile, "languageVersion", version, forTests) override fun changeApiVersion(version: String, forTests: Boolean): PsiElement? = changeKotlinTaskParameter(scriptFile, "apiVersion", version, forTests) @Suppress("OverridingDeprecatedMember") override fun addKotlinLibraryToModuleBuildScript( scope: DependencyScope, libraryDescriptor: ExternalLibraryDescriptor ) = addKotlinLibraryToModuleBuildScript(null, scope, libraryDescriptor) override fun addKotlinLibraryToModuleBuildScript( targetModule: Module?, scope: DependencyScope, libraryDescriptor: ExternalLibraryDescriptor ) { val dependencyString = String.format( "%s \"%s:%s:%s\"", scope.toGradleCompileScope(scriptFile.module?.getBuildSystemType() == BuildSystemType.AndroidGradle), libraryDescriptor.libraryGroupId, libraryDescriptor.libraryArtifactId, libraryDescriptor.maxVersion ) if (targetModule != null && usesNewMultiplatform()) { scriptFile .getKotlinBlock() .getSourceSetsBlock() .getBlockOrCreate(targetModule.name.takeLastWhile { it != '.' }) .getDependenciesBlock() .addLastExpressionInBlockIfNeeded(dependencyString) } else { scriptFile.getDependenciesBlock().apply { addLastExpressionInBlockIfNeeded(dependencyString) } } } override fun getKotlinStdlibVersion(): String? { val versionProperty = "\$kotlin_version" scriptFile.getBlockByName("buildScript")?.let { if (it.text.contains("ext.kotlin_version = ")) { return versionProperty } } val dependencies = scriptFile.getBlockByName("dependencies")?.statements val stdlibArtifactPrefix = "org.jetbrains.kotlin:kotlin-stdlib:" dependencies?.forEach { dependency -> val dependencyText = dependency.text val startIndex = dependencyText.indexOf(stdlibArtifactPrefix) + stdlibArtifactPrefix.length val endIndex = dependencyText.length - 1 if (startIndex != -1 && endIndex != -1) { return dependencyText.substring(startIndex, endIndex) } } return null } private fun addPluginRepositoryExpression(expression: String) { scriptFile .getBlockOrPrepend("pluginManagement") .getBlockOrCreate("repositories") .addLastExpressionInBlockIfNeeded(expression) } override fun addMavenCentralPluginRepository() { addPluginRepositoryExpression("mavenCentral()") } override fun addPluginRepository(repository: RepositoryDescription) { addPluginRepositoryExpression(repository.toGroovyRepositorySnippet()) } override fun addResolutionStrategy(pluginId: String) { scriptFile .getBlockOrPrepend("pluginManagement") .getBlockOrCreate("resolutionStrategy") .getBlockOrCreate("eachPlugin") .addLastStatementInBlockIfNeeded( """ if (requested.id.id == "$pluginId") { useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}") } """.trimIndent() ) } private fun GrClosableBlock.addParameterAssignment( parameterName: String, defaultValue: String, replaceIt: GrStatement.(Boolean) -> GrStatement ) { statements.firstOrNull { stmt -> (stmt as? GrAssignmentExpression)?.lValue?.text == parameterName }?.let { stmt -> stmt.replaceIt(false) } ?: addLastExpressionInBlockIfNeeded("$parameterName = $defaultValue") } private fun String.extractTextFromQuotes(quoteCharacter: Char): String? { val quoteIndex = indexOf(quoteCharacter) if (quoteIndex != -1) { val lastQuoteIndex = lastIndexOf(quoteCharacter) return if (lastQuoteIndex > quoteIndex) substring(quoteIndex + 1, lastQuoteIndex) else null } return null } private fun String.extractTextFromQuotes(): String = extractTextFromQuotes('\'') ?: extractTextFromQuotes('"') ?: this private fun addOrReplaceKotlinTaskParameter( gradleFile: GroovyFile, parameterName: String, defaultValue: String, forTests: Boolean, replaceIt: GrStatement.(Boolean) -> GrStatement ): PsiElement? { if (usesNewMultiplatform()) { val kotlinBlock = gradleFile.getKotlinBlock() val kotlinTargets = kotlinBlock.getBlockOrCreate("targets") val targetNames = mutableListOf<String>() fun GrStatement.handleTarget(targetExpectedText: String) { if (this is GrMethodCallExpression && invokedExpression.text == targetExpectedText) { val targetNameArgument = argumentList.expressionArguments.getOrNull(1)?.text if (targetNameArgument != null) { targetNames += targetNameArgument.extractTextFromQuotes() } } } for (target in kotlinTargets.statements) { target.handleTarget("fromPreset") } for (target in kotlinBlock.statements) { target.handleTarget("targets.fromPreset") } val configureBlock = kotlinTargets.getBlockOrCreate("configure") val factory = GroovyPsiElementFactory.getInstance(kotlinTargets.project) val argumentList = factory.createArgumentListFromText( targetNames.joinToString(prefix = "([", postfix = "])", separator = ", ") ) configureBlock.getStrictParentOfType<GrMethodCallExpression>()!!.argumentList.replaceWithArgumentList(argumentList) val kotlinOptions = configureBlock.getBlockOrCreate("tasks.getByName(compilations.main.compileKotlinTaskName).kotlinOptions") kotlinOptions.addParameterAssignment(parameterName, defaultValue, replaceIt) return kotlinOptions.parent.parent } val kotlinBlock = gradleFile.getBlockOrCreate(if (forTests) "compileTestKotlin" else "compileKotlin") for (stmt in kotlinBlock.statements) { if ((stmt as? GrAssignmentExpression)?.lValue?.text == "kotlinOptions.$parameterName") { return stmt.replaceIt(true) } } kotlinBlock.getBlockOrCreate("kotlinOptions").addParameterAssignment(parameterName, defaultValue, replaceIt) return kotlinBlock.parent } private fun changeKotlinTaskParameter( gradleFile: GroovyFile, parameterName: String, parameterValue: String, forTests: Boolean ): PsiElement? { return addOrReplaceKotlinTaskParameter( gradleFile, parameterName, "\"$parameterValue\"", forTests ) { insideKotlinOptions -> if (insideKotlinOptions) { replaceWithStatementFromText("kotlinOptions.$parameterName = \"$parameterValue\"") } else { replaceWithStatementFromText("$parameterName = \"$parameterValue\"") } } } private fun getGroovyDependencySnippet( artifactName: String, withVersion: Boolean, gradleVersion: GradleVersionInfo ): String { val configuration = gradleVersion.scope("implementation", versionProvider) return "$configuration \"org.jetbrains.kotlin:$artifactName${if (withVersion) ":\$kotlin_version" else ""}\"" } private fun getApplyPluginDirective(pluginName: String) = "apply plugin: '$pluginName'" private fun containsDirective(fileText: String, directive: String): Boolean { return fileText.contains(directive) || fileText.contains(directive.replace("\"", "'")) || fileText.contains(directive.replace("'", "\"")) } private fun getApplyStatement(file: GroovyFile): GrApplicationStatement? = file.getChildrenOfType<GrApplicationStatement>().find { it.invokedExpression.text == "apply" } private fun GrClosableBlock.addRepository(version: String): Boolean { val repository = getRepositoryForVersion(version) val snippet = when { repository != null -> repository.toGroovyRepositorySnippet() !isRepositoryConfigured(text) -> "$MAVEN_CENTRAL\n" else -> return false } return addLastExpressionInBlockIfNeeded(snippet) } private fun GrStatementOwner.getBuildScriptBlock() = getBlockOrCreate("buildscript") { newBlock -> val pluginsBlock = getBlockByName("plugins") ?: return@getBlockOrCreate false addBefore(newBlock, pluginsBlock.parent) true } private fun GrStatementOwner.getBuildScriptRepositoriesBlock(): GrClosableBlock = getBuildScriptBlock().getRepositoriesBlock() private fun GrStatementOwner.getBuildScriptDependenciesBlock(): GrClosableBlock = getBuildScriptBlock().getDependenciesBlock() private fun GrClosableBlock.addMavenCentralIfMissing(): Boolean = if (!isRepositoryConfigured(text)) addLastExpressionInBlockIfNeeded(MAVEN_CENTRAL) else false private fun GrStatementOwner.getRepositoriesBlock() = getBlockOrCreate("repositories") private fun GrStatementOwner.getDependenciesBlock(): GrClosableBlock = getBlockOrCreate("dependencies") private fun GrStatementOwner.getKotlinBlock(): GrClosableBlock = getBlockOrCreate("kotlin") private fun GrStatementOwner.getSourceSetsBlock(): GrClosableBlock = getBlockOrCreate("sourceSets") private fun GrClosableBlock.addOrReplaceExpression(snippet: String, predicate: (GrStatement) -> Boolean) { statements.firstOrNull(predicate)?.let { stmt -> stmt.replaceWithStatementFromText(snippet) return } addLastExpressionInBlockIfNeeded(snippet) } private fun getGroovyApplyPluginDirective(pluginName: String) = "apply plugin: '$pluginName'" private fun GrStatement.replaceWithStatementFromText(snippet: String): GrStatement { val newStatement = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(snippet) newStatement.reformatted() return replaceWithStatement(newStatement) } companion object { private const val VERSION_TEMPLATE = "\$VERSION$" private val VERSION = String.format("ext.kotlin_version = '%s'", VERSION_TEMPLATE) private const val GRADLE_PLUGIN_ID = "kotlin-gradle-plugin" private val CLASSPATH = "classpath \"$KOTLIN_GROUP_ID:$GRADLE_PLUGIN_ID:\$kotlin_version\"" private fun PsiElement.getBlockByName(name: String): GrClosableBlock? { return getChildrenOfType<GrMethodCallExpression>() .filter { it.closureArguments.isNotEmpty() } .find { it.invokedExpression.text == name } ?.let { it.closureArguments[0] } } fun GrStatementOwner.getBlockOrCreate( name: String, customInsert: GrStatementOwner.(newBlock: PsiElement) -> Boolean = { false } ): GrClosableBlock { var block = getBlockByName(name) if (block == null) { val factory = GroovyPsiElementFactory.getInstance(project) val newBlock = factory.createExpressionFromText("$name{\n}\n") if (!customInsert(newBlock)) { addAfter(newBlock, statements.lastOrNull() ?: firstChild) } block = getBlockByName(name)!! } return block } fun GrStatementOwner.getBlockOrPrepend(name: String) = getBlockOrCreate(name) { newBlock -> addAfter(newBlock, null) true } fun GrStatementOwner.getPluginsBlock() = getBlockOrCreate("plugins") { newBlock -> addAfter(newBlock, getBlockByName("buildscript")) true } fun GrClosableBlock.addLastExpressionInBlockIfNeeded(expressionText: String): Boolean = addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = false, isFirst = false) fun GrClosableBlock.addLastStatementInBlockIfNeeded(expressionText: String): Boolean = addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = true, isFirst = false) private fun GrClosableBlock.addFirstExpressionInBlockIfNeeded(expressionText: String): Boolean = addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = false, isFirst = true) private fun GrClosableBlock.addExpressionOrStatementInBlockIfNeeded(text: String, isStatement: Boolean, isFirst: Boolean): Boolean { if (statements.any { StringUtil.equalsIgnoreWhitespaces(it.text, text) }) return false val psiFactory = GroovyPsiElementFactory.getInstance(project) val newStatement = if (isStatement) psiFactory.createStatementFromText(text) else psiFactory.createExpressionFromText(text) newStatement.reformatted() if (!isFirst && statements.isNotEmpty()) { val lastStatement = statements[statements.size - 1] if (lastStatement != null) { addAfter(newStatement, lastStatement) } } else { if (firstChild != null) { addAfter(newStatement, firstChild) } } return true } } }
apache-2.0
348821958a5ce412807a23acb91ead41
42.782946
158
0.663155
6.002125
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpData.kt
1
3930
// 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.pullUp import com.intellij.psi.PsiNamedElement import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.memberInfo.getClassDescriptorIfAny import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.substitutions.getTypeSubstitution import org.jetbrains.kotlin.utils.keysToMapExceptNulls class KotlinPullUpData( val sourceClass: KtClassOrObject, val targetClass: PsiNamedElement, val membersToMove: Collection<KtNamedDeclaration> ) { val resolutionFacade = sourceClass.getResolutionFacade() val sourceClassContext = resolutionFacade.analyzeWithAllCompilerChecks(listOf(sourceClass)).bindingContext val sourceClassDescriptor = sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, sourceClass] as ClassDescriptor val memberDescriptors = membersToMove.keysToMapExceptNulls { when (it) { is KtPsiClassWrapper -> it.psiClass.getJavaClassDescriptor(resolutionFacade) is KtParameter -> sourceClassContext[BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, it] else -> sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] } } val targetClassDescriptor = targetClass.getClassDescriptorIfAny(resolutionFacade)!! val superEntryForTargetClass = sourceClass.getSuperTypeEntryByDescriptor(targetClassDescriptor, sourceClassContext) val targetClassSuperResolvedCall = superEntryForTargetClass.getResolvedCall(sourceClassContext) private val typeParametersInSourceClassContext by lazy { sourceClassDescriptor.declaredTypeParameters + sourceClass.getResolutionScope(sourceClassContext, resolutionFacade) .collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS) .filterIsInstance<TypeParameterDescriptor>() } val sourceToTargetClassSubstitutor: TypeSubstitutor by lazy { val substitution = LinkedHashMap<TypeConstructor, TypeProjection>() typeParametersInSourceClassContext.forEach { substitution[it.typeConstructor] = TypeProjectionImpl(TypeIntersector.getUpperBoundsAsType(it)) } val superClassSubstitution = getTypeSubstitution(targetClassDescriptor.defaultType, sourceClassDescriptor.defaultType) ?: emptyMap<TypeConstructor, TypeProjection>() for ((typeConstructor, typeProjection) in superClassSubstitution) { val subClassTypeParameter = typeProjection.type.constructor.declarationDescriptor as? TypeParameterDescriptor ?: continue val superClassTypeParameter = typeConstructor.declarationDescriptor ?: continue substitution[subClassTypeParameter.typeConstructor] = TypeProjectionImpl(superClassTypeParameter.defaultType) } TypeSubstitutor.create(substitution) } val isInterfaceTarget: Boolean = targetClassDescriptor.kind == ClassKind.INTERFACE }
apache-2.0
ee6e27dcefb841451a50265e551994de
50.038961
158
0.801272
5.813609
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/text/regex/MatchResultImpl.kt
2
8267
/* * 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. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlin.text.regex /** * Match result implementation */ internal class MatchResultImpl /** * @param input an input sequence for matching/searching. * @param regex a [Regex] instance used for matching/searching. * @param rightBound index in the [input] used as a right bound for matching/searching. Exclusive. */ constructor (internal val input: CharSequence, internal val regex: Regex) : MatchResult { // Harmony's implementation ======================================================================================== private val nativePattern = regex.nativePattern private val groupCount = nativePattern.capturingGroupCount private val groupBounds = IntArray(groupCount * 2) { -1 } private val consumers = IntArray(nativePattern.consumersCount + 1) { -1 } // Used by quantifiers to store a count of a quantified expression occurrences. val enterCounters: IntArray = IntArray( maxOf(nativePattern.groupQuantifierCount, 0) ) var startIndex: Int = 0 set (startIndex: Int) { field = startIndex if (previousMatch < 0) { previousMatch = startIndex } } var previousMatch = -1 var mode = Regex.Mode.MATCH // MatchResult interface =========================================================================================== /** The range of indices in the original string where match was captured. */ override val range: IntRange get() = getStart(0) until getEnd(0) /** The substring from the input string captured by this match. */ override val value: String get() = group(0) ?: throw AssertionError("No groupIndex #0 in the match result.") /** * A collection of groups matched by the regular expression. * * This collection has size of `groupCount + 1` where `groupCount` is the count of groups in the regular expression. * Groups are indexed from 1 to `groupCount` and group with the index 0 corresponds to the entire match. */ // Create one object or several ones? override val groups: MatchGroupCollection = object: MatchGroupCollection, AbstractCollection<MatchGroup?>() { override val size: Int get() = [email protected] override fun iterator(): Iterator<MatchGroup?> { return object: Iterator<MatchGroup?> { var nextIndex: Int = 0 override fun hasNext(): Boolean { return nextIndex < size } override fun next(): MatchGroup? { if (!hasNext()) { throw NoSuchElementException() } return get(nextIndex++) } } } override fun get(index: Int): MatchGroup? { val value = group(index) ?: return null return MatchGroup(value, getStart(index) until getEnd(index)) } } /** * A list of matched indexed group values. * * This list has size of `groupCount + 1` where `groupCount` is the count of groups in the regular expression. * Groups are indexed from 1 to `groupCount` and group with the index 0 corresponds to the entire match. * * If the group in the regular expression is optional and there were no match captured by that group, * corresponding item in [groupValues] is an empty string. * * @sample: samples.text.Regexps.matchDestructuringToGroupValues */ override val groupValues: List<String> get() = mutableListOf<String>().apply { for (i in 0 until groupCount) { this.add(group(i) ?: "") } } override fun next(): MatchResult? { var nextStart = range.endInclusive + 1 // If the current match is empty - shift by 1. if (nextStart == range.start) { nextStart++ } if (nextStart > input.length) { return null } return regex.find(input, nextStart) } // ================================================================================================================= // Harmony's implementation ======================================================================================== fun setConsumed(counter: Int, value: Int) { this.consumers[counter] = value } fun getConsumed(counter: Int): Int { return this.consumers[counter] } fun isCaptured(group: Int): Boolean = getStart(group) >= 0 // Setters and getters for starts and ends of groups =============================================================== internal fun setStart(group: Int, offset: Int) { checkGroup(group) groupBounds[group * 2] = offset } internal fun setEnd(group: Int, offset: Int) { checkGroup(group) groupBounds[group * 2 + 1] = offset } /** * Returns the index of the first character of the text that matched a given group. * * @param group the group, ranging from 0 to groupCount() - 1, with 0 representing the whole pattern. * @return the character index. */ fun getStart(group: Int = 0): Int { checkGroup(group) return groupBounds[group * 2] } /** * Returns the index of the first character following the text that matched a given group. * * @param group the group, ranging from 0 to groupCount() - 1, with 0 representing the whole pattern. * @return the character index. */ fun getEnd(group: Int = 0): Int { checkGroup(group) return groupBounds[group * 2 + 1] } // ================================================================================================== /** * Returns the text that matched a given group of the regular expression. * * @param group the group, ranging from 0 to groupCount() - 1, with 0 representing the whole pattern. * @return the text that matched the group. */ fun group(group: Int = 0): String? { val start = getStart(group) val end = getEnd(group) if (start < 0 || end < 0) { return null } return input.subSequence(getStart(group), getEnd(group)).toString() } /** * Returns the number of groups in the result, which is always equal to * the number of groups in the original regular expression. * * @return the number of groups. */ fun groupCount(): Int { return groupCount - 1 } /* * This method being called after any successful match; For now it's being * used to check zero group for empty match; */ fun finalizeMatch() { if (this.groupBounds[0] == -1) { this.groupBounds[0] = this.startIndex this.groupBounds[1] = this.startIndex } previousMatch = getEnd() } private fun checkGroup(group: Int) { if (group < 0 || group > groupCount) { throw IndexOutOfBoundsException("Group index out of bounds: $group") } } fun updateGroup(index: Int, srtOffset: Int, endOffset: Int) { checkGroup(index) groupBounds[index * 2] = srtOffset groupBounds[index * 2 + 1] = endOffset } }
apache-2.0
a369b165eb427d461e6706a4197b6bbb
34.787879
120
0.58171
4.840164
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/model/expectations/PoolAverageLoadExpectation.kt
2
799
package com.github.kerubistan.kerub.model.expectations import com.fasterxml.jackson.annotation.JsonTypeName import com.github.kerubistan.kerub.model.ExpectationLevel /** * */ @JsonTypeName("pool-average-load") data class PoolAverageLoadExpectation(val max: Int = 90, val min: Int = 10, val toleranceMs: Int = 10000, override val level: ExpectationLevel = ExpectationLevel.Want) : PoolExpectation { companion object { val loadRange = 1..100 } init { check(max > min) { "Maximum load ($max) must be larger than minimum ($min)" } check(max in loadRange) { "Maximum load ($max) must be between 0 and 100" } check(min in loadRange) { "Minimum load ($min) must be between 0 and 100" } check(toleranceMs > 0) { "Tolerance must be a positive number" } } }
apache-2.0
a127bf3caa222f30b86718a38e4bc338
32.333333
92
0.698373
3.665138
false
false
false
false
dkrivoruchko/ScreenStream
app/src/main/kotlin/info/dvkr/screenstream/service/ForegroundService.kt
1
9443
package info.dvkr.screenstream.service import android.annotation.SuppressLint import android.app.Service import android.content.Context import android.content.Intent import android.hardware.display.DisplayManager import android.os.Build import android.os.IBinder import android.view.Display import android.view.LayoutInflater import android.view.WindowManager import android.widget.Toast import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.ContextCompat import com.elvishew.xlog.XLog import info.dvkr.screenstream.R import info.dvkr.screenstream.common.AppError import info.dvkr.screenstream.common.AppStateMachine import info.dvkr.screenstream.common.getLog import info.dvkr.screenstream.common.settings.AppSettings import info.dvkr.screenstream.databinding.ToastSlowConnectionBinding import info.dvkr.screenstream.mjpeg.MjpegPublicState import info.dvkr.screenstream.mjpeg.settings.MjpegSettings import info.dvkr.screenstream.mjpeg.state.MjpegStateMachine import info.dvkr.screenstream.service.helper.IntentAction import info.dvkr.screenstream.service.helper.NotificationHelper import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import org.koin.android.ext.android.inject class ForegroundService : Service() { internal companion object { @JvmStatic @Volatile var isRunning: Boolean = false @JvmStatic fun getForegroundServiceIntent(context: Context): Intent = Intent(context, ForegroundService::class.java) @JvmStatic fun startForeground(context: Context, intent: Intent) { XLog.d(getLog("startForeground", intent.extras?.toString())) runCatching { ContextCompat.startForegroundService(context, intent) } .onFailure { XLog.e(getLog("startForeground", "Failed to start Foreground Service"), it) } } @JvmStatic fun startService(context: Context, intent: Intent) { XLog.d(getLog("startService", intent.extras?.toString())) runCatching { context.startService(intent) } .onFailure { XLog.e(getLog("startService", "Failed to start Service"), it) } } @JvmStatic private val serviceMessageSharedFlow = MutableSharedFlow<ServiceMessage>() @JvmStatic internal val serviceMessageFlow: SharedFlow<ServiceMessage> = serviceMessageSharedFlow.asSharedFlow() @JvmStatic internal suspend fun sendMessage(serviceMessage: ServiceMessage) = serviceMessageSharedFlow.emit(serviceMessage) } private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private val effectFlow = MutableSharedFlow<AppStateMachine.Effect>(extraBufferCapacity = 8) private val appSettings: AppSettings by inject() private val mjpegSettings: MjpegSettings by inject() private val notificationHelper: NotificationHelper by inject() private var appStateMachine: AppStateMachine? = null private var appErrorPrevious: AppError? = null override fun onBind(intent: Intent?): IBinder? = null override fun onCreate() { super.onCreate() XLog.d(getLog("onCreate")) notificationHelper.createNotificationChannel() notificationHelper.showForegroundNotification(this, NotificationHelper.NotificationType.START) effectFlow.onEach { effect -> if (effect !is AppStateMachine.Effect.Statistic) XLog.d([email protected]("onEffect", "Effect: $effect")) when (effect) { is AppStateMachine.Effect.ConnectionChanged -> Unit // TODO Notify user about restart reason is AppStateMachine.Effect.PublicState -> { if (effect is MjpegPublicState) { sendMessage( ServiceMessage.ServiceState( effect.isStreaming, effect.isBusy, effect.waitingForCastPermission, effect.netInterfaces, effect.appError ) ) val notificationType = if (effect.isStreaming) NotificationHelper.NotificationType.STOP else NotificationHelper.NotificationType.START notificationHelper.showForegroundNotification(this@ForegroundService, notificationType) onError(effect.appError) } } is AppStateMachine.Effect.Statistic -> { if (effect is AppStateMachine.Effect.Statistic.Clients) sendMessage(ServiceMessage.Clients(effect.clients)) if (effect is AppStateMachine.Effect.Statistic.Traffic) sendMessage(ServiceMessage.TrafficHistory(effect.traffic)) } } } .launchIn(coroutineScope) appStateMachine = MjpegStateMachine(this, appSettings, mjpegSettings, effectFlow, ::showSlowConnectionToast) isRunning = true } @Suppress("DEPRECATION") @SuppressLint("MissingPermission") override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val intentAction = IntentAction.fromIntent(intent) ?: return START_NOT_STICKY XLog.d(getLog("onStartCommand", "IntentAction: $intentAction")) when (intentAction) { IntentAction.GetServiceState -> { appStateMachine?.sendEvent(AppStateMachine.Event.RequestPublicState) } IntentAction.StartStream -> { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) sendBroadcast(Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) appStateMachine?.sendEvent(AppStateMachine.Event.StartStream) } IntentAction.StopStream -> { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) sendBroadcast(Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) appStateMachine?.sendEvent(AppStateMachine.Event.StopStream) } IntentAction.Exit -> { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) sendBroadcast(Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) notificationHelper.hideErrorNotification() stopForeground(true) coroutineScope.launch { sendMessage(ServiceMessage.FinishActivity) } [email protected]() } is IntentAction.CastIntent -> { appStateMachine?.sendEvent(AppStateMachine.Event.RequestPublicState) appStateMachine?.sendEvent(AppStateMachine.Event.StartProjection(intentAction.intent)) } IntentAction.CastPermissionsDenied -> { appStateMachine?.sendEvent(AppStateMachine.Event.CastPermissionsDenied) appStateMachine?.sendEvent(AppStateMachine.Event.RequestPublicState) } IntentAction.StartOnBoot -> appStateMachine?.sendEvent(AppStateMachine.Event.StartStream, 4500) IntentAction.RecoverError -> { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) sendBroadcast(Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) notificationHelper.hideErrorNotification() appStateMachine?.sendEvent(AppStateMachine.Event.RecoverError) } } return START_NOT_STICKY } override fun onDestroy() { XLog.d(getLog("onDestroy")) isRunning = false appStateMachine?.destroy() appStateMachine = null coroutineScope.cancel() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { stopForeground(STOP_FOREGROUND_REMOVE) } else { @Suppress("DEPRECATION") stopForeground(true) } XLog.d(getLog("onDestroy", "Done")) super.onDestroy() } private fun onError(appError: AppError?) { appErrorPrevious != appError || return appErrorPrevious = appError if (appError == null) { notificationHelper.hideErrorNotification() } else { XLog.e([email protected]("onError", "AppError: $appError")) notificationHelper.showErrorNotification(appError) } } @Suppress("DEPRECATION") private val windowContext: Context by lazy(LazyThreadSafetyMode.NONE) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { this } else { val display = ContextCompat.getSystemService(this, DisplayManager::class.java)!! .getDisplay(Display.DEFAULT_DISPLAY) this.createDisplayContext(display) .createWindowContext(WindowManager.LayoutParams.TYPE_TOAST, null) } } @Suppress("DEPRECATION") private fun showSlowConnectionToast() { coroutineScope.launch { val layoutInflater = ContextCompat.getSystemService(windowContext, LayoutInflater::class.java)!! val binding = ToastSlowConnectionBinding.inflate(layoutInflater) val drawable = AppCompatResources.getDrawable(windowContext, R.drawable.ic_notification_small_24dp) binding.ivToastSlowConnection.setImageDrawable(drawable) Toast(windowContext).apply { view = binding.root; duration = Toast.LENGTH_LONG }.show() } } }
mit
e34f4087737aaf2a6fdb264bc7ee0864
38.680672
137
0.663137
5.467863
false
false
false
false
GunoH/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/BaseLineStatusTrackerManagerTest.kt
5
4087
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs import com.intellij.diff.comparison.iterables.DiffIterableUtil import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.impl.UndoManagerImpl import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Document import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager import com.intellij.openapi.vcs.ex.* import com.intellij.openapi.vcs.impl.LineStatusTrackerManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.common.runAll import com.intellij.util.ui.UIUtil abstract class BaseLineStatusTrackerManagerTest : BaseChangeListsTest() { protected lateinit var shelveManager: ShelveChangesManager protected lateinit var lstm: LineStatusTrackerManager protected lateinit var undoManager: UndoManagerImpl override fun setUp() { super.setUp() DiffIterableUtil.setVerifyEnabled(true) lstm = LineStatusTrackerManager.getInstanceImpl(project) undoManager = UndoManager.getInstance(project) as UndoManagerImpl shelveManager = ShelveChangesManager.getInstance(project) } override fun tearDown() { runAll( { clm.waitUntilRefreshed() }, { UIUtil.dispatchAllInvocationEvents() }, { lstm.resetExcludedFromCommitMarkers() }, { lstm.releaseAllTrackers() }, { DiffIterableUtil.setVerifyEnabled(false) }, { super.tearDown() } ) } override fun resetSettings() { super.resetSettings() VcsApplicationSettings.getInstance().ENABLE_PARTIAL_CHANGELISTS = true VcsApplicationSettings.getInstance().SHOW_LST_GUTTER_MARKERS = true VcsApplicationSettings.getInstance().SHOW_WHITESPACES_IN_LST = true arePartialChangelistsSupported = true } protected fun releaseUnneededTrackers() { runWriteAction { } // LineStatusTrackerManager.MyApplicationListener.afterWriteActionFinished } protected val VirtualFile.tracker: LineStatusTracker<*>? get() = lstm.getLineStatusTracker(this) protected fun VirtualFile.withOpenedEditor(task: () -> Unit) { lstm.requestTrackerFor(document, this) try { task() } finally { lstm.releaseTrackerFor(document, this) } } protected open fun runCommand(groupId: String? = null, task: () -> Unit) { CommandProcessor.getInstance().executeCommand(project, { ApplicationManager.getApplication().runWriteAction(task) }, "", groupId) } protected fun undo(document: Document) { val editor = createMockFileEditor(document) undoManager.undo(editor) } protected fun redo(document: Document) { val editor = createMockFileEditor(document) undoManager.redo(editor) } protected fun PartialLocalLineStatusTracker.assertAffectedChangeLists(vararg expectedNames: String) { assertSameElements(this.getAffectedChangeListsIds().asListIdsToNames(), *expectedNames) } protected fun Range.assertChangeList(listName: String) { val localRange = this as LocalRange assertEquals(listName, localRange.changelistId.asListIdToName()) } protected fun VirtualFile.assertNullTracker() { val tracker = this.tracker if (tracker != null) { var message = "$tracker" + ": operational - ${tracker.isOperational()}" + ", valid - ${tracker.isValid()}, " + ", file - ${tracker.virtualFile}" if (tracker is PartialLocalLineStatusTracker) { message += ", hasPartialChanges - ${tracker.hasPartialChangesToCommit()}" + ", lists - ${tracker.getAffectedChangeListsIds().asListIdsToNames()}" } assertNull(message, tracker) } } protected fun PartialLocalLineStatusTracker.assertExcludedState(expected: ExclusionState, listName: String) { assertEquals(expected, getExcludedFromCommitState(listName.asListNameToId())) } }
apache-2.0
aa8013a9aa6d11287f858fb3d8f85e3a
35.491071
120
0.743088
5.014724
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantWithInspection.kt
1
5588
// 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.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.UnusedLambdaExpressionBodyInspection.Companion.replaceBlockExpressionWithLambdaBody import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class RedundantWithInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = callExpressionVisitor(fun(callExpression) { val callee = callExpression.calleeExpression ?: return if (callee.text != "with") return val valueArguments = callExpression.valueArguments if (valueArguments.size != 2) return val receiver = valueArguments[0].getArgumentExpression() ?: return val lambda = valueArguments[1].lambdaExpression() ?: return val lambdaBody = lambda.bodyExpression ?: return val context = callExpression.analyze(BodyResolveMode.PARTIAL_WITH_CFA) if (lambdaBody.statements.size > 1 && callExpression.isUsedAsExpression(context)) return if (callExpression.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe != FqName("kotlin.with")) return val lambdaDescriptor = context[BindingContext.FUNCTION, lambda.functionLiteral] ?: return var used = false lambda.functionLiteral.acceptChildren(object : KtVisitorVoid() { override fun visitKtElement(element: KtElement) { if (used) return element.acceptChildren(this) if (element is KtReturnExpression && element.getLabelName() == "with") { used = true return } if (isUsageOfDescriptor(lambdaDescriptor, element, context)) { used = true } } }) if (!used) { val quickfix = when (receiver) { is KtSimpleNameExpression, is KtStringTemplateExpression, is KtConstantExpression -> RemoveRedundantWithFix() else -> null } holder.registerProblem( callee, KotlinBundle.message("inspection.redundant.with.display.name"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, quickfix ) } }) } private fun KtValueArgument.lambdaExpression(): KtLambdaExpression? = (this as? KtLambdaArgument)?.getLambdaExpression() ?: this.getArgumentExpression() as? KtLambdaExpression private class RemoveRedundantWithFix : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.redundant.with.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val callExpression = descriptor.psiElement.parent as? KtCallExpression ?: return val lambdaExpression = callExpression.valueArguments.getOrNull(1)?.lambdaExpression() ?: return val lambdaBody = lambdaExpression.bodyExpression ?: return val declaration = callExpression.getStrictParentOfType<KtDeclarationWithBody>() val replaced = if (declaration?.equalsToken != null && KtPsiUtil.deparenthesize(declaration.bodyExpression) == callExpression) { val singleReturnedExpression = (lambdaBody.statements.singleOrNull() as? KtReturnExpression)?.returnedExpression if (singleReturnedExpression != null) { callExpression.replaced(singleReturnedExpression) } else { declaration.replaceBlockExpressionWithLambdaBody(lambdaBody) declaration.bodyExpression } } else { val result = lambdaBody.allChildren.takeUnless { it.isEmpty }?.let { range -> callExpression.parent.addRangeAfter(range.first, range.last, callExpression) } callExpression.delete() result } if (replaced != null) { replaced.findExistingEditor()?.moveCaret(replaced.startOffset) } } }
apache-2.0
729d8176077716c5ce85c3f126e8e94e
47.591304
158
0.695956
5.71955
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/build/output/KotlincOutputParser.kt
5
8173
// 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.build.output import com.intellij.build.FilePosition import com.intellij.build.events.BuildEvent import com.intellij.build.events.BuildEventsNls import com.intellij.build.events.MessageEvent import com.intellij.build.events.impl.FileMessageEventImpl import com.intellij.build.events.impl.MessageEventImpl import com.intellij.lang.LangBundle import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import org.jetbrains.annotations.Contract import org.jetbrains.annotations.NonNls import java.io.File import java.util.function.Consumer import java.util.regex.Matcher import java.util.regex.Pattern /** * Parses kotlinc's output. */ class KotlincOutputParser : BuildOutputParser { companion object { private val COMPILER_MESSAGES_GROUP: @BuildEventsNls.Title String @BuildEventsNls.Title get() = LangBundle.message("build.event.title.kotlin.compiler") } override fun parse(line: String, reader: BuildOutputInstantReader, consumer: Consumer<in BuildEvent>): Boolean { val colonIndex1 = line.colon() val severity = if (colonIndex1 >= 0) line.substringBeforeAndTrim(colonIndex1) else return false if (!severity.startsWithSeverityPrefix()) return false val lineWoSeverity = line.substringAfterAndTrim(colonIndex1) val colonIndex2 = lineWoSeverity.colon().skipDriveOnWin(lineWoSeverity) if (colonIndex2 < 0) return false val path = lineWoSeverity.substringBeforeAndTrim(colonIndex2) val file = File(path) val fileExtension = file.extension.toLowerCase() if (!file.isFile || (fileExtension != "kt" && fileExtension != "kts" && fileExtension != "java")) { //NON-NLS @NlsSafe val combinedMessage = lineWoSeverity.amendNextLinesIfNeeded(reader) return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), lineWoSeverity, combinedMessage), consumer) } val lineWoPath = lineWoSeverity.substringAfterAndTrim(colonIndex2) var lineWoPositionIndex = -1 var matcher: Matcher? = null if (lineWoPath.startsWith('(')) { val colonIndex3 = lineWoPath.colon() if (colonIndex3 >= 0) { lineWoPositionIndex = colonIndex3 } if (lineWoPositionIndex >= 0) { val position = lineWoPath.substringBeforeAndTrim(lineWoPositionIndex) matcher = KOTLIN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position) } } else { val colonIndex4 = lineWoPath.colon(1) if (colonIndex4 >= 0) { lineWoPositionIndex = colonIndex4 } else { lineWoPositionIndex = lineWoPath.colon() } if (lineWoPositionIndex >= 0) { val position = lineWoPath.substringBeforeAndTrim(colonIndex4) matcher = LINE_COLON_COLUMN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position) } } if (lineWoPositionIndex >= 0) { val relatedNextLines = "".amendNextLinesIfNeeded(reader) val message = lineWoPath.substringAfterAndTrim(lineWoPositionIndex) + relatedNextLines val details = line + relatedNextLines if (matcher != null && matcher.matches()) { val lineNumber = matcher.group(1) val symbolNumber = if (matcher.groupCount() >= 2) matcher.group(2) else "1" if (lineNumber != null) { val symbolNumberText = symbolNumber.toInt() return addMessage(createMessageWithLocation( reader.parentEventId, getMessageKind(severity), message, path, lineNumber.toInt(), symbolNumberText, details), consumer) } } return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), message, details), consumer) } else { @NlsSafe val combinedMessage = lineWoSeverity.amendNextLinesIfNeeded(reader) return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), lineWoSeverity, combinedMessage), consumer) } } private val COLON = ":" private val KOTLIN_POSITION_PATTERN = Pattern.compile("\\(([0-9]*), ([0-9]*)\\)") private val JAVAC_POSITION_PATTERN = Pattern.compile("([0-9]+)") private val LINE_COLON_COLUMN_POSITION_PATTERN = Pattern.compile("([0-9]*):([0-9]*)") private fun String.amendNextLinesIfNeeded(reader: BuildOutputInstantReader): String { var nextLine = reader.readLine() val builder = StringBuilder(this) while (nextLine != null) { if (nextLine.isNextMessage()) { reader.pushBack() break } else { builder.append("\n").append(nextLine) nextLine = reader.readLine() } } return builder.toString() } private fun String.isNextMessage(): Boolean { val colonIndex1 = indexOf(COLON) return colonIndex1 == 0 || (colonIndex1 >= 0 && substring(0, colonIndex1).startsWithSeverityPrefix()) // Next Kotlin message || StringUtil.startsWith(this, "Note: ") // Next javac info message candidate //NON-NLS || StringUtil.startsWith(this, "> Task :") // Next gradle message candidate //NON-NLS || StringUtil.containsIgnoreCase(this, "FAILURE") //NON-NLS || StringUtil.containsIgnoreCase(this, "FAILED") //NON-NLS } private fun String.startsWithSeverityPrefix() = getMessageKind(this) != MessageEvent.Kind.SIMPLE @NonNls private fun getMessageKind(kind: @NonNls String) = when (kind) { "e" -> MessageEvent.Kind.ERROR "w" -> MessageEvent.Kind.WARNING "i" -> MessageEvent.Kind.INFO "v" -> MessageEvent.Kind.SIMPLE else -> MessageEvent.Kind.SIMPLE } @Contract(pure = true) private fun String.substringAfterAndTrim(index: Int) = substring(index + 1).trim() @Contract(pure = true) private fun String.substringBeforeAndTrim(index: Int) = substring(0, index).trim() private fun String.colon() = indexOf(COLON) private fun String.colon(skip: Int): Int { var index = -1 repeat(skip + 1) { index = indexOf(COLON, index + 1) if (index < 0) return index } return index } private fun Int.skipDriveOnWin(line: String): Int { return if (this == 1) line.indexOf(COLON, this + 1) else this } private val KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT get() = // KaptError::class.java.canonicalName + ": " + KaptError.Kind.ERROR_RAISED.message "org.jetbrains.kotlin.kapt3.diagnostic.KaptError" + ": " + LangBundle.message("kapterror.error.while.annotation.processing") private fun isKaptErrorWhileAnnotationProcessing(message: MessageEvent): Boolean { if (message.kind != MessageEvent.Kind.ERROR) return false val messageText = message.message return messageText.startsWith(IllegalStateException::class.java.name) && messageText.contains(KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT) } private fun addMessage(message: MessageEvent, consumer: Consumer<in MessageEvent>): Boolean { // Ignore KaptError.ERROR_RAISED message from kapt. We already processed all errors from annotation processing if (isKaptErrorWhileAnnotationProcessing(message)) return true consumer.accept(message) return true } private fun createMessage(parentId: Any, messageKind: MessageEvent.Kind, text: @BuildEventsNls.Message String, detail: @BuildEventsNls.Description String): MessageEvent { return MessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail) //NON-NLS } private fun createMessageWithLocation( parentId: Any, messageKind: MessageEvent.Kind, text: @BuildEventsNls.Message String, file: String, lineNumber: Int, columnIndex: Int, detail: @BuildEventsNls.Description String ): FileMessageEventImpl { return FileMessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail, //NON-NLS FilePosition(File(file), lineNumber - 1, columnIndex - 1)) } }
apache-2.0
72977fcd823debbdf889ec9bff793fdd
39.068627
140
0.699621
4.651679
false
false
false
false
blan4/MangaReader
app/src/main/java/org/seniorsigan/mangareader/usecases/readmanga/ReadmangaMangaApiConverter.kt
1
3428
package org.seniorsigan.mangareader.usecases.readmanga import org.json.JSONArray import org.jsoup.Jsoup import org.seniorsigan.mangareader.models.ChapterItem import org.seniorsigan.mangareader.models.MangaItem import java.net.URI import java.util.regex.Pattern class ReadmangaMangaApiConverter { /** * Parses list of manga items such as search, popular, etc. */ fun parseList(data: String?, baseURL: String): List<MangaItem> { if (data == null) return emptyList() val doc = Jsoup.parse(data) val elements = doc.select(".tiles .tile") return elements.mapIndexed { i, el -> val img = el.select(".img img").first().attr("src") val title = el.select(".desc h3 a").first().text() val url = baseURL + el.select(".desc h3 a").first().attr("href") MangaItem(_id = i, coverURL = img, title = title, url = url) } } /** * Parses manga page and retrieve detailed info about manga */ fun parse(data: String?): MangaItem? { if (data == null) return null val doc = Jsoup.parse(data) val description = doc.select("#mangaBox > div[itemscope] > meta[itemprop=description]").first().attr("content") val title = doc.select("#mangaBox > div[itemscope] > meta[itemprop=name]").first().attr("content") val url = doc.select("#mangaBox > div[itemscope] > meta[itemprop=url]").first().attr("content") val images = doc.select(".picture-fotorama > img[itemprop=image]").map { it.attr("src") } return MangaItem( title = title, url = url, coverURL = images.firstOrNull(), description = description, coverURLS = images) } /** * Parses manga page and retrieve list of available chapters */ fun parseChapterList(html: String?, uri: URI): List<ChapterItem> { if (html == null) return emptyList() val doc = Jsoup.parse(html) val elements = doc.select(".table tbody tr td a") return elements.mapIndexed { i, el -> val title = el.text() val url = uri.resolve(el.attr("href")) ChapterItem(_id = i, title = title, url = url.toString()) } } /** * Parses chapter page and retrieve list of pages-images. */ fun parseChapter(html: String?): List<String> { if (html == null) return emptyList() val data = extract(html) ?: return emptyList() val pages = arrayListOf<Page>() with(JSONArray(data), { for (i in 0..length()-1) { val page = getJSONArray(i) pages.add(Page( host = page.getString(1), path = page.getString(0), item = page.getString(2) )) } }) return pages.map { it.uri } } private fun extract(html: String): String? { val regexp = "\\[\\[(.*?)\\]\\]" val pattern = Pattern.compile(regexp) val matcher = pattern.matcher(html) if (matcher.find()) { return matcher.group(0) } else { return null } } private data class Page( val host: String, val path: String, val item: String ) { val uri: String get() = "$host$path$item" } }
mit
4b2fbebc3a03cd49cf9d62c57a411f06
32.617647
119
0.552217
4.253102
false
false
false
false
jbmlaird/DiscogsBrowser
app/src/main/java/bj/vinylbrowser/model/common/BasicInformation.kt
1
1143
package bj.vinylbrowser.model.common import android.os.Parcel import android.os.Parcelable import bj.vinylbrowser.model.collection.Format import com.google.gson.annotations.SerializedName /** * Created by Josh Laird on 19/05/2017. */ data class BasicInformation(var formats: List<Format> = emptyList(), var thumb: String = "", var title: String = "", var labels: List<Label> = emptyList(), var year: String = "", var artists: List<Artist> = emptyList(), @SerializedName("resource_url") var resourceUrl: String = "", var id: String = "") : Parcelable { override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeList(formats) dest.writeString(thumb) dest.writeString(title) dest.writeList(labels) dest.writeString(year) dest.writeList(artists) dest.writeString(resourceUrl) dest.writeString(id) } override fun describeContents(): Int { return 0 } }
mit
c516d063ccec21152cb0f53a86a18077
32.647059
89
0.566929
4.926724
false
true
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/ErrorFormatter.kt
1
3690
package ch.rmy.android.http_shortcuts.utils import android.content.Context import androidx.annotation.StringRes import ch.rmy.android.framework.extensions.runIf import ch.rmy.android.framework.extensions.truncate import ch.rmy.android.framework.extensions.tryOrLog import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.exceptions.ResponseTooLargeException import ch.rmy.android.http_shortcuts.exceptions.UserException import ch.rmy.android.http_shortcuts.http.ErrorResponse import ch.rmy.android.http_shortcuts.http.HttpStatus import java.net.ConnectException import java.net.UnknownHostException import javax.inject.Inject class ErrorFormatter @Inject constructor( private val context: Context, ) { fun getPrettyError(error: Throwable, shortcutName: String, includeBody: Boolean = false): String = when (error) { is ErrorResponse -> { getHttpErrorMessage(error, shortcutName, includeBody) } is UserException -> { getErrorMessage(error) } else -> { String.format(getString(R.string.error_other), shortcutName, getErrorMessage(error)) } } private fun getHttpErrorMessage(error: ErrorResponse, shortcutName: String, includeBody: Boolean): String { val builder = StringBuilder() builder.append( String.format( getString(R.string.error_http), shortcutName, error.shortcutResponse.statusCode, HttpStatus.getMessage(error.shortcutResponse.statusCode), ) ) if (includeBody) { try { tryOrLog { val responseBody = error.shortcutResponse.getContentAsString(context) if (responseBody.isNotEmpty()) { builder.append("\n\n") builder.append(responseBody.truncate(MAX_ERROR_LENGTH)) } } } catch (e: ResponseTooLargeException) { builder.append("\n\n") builder.append(e.getLocalizedMessage(context)) } } return builder.toString() } private fun getErrorMessage(error: Throwable): String = when (error) { is UserException -> error.getLocalizedMessage(context) is ConnectException, is UnknownHostException, -> error.message!! else -> getUnknownErrorMessage(error) } private fun getUnknownErrorMessage(error: Throwable): String = getCauseChain(error) .let { if (it.size > 1 && it[0] is RuntimeException) { it.drop(1) } else { it } } .map(::getSingleErrorMessage) .distinct() .joinToString(separator = "\n") private fun getCauseChain(error: Throwable, recursionDepth: Int = 0): List<Throwable> = listOf(error) .runIf(error.cause != null && error.cause != error && recursionDepth < MAX_RECURSION_DEPTH) { plus(getCauseChain(error.cause!!, recursionDepth + 1)) } private fun getSingleErrorMessage(error: Throwable): String = when { error.message != null -> error.message!! else -> context.getString(R.string.error_generic) } private fun getString(@StringRes stringRes: Int): String = context.getString(stringRes) companion object { private const val MAX_RECURSION_DEPTH = 2 private const val MAX_ERROR_LENGTH = 10000 } }
mit
509071e5d138989f249cebe800ddbf28
34.480769
111
0.602981
4.95302
false
false
false
false
androman/BirthdayBook
app/src/main/java/ch/ybus/birthdaybook/service/ReminderReceiver.kt
1
1851
package ch.ybus.birthdaybook.service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import ch.ybus.birthdaybook.R import ch.ybus.birthdaybook.db.Database import ch.ybus.birthdaybook.db.RawContact import ch.ybus.birthdaybook.utils.DateUtils import ch.ybus.birthdaybook.utils.NotificationHelper import java.util.* class ReminderReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Log.i(TAG, "onReceive()") checkBirthdays(context) } private fun checkBirthdays(context: Context?) { if (context == null) { return } Log.d(TAG, "checkBirthdays()") val now = Date() val db = Database(context) val list = db.getTodaysBirthdays(now) for (contact in list) { sendNotification(context, contact, now.time) } } private fun sendNotification(context: Context, contact: RawContact, referenceTime: Long) { val tickerText: CharSequence? = contact.displayName val contentTitle: CharSequence = context.resources.getString( R.string.birthday_notification) val eventInfo = DateUtils.getEventInfo(contact.birthDate!!, referenceTime, 0) val contentText: CharSequence = context.resources.getString( R.string.birthday_notification_text, contact.displayName, Integer.valueOf(eventInfo.ageAtNextBirthday)) NotificationHelper.sendNotification( context, contact.photo, tickerText, contentTitle, contentText, System.currentTimeMillis().toInt() ) } companion object { // ---- Static private val TAG = ReminderReceiver::class.java.simpleName public val NOTIFICATION_CHANNEL = "birthday" } }
apache-2.0
356a576db0cb04f061b6b34f1d07feea
33.296296
94
0.683955
4.69797
false
false
false
false
neverwoodsS/StudyWithKotlin
src/workout/Test.kt
1
1379
package workout import java.io.File fun main() { // val string = """ // 请你务必审慎阅读、充分理解"救驾侠软件许可及服务协议"各条款,包括但不限于:为了向你提供紧急救援等服务,我们需要收集你的设备信息、操作日志等个人信息。 // 你可以阅读《救驾侠软件许可及服务协议》了解详细信息。如你同意,请点击"同意"开始接受我们的服务。 // """.trimIndent() // // println(string.indexOf("》")) var fileName = "/Users/zhangll/Library" val children = File(fileName).listFiles() val start = System.nanoTime() val total = children.map { if (it.name.contains("Containers")) return@map 0L val size = getTotalSizeOfFilesInDir(it) if (size > 1000 * 1000 * 100) println("${it.name} size: ${size.toFloat() / 1000 / 1000} MB") size }.sum() val end = System.nanoTime() println("Total Size: ${total / 1000 / 1000} MB") println("Time taken: " + (end - start) / 1.0e9) } // 递归方式 计算文件的大小 private fun getTotalSizeOfFilesInDir(file: File): Long { if (file.isFile) return file.length() val children = file.listFiles() var total: Long = 0 if (children != null) for (child in children) total += getTotalSizeOfFilesInDir(child) return total }
mit
3019e6bafc67d775cb7d51589ae9fe74
24.409091
90
0.623993
2.916449
false
false
false
false
kerubistan/kerub
src/main/kotlin/com/github/kerubistan/kerub/services/socket/ChannelSubscription.kt
2
873
package com.github.kerubistan.kerub.services.socket import com.github.kerubistan.kerub.model.Entity import com.github.kerubistan.kerub.model.messages.EntityMessage import io.github.kerubistan.kroki.strings.toUUID import kotlin.reflect.KClass data class ChannelSubscription(val entityClass: KClass<out Entity<out Any>>, val id: Any?) { companion object { fun fromChannel(channel: String): ChannelSubscription { val channelFormatted = addSlashPrefix(addSlashPostFix(channel)) val split = channelFormatted.split(slash).filter { it.isNotBlank() } val entityServiceAddress = addSlashPrefix(addSlashPostFix(split[0])) val entityId = split.elementAtOrNull(1)?.toUUID() return ChannelSubscription(requireNotNull(addressToEntity[entityServiceAddress]), entityId) } } fun interested(msg: EntityMessage): Boolean { return id == null || msg.obj.id == id } }
apache-2.0
0293b723b615ff87172414c0374d92d7
38.727273
94
0.783505
3.914798
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/ticket/TicketViewHolder.kt
1
8849
package org.fossasia.openevent.general.ticket import android.graphics.Paint import android.text.Editable import android.text.TextWatcher import android.text.Html import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.item_ticket.view.order import kotlinx.android.synthetic.main.item_ticket.view.orderRange import kotlinx.android.synthetic.main.item_ticket.view.price import kotlinx.android.synthetic.main.item_ticket.view.ticketName import kotlinx.android.synthetic.main.item_ticket.view.discountPrice import kotlinx.android.synthetic.main.item_ticket.view.donationInput import kotlinx.android.synthetic.main.item_ticket.view.orderQtySection import kotlinx.android.synthetic.main.item_ticket.view.priceSection import org.fossasia.openevent.general.R import org.fossasia.openevent.general.data.Resource import kotlinx.android.synthetic.main.item_ticket.view.priceInfo import kotlinx.android.synthetic.main.item_ticket.view.moreInfoSection import kotlinx.android.synthetic.main.item_ticket.view.seeMoreInfoText import kotlinx.android.synthetic.main.item_ticket.view.ticketDateText import kotlinx.android.synthetic.main.item_ticket.view.saleInfo import kotlinx.android.synthetic.main.item_ticket.view.description import org.fossasia.openevent.general.discount.DiscountCode import org.fossasia.openevent.general.event.EventUtils import org.fossasia.openevent.general.event.EventUtils.getFormattedDate import org.threeten.bp.DateTimeUtils import java.util.Date import kotlin.collections.ArrayList const val AMOUNT = "amount" const val TICKET_TYPE_FREE = "free" const val TICKET_TYPE_PAID = "paid" const val TICKET_TYPE_DONATION = "donation" class TicketViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val resource = Resource() fun bind( ticket: Ticket, selectedListener: TicketSelectedListener?, eventCurrency: String?, eventTimeZone: String?, ticketQuantity: Int, donationAmount: Float, discountCode: DiscountCode? = null ) { itemView.ticketName.text = ticket.name setupTicketSaleDate(ticket, eventTimeZone) setMoreInfoText() itemView.seeMoreInfoText.setOnClickListener { itemView.moreInfoSection.isVisible = !itemView.moreInfoSection.isVisible setMoreInfoText() } var minQty = ticket.minOrder var maxQty = ticket.maxOrder if (discountCode?.minQuantity != null) minQty = discountCode.minQuantity if (discountCode?.maxQuantity != null) maxQty = discountCode.maxQuantity if (discountCode == null) { minQty = ticket.minOrder maxQty = ticket.maxOrder itemView.discountPrice.visibility = View.GONE itemView.price.paintFlags = 0 } itemView.order.setOnClickListener { itemView.orderRange.performClick() } when (ticket.type) { TICKET_TYPE_DONATION -> { itemView.price.text = resource.getString(R.string.donation) itemView.priceSection.isVisible = false itemView.donationInput.isVisible = true if (donationAmount > 0F) itemView.donationInput.setText(donationAmount.toString()) setupDonationTicketPicker() } TICKET_TYPE_FREE -> { itemView.price.text = resource.getString(R.string.free) itemView.priceSection.isVisible = true itemView.donationInput.isVisible = false } TICKET_TYPE_PAID -> { itemView.price.text = "$eventCurrency${"%.2f".format(ticket.price)}" itemView.priceSection.isVisible = true itemView.donationInput.isVisible = false } } setupQtyPicker(minQty, maxQty, selectedListener, ticket, ticketQuantity) val priceInfo = "<b>${resource.getString(R.string.price)}:</b> ${itemView.price.text}" itemView.priceInfo.text = Html.fromHtml(priceInfo) if (ticket.description.isNullOrEmpty()) { itemView.description.isVisible = false } else { itemView.description.isVisible = true itemView.description.text = ticket.description } if (discountCode?.value != null && ticket.price != 0.toFloat()) { itemView.discountPrice.visibility = View.VISIBLE itemView.price.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG itemView.discountPrice.text = if (discountCode.type == AMOUNT) "$eventCurrency${ticket.price - discountCode.value}" else "$eventCurrency${"%.2f".format(ticket.price - (ticket.price * discountCode.value / 100))}" } } private fun setupDonationTicketPicker() { itemView.donationInput.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { /*Do Nothing*/ } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { /*Do Nothing*/ } override fun afterTextChanged(s: Editable?) { val donationEntered = s.toString() if (donationEntered.isNotBlank() && donationEntered.toFloat() > 0) { if (itemView.orderRange.selectedItemPosition == 0) itemView.orderRange.setSelection(1) } else { itemView.orderRange.setSelection(0) } } }) } private fun setupQtyPicker( minQty: Int, maxQty: Int, selectedListener: TicketSelectedListener?, ticket: Ticket, ticketQuantity: Int ) { if (minQty > 0 && maxQty > 0) { val spinnerList = ArrayList<String>() spinnerList.add("0") for (i in minQty..maxQty) { spinnerList.add(i.toString()) } itemView.orderRange.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) { val donationEntered = itemView.donationInput.text.toString() val donation = if (donationEntered.isEmpty()) 0F else donationEntered.toFloat() itemView.order.text = spinnerList[pos] selectedListener?.onSelected(ticket.id, spinnerList[pos].toInt(), donation) } override fun onNothingSelected(parent: AdapterView<*>) { } } itemView.orderRange.adapter = ArrayAdapter(itemView.context, android.R.layout.select_dialog_singlechoice, spinnerList) val currentQuantityPosition = spinnerList.indexOf(ticketQuantity.toString()) if (currentQuantityPosition != -1) { itemView.orderRange.setSelection(currentQuantityPosition) itemView.order.text = ticketQuantity.toString() } } } private fun setMoreInfoText() { itemView.seeMoreInfoText.text = resource.getString( if (itemView.moreInfoSection.isVisible) R.string.see_less else R.string.see_more) } private fun setupTicketSaleDate(ticket: Ticket, timeZone: String?) { val startAt = ticket.salesStartsAt val endAt = ticket.salesEndsAt if (startAt != null && endAt != null && timeZone != null) { val startsAt = EventUtils.getEventDateTime(startAt, timeZone) val endsAt = EventUtils.getEventDateTime(endAt, timeZone) val startDate = DateTimeUtils.toDate(startsAt.toInstant()) val endDate = DateTimeUtils.toDate(endsAt.toInstant()) val currentDate = Date() if (currentDate < startDate) { itemView.ticketDateText.isVisible = true itemView.ticketDateText.text = resource.getString(R.string.not_open) itemView.orderQtySection.isVisible = false } else if (startDate < currentDate && currentDate < endDate) { itemView.ticketDateText.isVisible = false itemView.orderQtySection.isVisible = true } else { itemView.ticketDateText.text = resource.getString(R.string.ended) itemView.ticketDateText.isVisible = true itemView.orderQtySection.isVisible = false } val salesEnd = "<b>${resource.getString(R.string.sales_end)}</b> ${getFormattedDate(endsAt)}" itemView.saleInfo.text = Html.fromHtml(salesEnd) } } }
apache-2.0
7554ea39f1fb62bbfbec22b1b26e2fbd
43.024876
117
0.652164
4.798807
false
false
false
false
ognev-zair/Kotlin-AgendaCalendarView
kotlin-agendacalendarview/src/main/java/com/ognev/kotlin/agendacalendarview/models/DayItem.kt
1
1734
package com.ognev.kotlin.agendacalendarview.models import com.ognev.kotlin.agendacalendarview.CalendarManager import com.ognev.kotlin.agendacalendarview.utils.DateHelper import java.util.Calendar import java.util.Date /** * Day model class. */ class DayItem // region Constructor ( // endregion // region Getters/Setters override var date: Date, override var value: Int, override var isToday: Boolean, override var month: String) : IDayItem { override var dayOftheWeek: Int = 0 override var isFirstDayOfTheMonth: Boolean = false override var isSelected: Boolean = false private var hasEvents: Boolean = false override fun setHasEvents(hasEvents: Boolean) { this.hasEvents = hasEvents } override fun hasEvents(): Boolean { return hasEvents } // endregion override fun toString(): String { return "DayItem{" .plus("Date='") .plus(date!!.toString()) .plus(", value=") .plus(value) .plus('}') } companion object { // region Public methods fun buildDayItemFromCal(calendar: Calendar): DayItem { val date = calendar.getTime() val isToday = DateHelper.sameDate(calendar, CalendarManager.instance!!.today) val value = calendar.get(Calendar.DAY_OF_MONTH) val dayItem = DayItem(date, value, isToday, CalendarManager.instance!!.monthHalfNameFormat!!.format(date)) if (value == 1) { dayItem.isFirstDayOfTheMonth = true } dayItem.isToday = isToday return dayItem } } // endregion }
apache-2.0
cf8c7c06605f91cfd789ca27581861db
24.5
118
0.607843
4.624
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/browser/Scripts.kt
1
1132
/* * Copyright (C) 2017-2018 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.browser object Scripts { const val GET_ICON_URL = "(function(){for(var e=document.getElementsByTagName(\"link\"),r=[],l=0;l<e.length;l++){" + "var n=e[l].rel;\"apple-touch-icon-precomposed\"!=n&&\"apple-touch-icon\"!=n||r.push(e[l])}" + "if(0==r.length)return\"\";for(var t=-1,u=-1,a=null,l=0;l<r.length;l++){var o=r[l].sizes[0];" + "if(null==o)a=r[l];else{var h=Number(o[0].match(/\\d+/));h>u&&(t=l,u=h)}}return-1==t?null==a?\"\":a.href:r[t].href}())" }
apache-2.0
657347ceda4b0a6bab894c00f40e80f0
46.208333
131
0.655477
3.067751
false
false
false
false
seventhroot/elysium
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/undirected/UndirectedFormatComponent.kt
1
4276
/* * Copyright 2020 Ren Binden * * 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.rpkit.chat.bukkit.chatchannel.undirected import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatchannel.pipeline.UndirectedChatChannelPipelineComponent import com.rpkit.chat.bukkit.context.UndirectedChatChannelMessageContext import com.rpkit.chat.bukkit.prefix.RPKPrefixProvider import com.rpkit.core.bukkit.util.closestChatColor import com.rpkit.players.bukkit.profile.RPKProfile import org.bukkit.Bukkit import org.bukkit.ChatColor import org.bukkit.configuration.serialization.ConfigurationSerializable import org.bukkit.configuration.serialization.SerializableAs @SerializableAs("UndirectedFormatComponent") class UndirectedFormatComponent(private val plugin: RPKChatBukkit, var formatString: String): UndirectedChatChannelPipelineComponent, ConfigurationSerializable { override fun process(context: UndirectedChatChannelMessageContext): UndirectedChatChannelMessageContext { val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val prefixProvider = plugin.core.serviceManager.getServiceProvider(RPKPrefixProvider::class) val senderMinecraftProfile = context.senderMinecraftProfile val senderProfile = context.senderProfile val senderCharacter = if (senderMinecraftProfile != null) characterProvider.getActiveCharacter(senderMinecraftProfile) else null val chatChannel = context.chatChannel var formattedMessage = ChatColor.translateAlternateColorCodes('&', formatString) if (formattedMessage.contains("\$message")) { formattedMessage = formattedMessage.replace("\$message", context.message) } if (formattedMessage.contains("\$sender-prefix")) { formattedMessage = if (senderProfile is RPKProfile) { formattedMessage.replace("\$sender-prefix", prefixProvider.getPrefix(senderProfile)) } else { formattedMessage.replace("\$sender-prefix", "") } } if (formattedMessage.contains("\$sender-player")) { formattedMessage = formattedMessage.replace("\$sender-player", senderProfile.name) } if (formattedMessage.contains("\$sender-character")) { if (senderCharacter != null) { formattedMessage = formattedMessage.replace("\$sender-character", if (senderCharacter.isNameHidden) "(HIDDEN ${senderCharacter.name.hashCode()})" else senderCharacter.name) } else { context.isCancelled = true } } if (formattedMessage.contains("\$channel")) { formattedMessage = formattedMessage.replace("\$channel", chatChannel.name) } if (formattedMessage.contains("\$color") || formattedMessage.contains("\$colour")) { val chatColorString = chatChannel.color.closestChatColor().toString() formattedMessage = formattedMessage.replace("\$color", chatColorString).replace("\$colour", chatColorString) } context.message = formattedMessage return context } override fun serialize(): MutableMap<String, Any> { return mutableMapOf( Pair("format", formatString) ) } companion object { @JvmStatic fun deserialize(serialized: MutableMap<String, Any>): UndirectedFormatComponent { return UndirectedFormatComponent( Bukkit.getPluginManager().getPlugin("rpk-chat-bukkit") as RPKChatBukkit, serialized["format"] as String ) } } }
apache-2.0
80cb7b1dc6f638400c45c73e3dccf206
45.48913
188
0.706034
5.496144
false
false
false
false
drmaas/ratpack-kotlin
ratpack-kotlin-dsl/src/test/kotlin/ratpack/kotlin/handling/KHandlerTest.kt
1
1272
package ratpack.kotlin.handling import io.kotest.core.spec.style.BehaviorSpec import io.kotest.matchers.shouldBe import ratpack.kotlin.test.testHttpClient class KHandlerTest: BehaviorSpec() { init { // test handler with a class given("a ratpack server") { val app = ratpack.kotlin.test.embed.ratpack { bindings { add(MyKHandler()) } handlers { get<MyKHandler>("class") get("instance", MyKHandler2()) } } `when`("a request is made to a class handler") { val client = testHttpClient(app) val r = client.get("class") then("it works") { r.statusCode shouldBe 200 r.body.text shouldBe "hello" app.close() } } `when`("a request is made to an instance handler") { val client = testHttpClient(app) val r = client.get("instance") then("it works") { r.statusCode shouldBe 200 r.body.text shouldBe "hello" app.close() } } } } } class MyKHandler: KHandler { override suspend fun handle(ctx: KContext) { ctx.render("hello") } } class MyKHandler2: KHandler { override suspend fun handle(ctx: KContext) { ctx.render("hello") } }
apache-2.0
1608037d8c29de70fb1615ec1be64207
23.461538
58
0.584119
4
false
true
false
false
bropane/Job-Seer
app/src/main/java/com/taylorsloan/jobseer/view/jobdetail/JobDetailActivity.kt
1
7686
package com.taylorsloan.jobseer.view.jobdetail import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.design.widget.AppBarLayout import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.squareup.picasso.Picasso import com.taylorsloan.jobseer.R import com.taylorsloan.jobseer.domain.job.models.Job import com.taylorsloan.jobseer.view.util.RoundedCornersTransformation import kotlinx.android.synthetic.main.activity_job_detail.* class JobDetailActivity : AppCompatActivity(), JobDetailContract.View, AppBarLayout.OnOffsetChangedListener { companion object { private const val KEY_JOB_ID = "jobId" private const val PERCENTAGE_TO_ANIMATE_AVATAR = 20 fun startActivity(context: Context, jobId: String){ val intent = Intent(context, JobDetailActivity::class.java) intent.putExtra(KEY_JOB_ID, jobId) context.startActivity(intent) } } private lateinit var jobId : String private lateinit var presenter : JobDetailContract.Presenter private var saveMenuItem : MenuItem? = null private var maxScrollSize = 0 private var isAvatarShown = true private var googleMap : GoogleMap? = null private var isSaved = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_job_detail) jobId = getJobIdFromIntent() presenter = JobDetailPresenter(this, jobId) mapView.onCreate(savedInstanceState) setupViews() setupInteractions() } override fun onDestroy() { super.onDestroy() mapView.onDestroy() } private fun setupViews(){ setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowTitleEnabled(false) appBarLayout.addOnOffsetChangedListener(this) maxScrollSize = appBarLayout.totalScrollRange mapView.getMapAsync { initMap(it) } view_mapBlock.setOnTouchListener { _, _ -> true } // Ignore All Touch Events on mapToNet view } private fun setupInteractions(){ fab.setOnClickListener { view -> Snackbar.make(view, R.string.activity_job_detail_open_website, Snackbar.LENGTH_LONG) .setAction(R.string.activity_job_detail_open, { presenter.openApplicationPage()}).show() } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_job_detail, menu) saveMenuItem = menu?.findItem(R.id.action_save) if (isSaved) { showSaved() } else { showUnsaved() } return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { return when(item?.itemId){ R.id.action_save ->{ if (isSaved) { presenter.unsaveJob() } else { presenter.saveJob() } true } R.id.action_share -> { presenter.openShareJobDialog() true } else->{ super.onOptionsItemSelected(item) } } } private fun initMap(map: GoogleMap){ googleMap = map } private fun getJobIdFromIntent() : String{ return intent.getStringExtra(KEY_JOB_ID) } override fun onSaveInstanceState(outState: Bundle?) { outState?.putString(KEY_JOB_ID, jobId) super.onSaveInstanceState(outState) } override fun onRestoreInstanceState(savedInstanceState: Bundle?) { super.onRestoreInstanceState(savedInstanceState) jobId = savedInstanceState?.getString(KEY_JOB_ID) ?: "" } override fun showJob(job: Job) { textView_jobName.text = job.title textView_companyName.text = job.company textView_location.text = job.location Picasso.with(this).load(job.company_logo) .transform(RoundedCornersTransformation(10, 0)) .fit() .centerInside() .into(imageView_companyIcon) html_text.setHtml(job.description ?: "") if (job.saved == true) { showSaved() } else { showUnsaved() } } override fun onStart() { super.onStart() mapView.onStart() } override fun onStop() { super.onStop() mapView.onStop() } override fun onLowMemory() { super.onLowMemory() mapView.onLowMemory() } override fun onResume() { super.onResume() presenter.subscribe() mapView.onResume() } override fun onPause() { super.onPause() presenter.unsubscribe() mapView.onPause() } override fun showCompanyWebPage(url: String) { val uri = Uri.parse(Uri.decode(url)) val intent = Intent(Intent.ACTION_VIEW) intent.data = uri startActivity(intent) } override fun showCompanyWebPageLoadError() { Toast.makeText(this, R.string.activity_job_detail_url_error, Toast.LENGTH_SHORT).show() } override fun showLocation(location: Pair<Double, Double>) { frameLayout_map.visibility = View.VISIBLE frameLayout_remote.visibility = View.GONE val marker = LatLng(location.first, location.second) googleMap?.addMarker(MarkerOptions().position(marker)) googleMap?.moveCamera(CameraUpdateFactory.newLatLng(marker)) googleMap?.moveCamera(CameraUpdateFactory.zoomTo(10.0f)) } override fun showRemoteLocation() { frameLayout_map.visibility = View.GONE frameLayout_remote.visibility = View.VISIBLE } override fun showShareJobDialog(company: String, position: String, link: String) { val intent = Intent(Intent.ACTION_SEND) intent.putExtra(Intent.EXTRA_TEXT, "Hey, check out this job for a " + "$position at $company. Apply Here: $link") intent.type = "text/plain" startActivity(Intent.createChooser(intent, resources .getText(R.string.activity_job_detail_share))) } override fun showSaved() { isSaved = true saveMenuItem?.setIcon(R.drawable.ic_star) } override fun showUnsaved() { isSaved = false saveMenuItem?.setIcon(R.drawable.ic_star_border) } override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) { if (maxScrollSize == 0) maxScrollSize = appBarLayout?.totalScrollRange ?: 0 val percentage = Math.abs(verticalOffset) * 100 / maxScrollSize if (percentage >= PERCENTAGE_TO_ANIMATE_AVATAR && isAvatarShown) { isAvatarShown = false imageView_companyIcon.animate() .scaleY(0f).scaleX(0f) .setDuration(200) .start() } if (percentage <= PERCENTAGE_TO_ANIMATE_AVATAR && !isAvatarShown) { isAvatarShown = true imageView_companyIcon.animate() .scaleY(1f).scaleX(1f) .start() } } }
mit
1f41a24a8950af4af368d5330cd99320
30.371429
108
0.63401
4.756188
false
false
false
false
wiryls/HomeworkCollectionOfMYLS
2017.AndroidApplicationDevelopment/Rehtaew/app/src/main/java/com/myls/rehtaew/adapter/ForecastRecyclerAdapter.kt
1
1794
package com.myls.rehtaew.adapter import android.content.Context import android.media.Image import android.support.v7.widget.RecyclerView import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.myls.rehtaew.R import com.myls.rehtaew.data.WeatherData import com.myls.rehtaew.utility.Extension.inflate /** * Created by myls on 11/10/17. */ class ForecastRecyclerAdapter(private val items: ArrayList<WeatherData.Forecast>) : RecyclerView.Adapter<ForecastRecyclerAdapter.ViewHolder>() { override fun getItemCount() = items.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(parent.inflate(R.layout.item_main)) override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder) { items[position].let { date.text = it.date week.text = it.weekday icon.setImageDrawable(icon.context.getDrawable(it.weatherIconId)) tmph.text = it.temperatureHigh tmpl.text = it.temperatureLow } } } class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) { val date = (view.findViewById(R.id.date_text_main) as TextView) val week = (view.findViewById(R.id.week_text_main) as TextView) val icon = (view.findViewById(R.id.forcast_image_main) as ImageView) val tmph = (view.findViewById(R.id.temphigh_text_main) as TextView) val tmpl = (view.findViewById(R.id.templow_text_main) as TextView) } companion object { val TAG = this::class.java.name } } // [How to build a Horizontal ListView with RecyclerView?] // (https://stackoverflow.com/a/28460399)
mit
50ef491e8dc575bdda0b4f5da7c9e38d
32.240741
81
0.692308
3.942857
false
false
false
false
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/components/InAppMessage.kt
1
2379
package com.github.premnirmal.ticker.components import android.app.Activity import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import com.github.premnirmal.tickerwidget.R import com.google.android.material.snackbar.Snackbar /** * Created by premnirmal on 2/26/16. */ object InAppMessage { private fun Activity.getRootView(): View = (this.findViewById<View>(android.R.id.content) as ViewGroup).getChildAt(0) fun showToast(context: Context, messageResId: Int) { Toast.makeText(context, messageResId, Toast.LENGTH_SHORT) .show() } fun showToast(context: Context, message: CharSequence) { Toast.makeText(context, message, Toast.LENGTH_SHORT) .show() } fun showMessage(activity: Activity, messageResId: Int, error: Boolean = false) { showMessage(activity, activity.getString(messageResId), error) } fun showMessage(view: View, messageResId: Int, error: Boolean = false) { showMessage(view, view.resources.getString(messageResId), error) } fun showMessage(activity: Activity, message: CharSequence, error: Boolean = false) { val snackbar = createSnackbar(activity.getRootView(), message, error) snackbar.show() } fun showMessage(view: View, message: String, error: Boolean) { val snackbar = createSnackbar(view, message, error) snackbar.show() } private fun createSnackbar(view: View, message: CharSequence, error: Boolean = false): Snackbar { val snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG) val snackBarView = snackbar.view val params = snackBarView.layoutParams as ViewGroup.MarginLayoutParams val margin = snackBarView.context.resources.getDimensionPixelSize(R.dimen.snackbar_margin) params.setMargins(margin, margin, margin, margin) snackBarView.layoutParams = params if (error) { val bg = R.drawable.snackbar_bg_error snackBarView.background = ResourcesCompat.getDrawable(view.context.resources, bg, null) val text = snackBarView.findViewById<TextView>(com.google.android.material.R.id.snackbar_text) text.setTextColor(ContextCompat.getColor(view.context, R.color.white)) } return snackbar } }
gpl-3.0
367f7de527d363e89ebeb2c93eefdc73
35.060606
100
0.739807
4.255814
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/locus/api/mapper/PointMerger.kt
1
4761
package locus.api.mapper import com.arcao.geocaching4locus.settings.manager.DefaultPreferenceManager import locus.api.mapper.Util.GSAK_USERNAME import locus.api.mapper.Util.applyUnavailabilityForGeocache import locus.api.objects.geoData.Point import locus.api.objects.geocaching.GeocachingLog class PointMerger( private val defaultPreferenceManager: DefaultPreferenceManager ) { fun mergePoints(dest: Point, src: Point?) { dest.removeExtraOnDisplay() val srcGcData = src?.gcData ?: return val destGcData = dest.gcData ?: return copyArchivedGeocacheLocation(dest, src) copyGsakGeocachingLogs(destGcData.logs, srcGcData.logs) copyComputedCoordinates(dest, src) copyPointId(dest, src) copyGcVote(dest, src) copyEditedGeocachingWaypointLocation(dest, src) // only when this feature is enabled if (defaultPreferenceManager.disableDnfNmNaGeocaches) { applyUnavailabilityForGeocache(dest, defaultPreferenceManager.disableDnfNmNaGeocachesThreshold) } } fun mergeGeocachingLogs(dest: Point?, src: Point?) { if (dest == null || src?.gcData == null) return // store original logs val originalLogs = ArrayList(dest.gcData?.logs.orEmpty()) // replace logs with new one dest.gcData?.logs?.apply { clear() src.gcData?.logs?.let(this::addAll) } // copy GSAK logs from original logs copyGsakGeocachingLogs(dest.gcData?.logs, originalLogs) } // issue #14: Keep cache logs from GSAK when updating cache private fun copyGsakGeocachingLogs( dest: MutableList<GeocachingLog>?, src: List<GeocachingLog>? ) { src ?: return dest ?: return for (fromLog in src.reversed()) { if (GSAK_USERNAME.equals(fromLog.finder, ignoreCase = true)) { fromLog.date = System.currentTimeMillis() dest.add(0, fromLog) } } } // issue #13: Use old coordinates when cache is archived after update private fun copyArchivedGeocacheLocation(dest: Point, src: Point) { val srcGcData = src.gcData ?: return val destGcData = dest.gcData ?: return val latitude = src.location.latitude val longitude = src.location.longitude // are valid coordinates if (latitude.isNaN() || longitude.isNaN() || latitude == 0.0 && longitude == 0.0) return // is new point not archived or has computed coordinates if (!destGcData.isArchived || srcGcData.isComputed) return // store coordinates to new point dest.location.apply { this.latitude = latitude this.longitude = longitude } } // Copy computed coordinates to new point private fun copyComputedCoordinates(dest: Point, src: Point) { val srcGcData = src.gcData ?: return val destGcData = dest.gcData ?: return if (!srcGcData.isComputed || destGcData.isComputed) return val location = dest.location destGcData.apply { latOriginal = location.latitude lonOriginal = location.longitude isComputed = true } // update coordinates to new location location.set(src.location) } private fun copyPointId(dest: Point, src: Point) { if (src.id == 0L) return dest.id = src.id } private fun copyGcVote(dest: Point, src: Point) { val srcGcData = src.gcData ?: return val destGcData = dest.gcData ?: return destGcData.apply { gcVoteAverage = srcGcData.gcVoteAverage gcVoteNumOfVotes = srcGcData.gcVoteNumOfVotes gcVoteUserVote = srcGcData.gcVoteUserVote } } private fun copyEditedGeocachingWaypointLocation(dest: Point, src: Point) { val destWaypoints = dest.gcData?.waypoints ?: return val srcWaypoints = src.gcData?.waypoints ?: return if (destWaypoints.isEmpty() || srcWaypoints.isEmpty()) return // find Waypoint with zero coordinates for (waypoint in destWaypoints) { if (waypoint.lat == 0.0 && waypoint.lon == 0.0) { // replace with coordinates from src Waypoint for (fromWaypoint in srcWaypoints) { if (waypoint.code.equals(fromWaypoint.code, ignoreCase = true)) { waypoint.apply { lat = fromWaypoint.lat lon = fromWaypoint.lon } } } } } } }
gpl-3.0
71ed0f06d41ca2b85d9bda7f7867a5e3
30.95302
107
0.607015
4.695266
false
false
false
false
avkviring/reakt
reakt/src/main/kotlin/com/github/andrewoma/react/Component.kt
1
1620
package com.github.andrewoma.react /** * A trait to allow rendering of React components using the Component builders */ interface ComponentRenderer<P:Any> { @Suppress("UNCHECKED_CAST") fun render(): ReactElement<P>? { // This bit of trickery makes root an instance of Component so that the scoped render method is visible val root = object : Component({ 0 }) {} root.render() check(root.children.size <= 1, "React only supports one (or zero) root components") // Can't check instance type when native // check(root.children[0] is ReactComponent<*, *>, "Root must be a Component or null") if (root.children.isEmpty()) return null return root.children[0].transform() as ReactElement<P>? } // Stolen from Kara. This allows a component to create an extension function to Component // that is scoped to this component fun Component.render() } /** * The standard base class for Kotlin components that use the Component builder */ abstract class ComponentSpec<S : Any, P : Any> : ReactComponentSpec<S, P>(), ComponentRenderer<S> /** * The base Component type */ open class Component(val transformer: (Component) -> Any) { val children: MutableList<Component> = ArrayList() fun constructAndInsert(component: Component, init: Component.() -> Unit = {}): Component { component.init() children.add(component) return component } fun transform(): Any { return transformer(this) } fun transformChildren(): Array<Any?> = Array(children.size, { children[it].transform() }) }
mit
49823edc4c270cccda8b753b763b3e7c
32.061224
111
0.667284
4.378378
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/broker/BrokerStockInfoExecutor.kt
1
6989
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.broker import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.discordinteraktions.common.utils.field import net.perfectdreams.loritta.cinnamon.emotes.Emotes import net.perfectdreams.loritta.common.utils.LorittaBovespaBrokerUtils import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.broker.BrokerExecutorUtils.brokerBaseEmbed import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.BrokerCommand import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions class BrokerStockInfoExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) { inner class Options : LocalizedApplicationCommandOptions(loritta) { val ticker = string("ticker", BrokerCommand.I18N_PREFIX.Stock.Options.Ticker.Text) { LorittaBovespaBrokerUtils.trackedTickerCodes.map { Pair(it.ticker, it.name) }.forEach { (tickerId, tickerTitle) -> choice("$tickerTitle ($tickerId)", tickerId.lowercase()) } } } override val options = Options() override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { context.deferChannelMessageEphemerally() val tickerId = args[options.ticker].uppercase() // This should *never* happen because the values are validated on Discord side BUT who knows if (tickerId !in LorittaBovespaBrokerUtils.validStocksCodes) context.failEphemerally(context.i18nContext.get(BrokerCommand.I18N_PREFIX.ThatIsNotAnValidStockTicker(loritta.commandMentions.brokerInfo))) val stockInformation = context.loritta.pudding.bovespaBroker.getTicker(tickerId) ?: context.failEphemerally(context.i18nContext.get(BrokerCommand.I18N_PREFIX.ThatIsNotAnValidStockTicker(loritta.commandMentions.brokerInfo))) val stockAsset = context.loritta.pudding.bovespaBroker.getUserBoughtStocks(context.user.id.value.toLong()) .firstOrNull { it.ticker == tickerId } context.sendEphemeralMessage { brokerBaseEmbed(context) { title = "${Emotes.LoriStonks} ${context.i18nContext.get(BrokerCommand.I18N_PREFIX.Stock.Embed.Title)}" // This is just like the "/broker portfolio" command // There is two alternatives however: If the user has stock, the output will be the same as the "/broker portfolio" command // If not, it will be just the buy/sell price val tickerInformation = stockInformation val tickerName = LorittaBovespaBrokerUtils.trackedTickerCodes.first { it.ticker == tickerInformation.ticker }.name val currentPrice = LorittaBovespaBrokerUtils.convertReaisToSonhos(tickerInformation.value) val buyingPrice = LorittaBovespaBrokerUtils.convertToBuyingPrice(currentPrice) // Buying price val sellingPrice = LorittaBovespaBrokerUtils.convertToSellingPrice(currentPrice) // Selling price val changePercentage = tickerInformation.dailyPriceVariation val emojiStatus = BrokerExecutorUtils.getEmojiStatusForTicker(tickerInformation) if (stockAsset != null) { val (tickerId, stockCount, stockSum, stockAverage) = stockAsset val totalGainsIfSoldNow = LorittaBovespaBrokerUtils.convertToSellingPrice( LorittaBovespaBrokerUtils.convertReaisToSonhos( tickerInformation.value ) ) * stockCount val diff = totalGainsIfSoldNow - stockSum val emojiProfit = when { diff > 0 -> "\uD83D\uDD3C" 0 > diff -> "\uD83D\uDD3D" else -> "⏹️" } // https://percentage-change-calculator.com/ val profitPercentage = ((totalGainsIfSoldNow - stockSum.toDouble()) / stockSum) val youHaveSharesInThisTickerMessage = context.i18nContext.get( BrokerCommand.I18N_PREFIX.Portfolio.YouHaveSharesInThisTicker( stockCount, stockSum, totalGainsIfSoldNow, diff.let { if (it > 0) "+$it" else it.toString() }, profitPercentage ) ) if (!LorittaBovespaBrokerUtils.checkIfTickerIsActive(tickerInformation.status)) { field( "$emojiStatus$emojiProfit `${tickerId}` ($tickerName) | ${"%.2f".format(changePercentage)}%", """${context.i18nContext.get(BrokerCommand.I18N_PREFIX.Info.Embed.PriceBeforeMarketClose(currentPrice))} |$youHaveSharesInThisTickerMessage """.trimMargin() ) } else { field( "$emojiStatus$emojiProfit `${tickerId}` ($tickerName) | ${"%.2f".format(changePercentage)}%", """${context.i18nContext.get(BrokerCommand.I18N_PREFIX.Info.Embed.BuyPrice(buyingPrice))} |${context.i18nContext.get(BrokerCommand.I18N_PREFIX.Info.Embed.SellPrice(sellingPrice))} |$youHaveSharesInThisTickerMessage""".trimMargin() ) } } else { if (!LorittaBovespaBrokerUtils.checkIfTickerIsActive(tickerInformation.status)) { field( "$emojiStatus `${tickerId}` ($tickerName) | ${"%.2f".format(changePercentage)}%", context.i18nContext.get(BrokerCommand.I18N_PREFIX.Info.Embed.PriceBeforeMarketClose(currentPrice)) .trimMargin() ) } else { field( "$emojiStatus `${tickerId}` ($tickerName) | ${"%.2f".format(changePercentage)}%", """${context.i18nContext.get(BrokerCommand.I18N_PREFIX.Info.Embed.BuyPrice(buyingPrice))} |${context.i18nContext.get(BrokerCommand.I18N_PREFIX.Info.Embed.SellPrice(sellingPrice))}""".trimMargin() ) } } } } } }
agpl-3.0
d4f6f59c045672e80a951c7499bfd38e
58.709402
154
0.618468
5.491352
false
false
false
false
LorittaBot/Loritta
web/dashboard/spicy-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/dashboard/frontend/utils/discordcdn/CdnUrl.kt
1
908
package net.perfectdreams.loritta.cinnamon.dashboard.frontend.utils.discordcdn // From Kord public class CdnUrl(private val rawAssetUri: String) { public fun toUrl(): String { return toUrl(UrlFormatBuilder()) } public inline fun toUrl(format: UrlFormatBuilder.() -> Unit): String { val config = UrlFormatBuilder().apply(format) return toUrl(config) } public fun toUrl(config: UrlFormatBuilder): String { val urlBuilder = StringBuilder(rawAssetUri).append(".").append(config.format.extension) config.size?.let { urlBuilder.append("?size=").append(it.maxRes) } return urlBuilder.toString() } override fun toString(): String { return "CdnUrl(rawAssetUri=$rawAssetUri)" } public class UrlFormatBuilder { public var format: Image.Format = Image.Format.WEBP public var size: Image.Size? = null } }
agpl-3.0
2967b0951caeaa3a26f35a36c2deafac
31.464286
95
0.671806
4.472906
false
true
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/util/http/ConnectivityInterceptor.kt
1
1129
package me.proxer.app.util.http import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.os.Build import android.provider.Settings import androidx.core.content.getSystemService import me.proxer.app.exception.NotConnectedException import me.proxer.app.util.compat.isConnected import okhttp3.Interceptor import okhttp3.Response /** * @author Ruben Gees */ class ConnectivityInterceptor(context: Context) : Interceptor { private val connectivityManager = requireNotNull(context.getSystemService<ConnectivityManager>()) private val hasConnectionSettings = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY).resolveActivity(context.packageManager) != null || Intent(Settings.ACTION_WIRELESS_SETTINGS).resolveActivity(context.packageManager) != null override fun intercept(chain: Interceptor.Chain): Response { if (hasConnectionSettings && !connectivityManager.isConnected) { throw NotConnectedException() } return chain.proceed(chain.request()) } }
gpl-3.0
eeee70c4416d088ae6edcd204aa3b347
34.28125
110
0.773251
4.704167
false
false
false
false