repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
inorichi/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsReaderController.kt
1
13116
package eu.kanade.tachiyomi.ui.setting import android.os.Build import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferenceValues import eu.kanade.tachiyomi.data.preference.PreferenceValues.TappingInvertMode import eu.kanade.tachiyomi.ui.reader.setting.OrientationType import eu.kanade.tachiyomi.ui.reader.setting.ReadingModeType import eu.kanade.tachiyomi.util.preference.bindTo import eu.kanade.tachiyomi.util.preference.defaultValue import eu.kanade.tachiyomi.util.preference.entriesRes import eu.kanade.tachiyomi.util.preference.intListPreference import eu.kanade.tachiyomi.util.preference.listPreference import eu.kanade.tachiyomi.util.preference.preferenceCategory import eu.kanade.tachiyomi.util.preference.summaryRes import eu.kanade.tachiyomi.util.preference.switchPreference import eu.kanade.tachiyomi.util.preference.titleRes import eu.kanade.tachiyomi.util.system.hasDisplayCutout import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys class SettingsReaderController : SettingsController() { override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply { titleRes = R.string.pref_category_reader intListPreference { key = Keys.defaultReadingMode titleRes = R.string.pref_viewer_type entriesRes = arrayOf( R.string.left_to_right_viewer, R.string.right_to_left_viewer, R.string.vertical_viewer, R.string.webtoon_viewer, R.string.vertical_plus_viewer ) entryValues = ReadingModeType.values().drop(1) .map { value -> "${value.flagValue}" }.toTypedArray() defaultValue = "${ReadingModeType.RIGHT_TO_LEFT.flagValue}" summary = "%s" } intListPreference { bindTo(preferences.doubleTapAnimSpeed()) titleRes = R.string.pref_double_tap_anim_speed entries = arrayOf(context.getString(R.string.double_tap_anim_speed_0), context.getString(R.string.double_tap_anim_speed_normal), context.getString(R.string.double_tap_anim_speed_fast)) entryValues = arrayOf("1", "500", "250") // using a value of 0 breaks the image viewer, so min is 1 summary = "%s" } switchPreference { key = Keys.showReadingMode titleRes = R.string.pref_show_reading_mode summaryRes = R.string.pref_show_reading_mode_summary defaultValue = true } switchPreference { bindTo(preferences.showNavigationOverlayOnStart()) titleRes = R.string.pref_show_navigation_mode summaryRes = R.string.pref_show_navigation_mode_summary } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { switchPreference { bindTo(preferences.trueColor()) titleRes = R.string.pref_true_color summaryRes = R.string.pref_true_color_summary } } switchPreference { bindTo(preferences.pageTransitions()) titleRes = R.string.pref_page_transitions } preferenceCategory { titleRes = R.string.pref_category_display intListPreference { key = Keys.defaultOrientationType titleRes = R.string.pref_rotation_type entriesRes = arrayOf( R.string.rotation_free, R.string.rotation_portrait, R.string.rotation_landscape, R.string.rotation_force_portrait, R.string.rotation_force_landscape, ) entryValues = OrientationType.values().drop(1) .map { value -> "${value.flagValue}" }.toTypedArray() defaultValue = "${OrientationType.FREE.flagValue}" summary = "%s" } intListPreference { bindTo(preferences.readerTheme()) titleRes = R.string.pref_reader_theme entriesRes = arrayOf(R.string.black_background, R.string.gray_background, R.string.white_background, R.string.automatic_background) entryValues = arrayOf("1", "2", "0", "3") summary = "%s" } switchPreference { bindTo(preferences.fullscreen()) titleRes = R.string.pref_fullscreen } if (activity?.hasDisplayCutout() == true) { switchPreference { bindTo(preferences.cutoutShort()) titleRes = R.string.pref_cutout_short visibleIf(preferences.fullscreen()) { it } } } switchPreference { bindTo(preferences.keepScreenOn()) titleRes = R.string.pref_keep_screen_on } switchPreference { bindTo(preferences.showPageNumber()) titleRes = R.string.pref_show_page_number } } preferenceCategory { titleRes = R.string.pref_category_reading switchPreference { key = Keys.skipRead titleRes = R.string.pref_skip_read_chapters defaultValue = false } switchPreference { key = Keys.skipFiltered titleRes = R.string.pref_skip_filtered_chapters defaultValue = true } switchPreference { bindTo(preferences.alwaysShowChapterTransition()) titleRes = R.string.pref_always_show_chapter_transition } } preferenceCategory { titleRes = R.string.pager_viewer intListPreference { bindTo(preferences.navigationModePager()) titleRes = R.string.pref_viewer_nav entries = context.resources.getStringArray(R.array.pager_nav).also { values -> entryValues = values.indices.map { index -> "$index" }.toTypedArray() } summary = "%s" visibleIf(preferences.readWithTapping()) { it } } listPreference { bindTo(preferences.pagerNavInverted()) titleRes = R.string.pref_read_with_tapping_inverted entriesRes = arrayOf( R.string.tapping_inverted_none, R.string.tapping_inverted_horizontal, R.string.tapping_inverted_vertical, R.string.tapping_inverted_both ) entryValues = arrayOf( TappingInvertMode.NONE.name, TappingInvertMode.HORIZONTAL.name, TappingInvertMode.VERTICAL.name, TappingInvertMode.BOTH.name ) summary = "%s" visibleIf(preferences.readWithTapping()) { it } } intListPreference { bindTo(preferences.imageScaleType()) titleRes = R.string.pref_image_scale_type entriesRes = arrayOf( R.string.scale_type_fit_screen, R.string.scale_type_stretch, R.string.scale_type_fit_width, R.string.scale_type_fit_height, R.string.scale_type_original_size, R.string.scale_type_smart_fit ) entryValues = arrayOf("1", "2", "3", "4", "5", "6") summary = "%s" } intListPreference { bindTo(preferences.zoomStart()) titleRes = R.string.pref_zoom_start entriesRes = arrayOf( R.string.zoom_start_automatic, R.string.zoom_start_left, R.string.zoom_start_right, R.string.zoom_start_center ) entryValues = arrayOf("1", "2", "3", "4") summary = "%s" } switchPreference { bindTo(preferences.cropBorders()) titleRes = R.string.pref_crop_borders } switchPreference { bindTo(preferences.dualPageSplitPaged()) titleRes = R.string.pref_dual_page_split } switchPreference { bindTo(preferences.dualPageInvertPaged()) titleRes = R.string.pref_dual_page_invert summaryRes = R.string.pref_dual_page_invert_summary visibleIf(preferences.dualPageSplitPaged()) { it } } } preferenceCategory { titleRes = R.string.webtoon_viewer intListPreference { bindTo(preferences.navigationModeWebtoon()) titleRes = R.string.pref_viewer_nav entries = context.resources.getStringArray(R.array.webtoon_nav).also { values -> entryValues = values.indices.map { index -> "$index" }.toTypedArray() } summary = "%s" visibleIf(preferences.readWithTapping()) { it } } listPreference { bindTo(preferences.webtoonNavInverted()) titleRes = R.string.pref_read_with_tapping_inverted entriesRes = arrayOf( R.string.tapping_inverted_none, R.string.tapping_inverted_horizontal, R.string.tapping_inverted_vertical, R.string.tapping_inverted_both ) entryValues = arrayOf( TappingInvertMode.NONE.name, TappingInvertMode.HORIZONTAL.name, TappingInvertMode.VERTICAL.name, TappingInvertMode.BOTH.name ) summary = "%s" visibleIf(preferences.readWithTapping()) { it } } intListPreference { bindTo(preferences.webtoonSidePadding()) titleRes = R.string.pref_webtoon_side_padding entriesRes = arrayOf( R.string.webtoon_side_padding_0, R.string.webtoon_side_padding_10, R.string.webtoon_side_padding_15, R.string.webtoon_side_padding_20, R.string.webtoon_side_padding_25 ) entryValues = arrayOf("0", "10", "15", "20", "25") summary = "%s" } listPreference { bindTo(preferences.readerHideThreshold()) titleRes = R.string.pref_hide_threshold entriesRes = arrayOf( R.string.pref_highest, R.string.pref_high, R.string.pref_low, R.string.pref_lowest ) entryValues = PreferenceValues.ReaderHideThreshold.values() .map { it.name } .toTypedArray() summary = "%s" } switchPreference { bindTo(preferences.cropBordersWebtoon()) titleRes = R.string.pref_crop_borders } switchPreference { bindTo(preferences.dualPageSplitWebtoon()) titleRes = R.string.pref_dual_page_split } switchPreference { bindTo(preferences.dualPageInvertWebtoon()) titleRes = R.string.pref_dual_page_invert summaryRes = R.string.pref_dual_page_invert_summary visibleIf(preferences.dualPageSplitWebtoon()) { it } } } preferenceCategory { titleRes = R.string.pref_reader_navigation switchPreference { bindTo(preferences.readWithTapping()) titleRes = R.string.pref_read_with_tapping } switchPreference { bindTo(preferences.readWithVolumeKeys()) titleRes = R.string.pref_read_with_volume_keys } switchPreference { bindTo(preferences.readWithVolumeKeysInverted()) titleRes = R.string.pref_read_with_volume_keys_inverted visibleIf(preferences.readWithVolumeKeys()) { it } } } preferenceCategory { titleRes = R.string.pref_reader_actions switchPreference { bindTo(preferences.readWithLongTap()) titleRes = R.string.pref_read_with_long_tap } switchPreference { key = Keys.folderPerManga titleRes = R.string.pref_create_folder_per_manga summaryRes = R.string.pref_create_folder_per_manga_summary defaultValue = false } } } }
apache-2.0
18765a40a2dd66190a5266dda219e524
39.859813
196
0.544221
5.107477
false
false
false
false
Zhuinden/simple-stack
samples/advanced-samples/mvvm-sample/src/main/java/com/zhuinden/simplestackexamplemvvm/features/addedittask/AddEditTaskViewModel.kt
1
2046
package com.zhuinden.simplestackexamplemvvm.features.addedittask import com.zhuinden.simplestack.Backstack import com.zhuinden.simplestack.Bundleable import com.zhuinden.simplestackexamplemvvm.R import com.zhuinden.simplestackexamplemvvm.application.SnackbarTextEmitter import com.zhuinden.simplestackexamplemvvm.data.Task import com.zhuinden.simplestackexamplemvvm.data.tasks.TasksDataSource import com.zhuinden.simplestackexamplemvvm.features.tasks.TasksViewModel import com.zhuinden.statebundle.StateBundle class AddEditTaskViewModel( private val snackbarTextEmitter: SnackbarTextEmitter, private val tasksViewModel: TasksViewModel, private val tasksDataSource: TasksDataSource, private val backstack: Backstack, private val key: AddEditTaskKey ) : Bundleable { var title: String = key.task?.title ?: "" var description: String = key.task?.description ?: "" fun onSaveTaskClicked() { if (key.task == null) { createTask() } else { updateTask() } } private fun createTask() { val newTask: Task = Task.createNewActiveTask(title, description) if (newTask.isEmpty) { snackbarTextEmitter.emit(R.string.empty_task_message) } else { tasksDataSource.saveTask(newTask) tasksViewModel.onTaskAdded() backstack.jumpToRoot() } } private fun updateTask() { tasksDataSource.saveTask(Task.createTaskWithId(title, description, key.task?.id, key.task?.completed ?: false)) tasksViewModel.onTaskSaved() backstack.jumpToRoot() } override fun toBundle(): StateBundle { val bundle = StateBundle() bundle.putString("title", title) bundle.putString("description", description) return bundle } override fun fromBundle(bundle: StateBundle?) { if (bundle != null) { title = bundle.getString("title", "") description = bundle.getString("description", "") } } }
apache-2.0
bfa74a4fb8a0865489ab92f541b5eb8f
32.016129
108
0.682796
4.825472
false
false
false
false
SUPERCILEX/Robot-Scouter
buildSrc/src/main/kotlin/com/supercilex/robotscouter/build/RobotScouterBuildPlugin.kt
1
1810
package com.supercilex.robotscouter.build import child import com.supercilex.robotscouter.build.tasks.DeployServer import com.supercilex.robotscouter.build.tasks.GenerateChangelog import com.supercilex.robotscouter.build.tasks.RebuildSecrets import com.supercilex.robotscouter.build.tasks.Setup import com.supercilex.robotscouter.build.tasks.UpdateTranslations import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.register internal class RobotScouterBuildPlugin : Plugin<Project> { override fun apply(project: Project) { check(project === project.rootProject) { "Cannot apply build plugin to subprojects." } project.tasks.register<Setup>("setup") { group = "build setup" description = "Performs one-time setup to prepare Robot Scouter for building." } project.tasks.register<RebuildSecrets>("rebuildSecrets") { group = "build setup" description = "Repackages a new version of the secrets for CI." } project.tasks.register<UpdateTranslations>("updateTranslations") { group = "build setup" description = "Overwrites existing translations with new ones." translationDir.set(project.file("tmp-translations")) } applyAndroidBase(project.child("android-base")) applyFunctions(project.child("functions")) } private fun applyAndroidBase(project: Project) { project.tasks.register<GenerateChangelog>("generateChangelog") } private fun applyFunctions(project: Project) { project.tasks.register<DeployServer>("deployServer") { group = "publishing" description = "Deploys Robot Scouter to the Web and Backend." dependsOn("assemble") } } }
gpl-3.0
1e5017df3dad4005b38efe8bdd955db9
36.708333
94
0.696133
4.641026
false
false
false
false
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/adapter/AssigneeSpinnerAdapter.kt
2
1842
package com.commit451.gitlab.adapter import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import com.commit451.gitlab.R import com.commit451.gitlab.model.api.User import com.commit451.gitlab.viewHolder.AssigneeSpinnerViewHolder /** * Adapter to show assignees in a spinner */ class AssigneeSpinnerAdapter(context: Context, members: MutableList<User?>) : ArrayAdapter<User?>(context, 0, members) { init { members.add(0, null) notifyDataSetChanged() } fun getSelectedItemPosition(userBasic: User?): Int { if (userBasic == null) { return 0 } for (i in 0..count - 1) { val member = getItem(i) if (member != null && userBasic.id == member.id) { return i } } return 0 } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { return getTheView(position, convertView, parent) } override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { return getTheView(position, convertView, parent) } private fun getTheView(position: Int, convertView: View?, parent: ViewGroup): View { val member = getItem(position) val assigneeSpinnerViewHolder: AssigneeSpinnerViewHolder if (convertView == null) { assigneeSpinnerViewHolder = AssigneeSpinnerViewHolder.inflate(parent) assigneeSpinnerViewHolder.itemView.setTag(R.id.list_view_holder, assigneeSpinnerViewHolder) } else { assigneeSpinnerViewHolder = convertView.getTag(R.id.list_view_holder) as AssigneeSpinnerViewHolder } assigneeSpinnerViewHolder.bind(member) return assigneeSpinnerViewHolder.itemView } }
apache-2.0
b37b2e972733db94796b1f91c73c1db0
32.509091
120
0.675353
4.460048
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/main/java/jp/toastkid/yobidashi/browser/webview/CustomWebView.kt
1
9093
package jp.toastkid.yobidashi.browser.webview import android.content.Context import android.content.Intent import android.view.ActionMode import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.MotionEvent import android.webkit.WebView import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.core.net.toUri import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import jp.toastkid.lib.BrowserViewModel import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.libs.speech.SpeechMaker import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.browser.webview.usecase.SelectedTextUseCase /** * Extend for disabling pull-to-refresh on Google map. * * @author toastkidjp */ internal class CustomWebView(context: Context) : WebView(context) { /** * Pull-to-Refresh availability. */ var enablePullToRefresh = false /** * Scrolling value. */ private var scrolling: Int = 1 private var nestedOffsetY: Float = 0f private var lastY: Float = 0f private var nestedOffsetX: Float = 0f private var lastX: Float = 0f private val scrollOffset = IntArray(2) private val scrollConsumed = IntArray(2) private val speechMaker by lazy { SpeechMaker(context) } private val viewModel = (context as? ViewModelStoreOwner)?.let { ViewModelProvider(it).get(BrowserViewModel::class.java) } override fun dispatchTouchEvent(motionEvent: MotionEvent?): Boolean { if (motionEvent?.action == MotionEvent.ACTION_UP) { scrolling = 0 } if (isMultiTap(motionEvent)) { return super.dispatchTouchEvent(motionEvent) } val event = MotionEvent.obtain(motionEvent) val action = event.actionMasked if (action == MotionEvent.ACTION_DOWN) { nestedOffsetX = 0f nestedOffsetY = 0f } val eventX = event.x.toInt() val eventY = event.y.toInt() when (action) { MotionEvent.ACTION_MOVE -> { var deltaX: Float = lastX - eventX var deltaY: Float = lastY - eventY if (enablePullToRefresh && (deltaY < 0)) { viewModel?.nestedScrollDispatcher()?.dispatchPreScroll( Offset(0f, deltaY / 10f), NestedScrollSource.Drag ) return true } enablePullToRefresh = false // NestedPreScroll if (dispatchNestedPreScroll(deltaX.toInt(), deltaY.toInt(), scrollConsumed, scrollOffset)) { deltaY -= scrollConsumed[1] lastY = eventY - scrollOffset[1].toFloat() deltaX -= scrollConsumed[0] lastX = eventX - scrollConsumed[0].toFloat() event.offsetLocation(deltaX, deltaY) nestedOffsetX += scrollOffset[0] nestedOffsetY += scrollOffset[1] } else { lastY = eventY.toFloat() } val returnValue = super.dispatchTouchEvent(event) // NestedScroll if (dispatchNestedScroll(scrollOffset[0], scrollOffset[1], deltaX.toInt(), deltaY.toInt(), scrollOffset)) { event.offsetLocation(scrollOffset[0].toFloat(), scrollOffset[1].toFloat()) nestedOffsetX += scrollOffset[0] nestedOffsetY += scrollOffset[1] lastY -= scrollOffset[1] } return returnValue } MotionEvent.ACTION_DOWN -> { val returnValue = super.dispatchTouchEvent(event) lastX = eventX.toFloat() lastY = eventY.toFloat() // start NestedScroll //startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH) return returnValue } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { val returnValue = super.dispatchTouchEvent(event) enablePullToRefresh = false viewModel?.nestedScrollDispatcher()?.dispatchPostScroll( Offset.Zero, Offset.Zero, NestedScrollSource.Drag ) // end NestedScroll stopNestedScroll() return returnValue } } return true } private fun isMultiTap(motionEvent: MotionEvent?) = (motionEvent?.pointerCount ?: 0) >= 2 override fun onOverScrolled(scrollX: Int, scrollY: Int, clampedX: Boolean, clampedY: Boolean) { super.onOverScrolled(scrollX, scrollY, clampedX, clampedY) enablePullToRefresh = scrolling <= 0 } override fun onScrollChanged(horizontal: Int, vertical: Int, oldHorizontal: Int, oldVertical: Int) { super.onScrollChanged(horizontal, vertical, oldHorizontal, oldVertical) scrolling += vertical } override fun startActionMode(callback: ActionMode.Callback?, type: Int): ActionMode? = super.startActionMode( object : ActionMode.Callback { override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean { if (enablePullToRefresh) { return false } val menuInflater = MenuInflater(context) menuInflater.inflate(R.menu.context_speech, menu) menuInflater.inflate(R.menu.context_browser, menu) return true } override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean { when (item?.itemId) { R.id.context_edit_speech -> { selectedTextExtractor.withAction(this@CustomWebView) { speechMaker.invoke(it) } mode?.finish() return true } R.id.preview_search -> { searchWithPreview() mode?.finish() return true } R.id.search_with_map_app -> { selectedTextExtractor.withAction(this@CustomWebView) { context.startActivity( Intent(Intent.ACTION_VIEW, "geo:0,0?q=$it".toUri()) ) } mode?.finish() return true } R.id.web_search -> { search() mode?.finish() return true } R.id.count -> { countSelectedCharacters() mode?.finish() return true } } return callback?.onActionItemClicked(mode, item) ?: false } override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { return callback?.onPrepareActionMode(mode, menu) ?: false } override fun onDestroyActionMode(mode: ActionMode?) { callback?.onDestroyActionMode(mode) } }, type ) private fun countSelectedCharacters() { selectedTextExtractor.withAction(this) { SelectedTextUseCase.make(context)?.countCharacters(it) } } private fun search() { selectedTextExtractor.withAction(this@CustomWebView) { word -> SelectedTextUseCase.make(context) ?.search(word, PreferenceApplier(context).getDefaultSearchEngine()) } } private fun searchWithPreview() { selectedTextExtractor.withAction(this@CustomWebView) { word -> SelectedTextUseCase.make(context) ?.searchWithPreview(word, PreferenceApplier(context).getDefaultSearchEngine()) } } companion object { private val selectedTextExtractor = SelectedTextExtractor() } }
epl-1.0
055c7e8149bcaa1b1af73e2142fdee9e
37.210084
123
0.515341
6.025845
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/data/converters/RankedPlayerConverter.kt
1
2839
package com.garpr.android.data.converters import com.garpr.android.data.models.RankedPlayer import com.squareup.moshi.FromJson import com.squareup.moshi.JsonDataException import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import com.squareup.moshi.ToJson object RankedPlayerConverter { private val ID = 0 to "id" private val NAME = 1 to "name" private val PREVIOUS_RANK = 2 to "previous_rank" private val RANK = 3 to "rank" private val RATING = 4 to "rating" private val OPTIONS = JsonReader.Options.of(ID.second, NAME.second, PREVIOUS_RANK.second, RANK.second, RATING.second) @FromJson fun fromJson(reader: JsonReader): RankedPlayer? { if (reader.peek() == JsonReader.Token.NULL) { return reader.nextNull() } reader.beginObject() var id: String? = null var name: String? = null var rating: Float? = null var rank: Int? = null var previousRank: Int? = null while (reader.hasNext()) { when (reader.selectName(OPTIONS)) { ID.first -> id = reader.nextString() NAME.first -> name = reader.nextString() PREVIOUS_RANK.first -> { previousRank = if (reader.peek() == JsonReader.Token.NUMBER) { reader.nextInt() } else { reader.skipValue() Int.MIN_VALUE } } RATING.first -> rating = reader.nextDouble().toFloat() RANK.first -> rank = reader.nextInt() else -> { reader.skipName() reader.skipValue() } } } reader.endObject() if (id == null || name == null || rating == null || rank == null) { throw JsonDataException("Invalid JSON data (id:$id, name:$name, rating:$rating, " + "rank:$rank, previousRank:$previousRank)") } return RankedPlayer( id = id, name = name, rating = rating, rank = rank, previousRank = previousRank ) } @ToJson fun toJson(writer: JsonWriter, value: RankedPlayer?) { if (value == null) { return } writer.beginObject() .name(ID.second).value(value.id) .name(NAME.second).value(value.name) .name(RATING.second).value(value.rating) .name(RANK.second).value(value.rank) if (value.previousRank != null && value.previousRank != Int.MIN_VALUE) { writer.name(PREVIOUS_RANK.second).value(value.previousRank) } writer.endObject() } }
unlicense
795a5c9d1f5b83e9472872698377aad1
30.197802
95
0.532582
4.601297
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_gls/src/main/java/no/nordicsemi/android/gls/main/view/GLSScreen.kt
1
4294
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.gls.main.view import androidx.compose.foundation.layout.Column import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import no.nordicsemi.android.gls.R import no.nordicsemi.android.gls.main.viewmodel.GLSViewModel import no.nordicsemi.android.service.* import no.nordicsemi.android.ui.view.BackIconAppBar import no.nordicsemi.android.ui.view.LoggerIconAppBar import no.nordicsemi.android.utils.exhaustive import no.nordicsemi.ui.scanner.ui.DeviceConnectingView import no.nordicsemi.ui.scanner.ui.DeviceDisconnectedView import no.nordicsemi.ui.scanner.ui.NoDeviceView import no.nordicsemi.ui.scanner.ui.Reason @Composable fun GLSScreen() { val viewModel: GLSViewModel = hiltViewModel() val state = viewModel.state.collectAsState().value Column { val navigateUp = { viewModel.onEvent(DisconnectEvent) } AppBar(state, navigateUp, viewModel) Column(modifier = Modifier.verticalScroll(rememberScrollState())) { when (state) { NoDeviceState -> NoDeviceView() is WorkingState -> when (state.result) { is IdleResult, is ConnectingResult -> DeviceConnectingView { viewModel.onEvent(DisconnectEvent) } is ConnectedResult -> DeviceConnectingView { viewModel.onEvent(DisconnectEvent) } is DisconnectedResult -> DeviceDisconnectedView(Reason.USER, navigateUp) is LinkLossResult -> DeviceDisconnectedView(Reason.LINK_LOSS, navigateUp) is MissingServiceResult -> DeviceDisconnectedView(Reason.MISSING_SERVICE, navigateUp) is UnknownErrorResult -> DeviceDisconnectedView(Reason.UNKNOWN, navigateUp) is SuccessResult -> GLSContentView(state.result.data) { viewModel.onEvent(it) } } }.exhaustive } } } @Composable private fun AppBar(state: GLSViewState, navigateUp: () -> Unit, viewModel: GLSViewModel) { val toolbarName = (state as? WorkingState)?.let { (it.result as? DeviceHolder)?.deviceName() } if (toolbarName == null) { BackIconAppBar(stringResource(id = R.string.gls_title), navigateUp) } else { LoggerIconAppBar(toolbarName, { viewModel.onEvent(DisconnectEvent) }, { viewModel.onEvent(DisconnectEvent) }) { viewModel.onEvent(OpenLoggerEvent) } } }
bsd-3-clause
0258ee1107cb8eb277436251f559cba8
43.729167
105
0.731253
4.652221
false
false
false
false
MaisonWan/AppFileExplorer
FileExplorer/src/main/java/com/domker/app/explorer/adapter/TabPagerAdapter.kt
1
1701
package com.domker.app.explorer.adapter import android.app.Fragment import android.app.FragmentManager import android.content.Context import android.os.Bundle import android.support.v13.app.FragmentPagerAdapter import android.util.Log import com.domker.app.explorer.fragment.FileListFragment import com.domker.app.explorer.util.PhoneInfo /** * Tab和ViewPager组合使用 * Created by wanlipeng on 2017/9/11. */ class TabPagerAdapter(val context: Context, fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) { private lateinit var fragments : Array<FileListFragment?> /** * 显示tab的名字 */ var tabNames: Array<String>? = null set(value) { field = value fragments = arrayOfNulls(field!!.size) } override fun getItem(position: Int): Fragment { Log.i("Adapter", "getItem: " + position) if (fragments[position] == null) { fragments[position] = FileListFragment() } val fragment = fragments[position] val bundle = Bundle() when (position) { 0 -> bundle.putString(FileListFragment.KEY_DEFAULT_PATH, PhoneInfo.getSdCardPath()!!) 1 -> bundle.putString(FileListFragment.KEY_DEFAULT_PATH, PhoneInfo.getInnerPath(context)) } fragment?.arguments = bundle return fragment!! } override fun getCount(): Int = tabNames?.size ?:0 override fun getPageTitle(position: Int): CharSequence { return tabNames?.get(position) ?: "" } fun getCurrentFragment(position: Int): FileListFragment? { return if (position >= fragments.size) null else fragments[position] } }
apache-2.0
e827bb5ec1f4f0a5ec2360c356073226
30.148148
101
0.671624
4.343669
false
false
false
false
lavong/FlickrImageSearchDemo
app/src/main/java/com/ingloriousmind/android/flickrimagesearchdemo/photowall/PhotowallAdapter.kt
1
1973
package com.ingloriousmind.android.flickrimagesearchdemo.photowall import android.support.v7.widget.RecyclerView import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.ingloriousmind.android.flickrimagesearchdemo.R import com.ingloriousmind.android.flickrimagesearchdemo.photowall.model.PhotoItem class PhotowallAdapter(val clickHandler: ClickHandler) : RecyclerView.Adapter<PhotowallAdapter.PhotoViewHolder>() { var items: MutableList<PhotoItem> = mutableListOf() override fun onBindViewHolder(holder: PhotoViewHolder, pos: Int) { val photoItem = items.get(pos) Glide.with(holder.image.context).load(photoItem.imageUrl).into(holder.image) holder.label.visibility = if (TextUtils.isEmpty(photoItem.label)) View.GONE else View.VISIBLE holder.label.text = photoItem.label holder.itemView.setOnClickListener { clickHandler.onPhotoClicked(photoItem, pos) } } override fun getItemCount(): Int { return items.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_photo_wall, parent, false) return PhotoViewHolder(view) } fun setPhotoItems(photos: List<PhotoItem>) { items.clear() items.addAll(photos) notifyDataSetChanged() } fun clear() { items.clear() notifyDataSetChanged() } inner class PhotoViewHolder(view: View) : RecyclerView.ViewHolder(view) { val image: ImageView = view.findViewById(R.id.item_photo_wall_image) as ImageView val label: TextView = view.findViewById(R.id.item_photo_wall_label) as TextView } interface ClickHandler { fun onPhotoClicked(photoItem: PhotoItem, position: Int) } }
apache-2.0
f392b8c5bf6518032aa1be7a8e139a9e
34.25
115
0.736442
4.093361
false
false
false
false
http4k/http4k
http4k-client/okhttp/src/main/kotlin/org/http4k/client/OkHttp.kt
1
4570
package org.http4k.client import okhttp3.Call import okhttp3.Callback import okhttp3.OkHttpClient import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.internal.http.HttpMethod.permitsRequestBody import org.http4k.client.PreCannedOkHttpClients.defaultOkHttpClient import org.http4k.core.BodyMode import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.Status.Companion.CLIENT_TIMEOUT import org.http4k.core.Status.Companion.CONNECTION_REFUSED import org.http4k.core.Status.Companion.SERVICE_UNAVAILABLE import org.http4k.core.Status.Companion.UNKNOWN_HOST import java.io.IOException import java.io.InterruptedIOException import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException import java.security.SecureRandom import java.security.cert.X509Certificate import javax.net.ssl.SSLContext import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager object OkHttp { @JvmStatic @JvmOverloads @JvmName("create") operator fun invoke( client: OkHttpClient = defaultOkHttpClient(), bodyMode: BodyMode = BodyMode.Memory ): DualSyncAsyncHttpHandler = object : DualSyncAsyncHttpHandler { override fun invoke(request: Request): Response = try { client.newCall(request.asOkHttp()).execute().asHttp4k(bodyMode) } catch (e: ConnectException) { Response(CONNECTION_REFUSED.toClientStatus(e)) } catch (e: UnknownHostException) { Response(UNKNOWN_HOST.toClientStatus(e)) } catch (e: InterruptedIOException) { when { e is SocketTimeoutException -> Response(CLIENT_TIMEOUT.toClientStatus(e)) e.message == "timeout" -> Response(CLIENT_TIMEOUT.toClientStatus(e)) else -> throw e } } override operator fun invoke(request: Request, fn: (Response) -> Unit) = client.newCall(request.asOkHttp()).enqueue(Http4kCallback(bodyMode, fn)) } private class Http4kCallback(private val bodyMode: BodyMode, private val fn: (Response) -> Unit) : Callback { override fun onFailure(call: Call, e: IOException) = fn( Response( when (e) { is SocketTimeoutException -> CLIENT_TIMEOUT else -> SERVICE_UNAVAILABLE }.description("Client Error: caused by ${e.localizedMessage}") ) ) override fun onResponse(call: Call, response: okhttp3.Response) = fn(response.asHttp4k(bodyMode)) } } internal fun Request.asOkHttp(): okhttp3.Request = headers.fold( okhttp3.Request.Builder() .url(uri.toString()) .method(method.toString(), requestBody()) ) { memo, (first, second) -> val notNullValue = second ?: "" memo.addHeader(first, notNullValue) }.build() private fun Request.requestBody() = if (permitsRequestBody(method.toString())) body.payload.array().toRequestBody() else null private fun okhttp3.Response.asHttp4k(bodyMode: BodyMode): Response { val init = Response(Status(code, message)) val headers = headers.toMultimap().flatMap { it.value.map { hValue -> it.key to hValue } } return (body?.let { init.body(bodyMode(it.byteStream())) } ?: init).headers(headers) } object PreCannedOkHttpClients { /** * Standard non-redirecting client */ fun defaultOkHttpClient() = OkHttpClient.Builder() .followRedirects(false) .build() /** * Do not use this in production! This is useful for testing locally and debugging HTTPS traffic */ fun insecureOkHttpClient(): OkHttpClient { val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager { override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) { } override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) { } override fun getAcceptedIssuers() = arrayOf<X509Certificate>() }) val sslSocketFactory = SSLContext.getInstance("SSL").apply { init(null, trustAllCerts, SecureRandom()) }.socketFactory return OkHttpClient.Builder() .sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager) .hostnameVerifier { _, _ -> true }.build() } }
apache-2.0
ae4d20ea7e155af8e7bb03424df7637b
36.768595
113
0.663895
4.506903
false
false
false
false
msebire/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsStatusMerger.kt
2
5366
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.impl import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.changes.Change import com.intellij.util.SmartList import com.intellij.util.containers.ContainerUtil import com.intellij.vcsUtil.VcsUtil abstract class VcsStatusMerger<S> { fun merge(statuses: List<List<S>>): List<MergedStatusInfo<S>> { statuses.singleOrNull()?.let { return it.map { MergedStatusInfo(it) } } val pathsToStatusesMap = statuses.map { infos -> infos.mapNotNull { info -> getPath(info)?.let { Pair(it, info) } }.toMap(linkedMapOf()) } val result = mutableListOf<MergedStatusInfo<S>>() outer@ for (path in pathsToStatusesMap.first().keys) { val statusesList = mutableListOf<S>() for (pathsToStatusesForParent in pathsToStatusesMap) { val status = pathsToStatusesForParent[path] ?: continue@outer statusesList.add(status) } result.add(MergedStatusInfo(merge(path, statusesList), statusesList)) } return result } fun merge(path: String, statuses: List<S>): S { val types = statuses.map { getType(it) }.distinct() if (types.size == 1) { if (types.single() == Change.Type.MOVED) { var renamedFrom: String? = null for (status in statuses) { if (renamedFrom == null) { renamedFrom = getFirstPath(status) } else if (renamedFrom != getFirstPath(status)) { return createStatus(Change.Type.MODIFICATION, path, null) } } } return statuses[0] } return if (types.contains(Change.Type.DELETED)) createStatus(Change.Type.DELETED, path, null) else createStatus(Change.Type.MODIFICATION, path, null) } private fun getPath(info: S): String? { when (getType(info)) { Change.Type.MODIFICATION, Change.Type.NEW, Change.Type.DELETED -> return getFirstPath(info) Change.Type.MOVED -> return getSecondPath(info) } } protected abstract fun createStatus(type: Change.Type, path: String, secondPath: String?): S protected abstract fun getFirstPath(info: S): String protected abstract fun getSecondPath(info: S): String? protected abstract fun getType(info: S): Change.Type class MergedStatusInfo<S> @JvmOverloads constructor(val statusInfo: S, infos: List<S> = ContainerUtil.emptyList()) { val mergedStatusInfos: List<S> init { mergedStatusInfos = SmartList(infos) } override fun toString(): String { return "MergedStatusInfo{" + "myStatusInfo=" + statusInfo + ", myMergedStatusInfos=" + mergedStatusInfos + '}'.toString() } } } data class VcsFileStatusInfo(val type: Change.Type, val firstPath: String, val secondPath: String?) { override fun toString(): String { var s = type.toString() + " " + firstPath if (secondPath != null) { s += " -> $secondPath" } return s } } class VcsFileStatusInfoMerger : VcsStatusMerger<VcsFileStatusInfo>() { override fun createStatus(type: Change.Type, path: String, secondPath: String?): VcsFileStatusInfo { return VcsFileStatusInfo(type, path, secondPath) } override fun getFirstPath(info: VcsFileStatusInfo): String = info.firstPath override fun getSecondPath(info: VcsFileStatusInfo): String? = info.secondPath override fun getType(info: VcsFileStatusInfo): Change.Type = info.type } abstract class VcsChangesMerger : VcsStatusMerger<Change>() { override fun createStatus(type: Change.Type, path: String, secondPath: String?): Change { when (type) { Change.Type.NEW -> return createChange(type, null, VcsUtil.getFilePath(path)) Change.Type.DELETED -> return createChange(type, VcsUtil.getFilePath(path), null) Change.Type.MOVED -> return createChange(type, VcsUtil.getFilePath(path), VcsUtil.getFilePath(secondPath)) Change.Type.MODIFICATION -> return createChange(type, VcsUtil.getFilePath(path), VcsUtil.getFilePath(path)) } } protected abstract fun createChange(type: Change.Type, beforePath: FilePath?, afterPath: FilePath?): Change fun merge(path: FilePath, changesToParents: List<Change>): Change { return MergedChange.SimpleMergedChange(merge(path.path, changesToParents), changesToParents) } override fun getFirstPath(info: Change): String { when (info.type!!) { Change.Type.MODIFICATION, Change.Type.NEW -> return info.afterRevision!!.file.path Change.Type.DELETED, Change.Type.MOVED -> return info.beforeRevision!!.file.path } } override fun getSecondPath(info: Change): String? { when (info.type!!) { Change.Type.MOVED -> return info.afterRevision!!.file.path else -> return null } } override fun getType(info: Change): Change.Type = info.type }
apache-2.0
689526e7cb5764fc60580a46089cc633
34.078431
118
0.694558
4.074412
false
false
false
false
microg/android_packages_apps_GmsCore
firebase-auth-core/src/main/kotlin/org/microg/gms/firebase/auth/ReCaptchaActivity.kt
1
4066
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.gms.firebase.auth import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.content.Intent.* import android.os.Bundle import android.os.ResultReceiver import android.util.Log import android.webkit.JavascriptInterface import android.webkit.WebSettings import android.webkit.WebView import androidx.appcompat.app.AppCompatActivity import org.microg.gms.firebase.auth.core.R import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine private const val TAG = "GmsFirebaseAuthCaptcha" class ReCaptchaActivity : AppCompatActivity() { private val receiver: ResultReceiver? get() = intent.getParcelableExtra(EXTRA_RESULT_RECEIVER) private val hostname: String get() = intent.getStringExtra(EXTRA_HOSTNAME) ?: "localhost:5000" private var finished = false @SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) openWebsite() } private fun openWebsite() { val apiKey = intent.getStringExtra(EXTRA_API_KEY) ?: return finishResult(Activity.RESULT_CANCELED) setContentView(R.layout.activity_recaptcha) val view = findViewById<WebView>(R.id.web) val settings = view.settings settings.javaScriptEnabled = true settings.useWideViewPort = false settings.setSupportZoom(false) settings.displayZoomControls = false settings.cacheMode = WebSettings.LOAD_NO_CACHE view.addJavascriptInterface(object : Any() { @JavascriptInterface fun onReCaptchaToken(token: String) { Log.d(TAG, "onReCaptchaToken: $token") finishResult(Activity.RESULT_OK, token) } }, "MyCallback") val captcha = assets.open("recaptcha.html").bufferedReader().readText().replace("%apikey%", apiKey) view.loadDataWithBaseURL("https://$hostname/", captcha, null, null, "https://$hostname/") } fun finishResult(resultCode: Int, token: String? = null) { finished = true setResult(resultCode, token?.let { Intent().apply { putExtra(EXTRA_TOKEN, it) } }) receiver?.send(resultCode, token?.let { Bundle().apply { putString(EXTRA_TOKEN, it) } }) finish() } override fun onDestroy() { super.onDestroy() if (!finished) receiver?.send(Activity.RESULT_CANCELED, null) } companion object { const val EXTRA_TOKEN = "token" const val EXTRA_API_KEY = "api_key" const val EXTRA_HOSTNAME = "hostname" const val EXTRA_RESULT_RECEIVER = "receiver" fun isSupported(context: Context): Boolean = true suspend fun awaitToken(context: Context, apiKey: String, hostname: String? = null) = suspendCoroutine<String> { continuation -> val intent = Intent(context, ReCaptchaActivity::class.java) val resultReceiver = object : ResultReceiver(null) { override fun onReceiveResult(resultCode: Int, resultData: Bundle?) { try { if (resultCode == Activity.RESULT_OK) { continuation.resume(resultData?.getString(EXTRA_TOKEN)!!) } } catch (e: Exception) { continuation.resumeWithException(e) } } } intent.putExtra(EXTRA_API_KEY, apiKey) intent.putExtra(EXTRA_RESULT_RECEIVER, resultReceiver) intent.putExtra(EXTRA_HOSTNAME, hostname) intent.addFlags(FLAG_ACTIVITY_NEW_TASK) intent.addFlags(FLAG_ACTIVITY_REORDER_TO_FRONT) intent.addFlags(FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) context.startActivity(intent) } } }
apache-2.0
90edf40474226ef8ebbb2dc94b47cb3d
38.475728
135
0.657895
4.684332
false
false
false
false
alashow/music-android
modules/domain/src/main/java/tm/alashow/datmusic/domain/entities/AudioHeader.kt
1
2436
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.domain.entities import android.media.MediaFormat import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.util.Locale data class AudioHeader( val mime: String = "", val format: String = "", val bitrate: Int = 0, val sampleRate: Int = 0, val channelCount: Int = 0, val durationMicros: Long = 0 ) { fun info(): String { val otherSymbols = DecimalFormatSymbols(Locale.US) val df = DecimalFormat("#.#", otherSymbols) val sample = "%s kHz".format(df.format((sampleRate.toFloat() / 1000f))) val bitrate = "%.0f kbps".format((bitrate.toFloat() / 1000)) return "$sample $bitrate $format".uppercase() } companion object { private fun MediaFormat.integer(key: String, default: Int): Int = try { getInteger(key) } catch (e: Exception) { default } private fun MediaFormat.string(key: String, default: String): String = try { getString(key) ?: default } catch (e: Exception) { default } private fun MediaFormat.long(key: String, default: Long): Long = try { getLong(key) } catch (e: Exception) { default } fun from(audioDownloadItem: AudioDownloadItem, mediaFormat: MediaFormat): AudioHeader { var header = AudioHeader( mime = mediaFormat.string(MediaFormat.KEY_MIME, "audio/mpeg"), bitrate = mediaFormat.integer(MediaFormat.KEY_BIT_RATE, 0), sampleRate = mediaFormat.integer(MediaFormat.KEY_SAMPLE_RATE, 0), channelCount = mediaFormat.integer(MediaFormat.KEY_CHANNEL_COUNT, 0), durationMicros = mediaFormat.long(MediaFormat.KEY_DURATION, 0L), ) if (header.bitrate == 0) { header = header.copy( bitrate = ((audioDownloadItem.downloadInfo.total * 8) / (header.durationMicros / 1E6)).toInt() ) } header = header.copy( format = when (header.mime) { "audio/mpeg" -> "mp3" "audio/raw", "audio/flac" -> "flac" else -> header.mime.replace("audio/", "") } ) return header } } }
apache-2.0
7be9833390a5656c1a62fe62cc356adb
32.369863
114
0.561987
4.461538
false
false
false
false
sabi0/intellij-community
java/java-impl/src/com/intellij/psi/impl/JavaPlatformModuleSystem.kt
1
11882
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl import com.intellij.codeInsight.JavaModuleSystemEx import com.intellij.codeInsight.JavaModuleSystemEx.ErrorWithFixes import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.JavaErrorMessages import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil import com.intellij.codeInsight.daemon.impl.quickfix.AddExportsDirectiveFix import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiresDirectiveFix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.JdkOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.psi.* import com.intellij.psi.impl.light.LightJavaModule import com.intellij.psi.impl.source.PsiJavaModuleReference import com.intellij.psi.util.PsiUtil /** * Checks package accessibility according to JLS 7 "Packages and Modules". * * @see <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-7.html">JLS 7 "Packages and Modules"</a> * @see <a href="http://openjdk.java.net/jeps/261">JEP 261: Module System</a> */ class JavaPlatformModuleSystem : JavaModuleSystemEx { override fun getName(): String = "Java Platform Module System" override fun isAccessible(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): Boolean = checkAccess(targetPackageName, targetFile?.originalFile, place, quick = true) == null override fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): ErrorWithFixes? = checkAccess(targetPackageName, targetFile?.originalFile, place, quick = false) private fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement, quick: Boolean): ErrorWithFixes? { val useFile = place.containingFile?.originalFile if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) { val useVFile = useFile.virtualFile val index = ProjectFileIndex.getInstance(useFile.project) if (useVFile == null || !index.isInLibrarySource(useVFile)) { if (targetFile != null && targetFile.isPhysical) { return checkAccess(targetFile, useFile, targetPackageName, quick) } else if (useVFile != null) { val target = JavaPsiFacade.getInstance(useFile.project).findPackage(targetPackageName) if (target != null) { val module = index.getModuleForFile(useVFile) if (module != null) { val test = index.isInTestSourceContent(useVFile) val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test)) if (dirs.isEmpty()) { return if (quick) ERR else ErrorWithFixes(JavaErrorMessages.message("package.not.found", target.qualifiedName)) } val error = checkAccess(dirs[0], useFile, target.qualifiedName, quick) return when { error == null -> null dirs.size == 1 -> error dirs.asSequence().drop(1).any { checkAccess(it, useFile, target.qualifiedName, true) == null } -> null else -> error } } } } } } return null } private val ERR = ErrorWithFixes("-") private fun checkAccess(target: PsiFileSystemItem, place: PsiFileSystemItem, packageName: String, quick: Boolean): ErrorWithFixes? { val targetModule = JavaModuleGraphUtil.findDescriptorByElement(target) val useModule = JavaModuleGraphUtil.findDescriptorByElement(place) if (targetModule != null) { if (targetModule == useModule) { return null } val targetName = targetModule.name val useName = useModule?.name ?: "ALL-UNNAMED" val module = place.virtualFile?.let { ProjectFileIndex.getInstance(place.project).getModuleForFile(it) } if (useModule == null) { val origin = targetModule.containingFile?.virtualFile if (origin == null || module == null || ModuleRootManager.getInstance(module).fileIndex.getOrderEntryForFile(origin) !is JdkOrderEntry) { return null // a target is not on the mandatory module path } val root = PsiJavaModuleReference.resolve(place, "java.se", false) if (!(root == null || JavaModuleGraphUtil.reads(root, targetModule) || inAddedModules(module, targetName) || hasUpgrade(module, targetName, packageName, place))) { return if (quick) ERR else ErrorWithFixes( JavaErrorMessages.message("module.access.not.in.graph", packageName, targetName), listOf(AddModulesOptionFix(module, targetName))) } } if (!(targetModule is LightJavaModule || JavaModuleGraphUtil.exports(targetModule, packageName, useModule) || module != null && inAddedExports(module, targetName, packageName, useName))) { if (quick) return ERR val fixes = when { packageName.isEmpty() -> emptyList() targetModule is PsiCompiledElement && module != null -> listOf(AddExportsOptionFix(module, targetName, packageName, useName)) targetModule !is PsiCompiledElement && useModule != null -> listOf(AddExportsDirectiveFix(targetModule, packageName, useName)) else -> emptyList() } return when (useModule) { null -> ErrorWithFixes(JavaErrorMessages.message("module.access.from.unnamed", packageName, targetName), fixes) else -> ErrorWithFixes(JavaErrorMessages.message("module.access.from.named", packageName, targetName, useName), fixes) } } if (useModule != null && !(targetName == PsiJavaModule.JAVA_BASE || JavaModuleGraphUtil.reads(useModule, targetModule))) { return when { quick -> ERR PsiNameHelper.isValidModuleName(targetName, useModule) -> ErrorWithFixes( JavaErrorMessages.message("module.access.does.not.read", packageName, targetName, useName), listOf(AddRequiresDirectiveFix(useModule, targetName))) else -> ErrorWithFixes(JavaErrorMessages.message("module.access.bad.name", packageName, targetName)) } } } else if (useModule != null) { return if (quick) ERR else ErrorWithFixes(JavaErrorMessages.message("module.access.to.unnamed", packageName, useModule.name)) } return null } private fun hasUpgrade(module: Module, targetName: String, packageName: String, place: PsiFileSystemItem): Boolean { if (PsiJavaModule.UPGRADEABLE.contains(targetName)) { val target = JavaPsiFacade.getInstance(module.project).findPackage(packageName) if (target != null) { val useVFile = place.virtualFile if (useVFile != null) { val index = ModuleRootManager.getInstance(module).fileIndex val test = index.isInTestSourceContent(useVFile) val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test)) return dirs.asSequence().any { index.getOrderEntryForFile(it.virtualFile) !is JdkOrderEntry } } } } return false } private fun inAddedExports(module: Module, targetName: String, packageName: String, useName: String): Boolean { val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module) if (options.isEmpty()) return false val prefix = "${targetName}/${packageName}=" return optionValues(options, "--add-exports") .filter { it.startsWith(prefix) } .map { it.substring(prefix.length) } .flatMap { it.splitToSequence(",") } .any { it == useName } } private fun inAddedModules(module: Module, moduleName: String): Boolean { val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module) return optionValues(options, "--add-modules") .flatMap { it.splitToSequence(",") } .any { it == moduleName || it == "ALL-SYSTEM" } } private fun optionValues(options: List<String>, name: String) = if (options.isEmpty()) emptySequence() else { var useValue = false options.asSequence() .map { when { it == name -> { useValue = true; "" } useValue -> { useValue = false; it } it.startsWith(name) && it[name.length] == '=' -> it.substring(name.length + 1) else -> "" } } .filterNot { it.isEmpty() } } private abstract class CompilerOptionFix(private val module: Module) : IntentionAction { override fun getFamilyName() = "dfd4a2c1-da18-4651-9aa8-d7d31cae10be" // random string; never visible override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = !module.isDisposed override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { if (isAvailable(project, editor, file)) { val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module).toMutableList() update(options) JavaCompilerConfigurationProxy.setAdditionalOptions(module.project, module, options) PsiManager.getInstance(project).dropPsiCaches() DaemonCodeAnalyzer.getInstance(project).restart() } } protected abstract fun update(options: MutableList<String>) override fun startInWriteAction() = true } private class AddExportsOptionFix(module: Module, targetName: String, packageName: String, private val useName: String) : CompilerOptionFix(module) { private val qualifier = "${targetName}/${packageName}" override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-exports=${qualifier}=${useName}") override fun update(options: MutableList<String>) { var idx = -1; var candidate = -1; var offset = 0 for ((i, option) in options.withIndex()) { if (option.startsWith("--add-exports")) { if (option.length == 13) { candidate = i + 1 ; offset = 0 } else if (option[13] == '=') { candidate = i; offset = 14 } } if (i == candidate && option.startsWith(qualifier, offset)) { val qualifierEnd = qualifier.length + offset if (option.length == qualifierEnd || option[qualifierEnd] == '=') { idx = i } } } when { idx == -1 -> options += "--add-exports=${qualifier}=${useName}" candidate == options.size -> options[idx - 1] = "--add-exports=${qualifier}=${useName}" else -> { val value = options[idx] options[idx] = if (value.endsWith('=') || value.endsWith(',')) value + useName else "${value},${useName}" } } } } private class AddModulesOptionFix(module: Module, private val moduleName: String) : CompilerOptionFix(module) { override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-modules=${moduleName}") override fun update(options: MutableList<String>) { var idx = -1 for ((i, option) in options.withIndex()) { if (option.startsWith("--add-modules")) { if (option.length == 13) idx = i + 1 else if (option[13] == '=') idx = i } } when (idx) { -1 -> options += "--add-modules=${moduleName}" options.size -> options[idx - 1] = "--add-modules=${moduleName}" else -> { val value = options[idx] options[idx] = if (value.endsWith('=') || value.endsWith(',')) value + moduleName else "${value},${moduleName}" } } } } }
apache-2.0
c0ae1bc8ee1c2c520eca36bce7f4246b
44.703846
151
0.668743
4.670597
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/common/SecondaryOutput.kt
1
1795
package net.ndrei.teslapoweredthingies.common import net.minecraft.block.Block import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraftforge.oredict.OreDictionary import net.ndrei.teslacorelib.utils.copyWithSize import java.util.* /** * Created by CF on 2017-06-30. */ interface IRecipeOutput { fun getOutput(): ItemStack fun getPossibleOutput(): ItemStack } interface IChancedRecipeOutput { val chance: Float } open class Output(private val stack: ItemStack) : IRecipeOutput { override fun getOutput() = this.stack.copy() override final fun getPossibleOutput() = this.stack.copy() } class SecondaryOutput(override val chance: Float, stack: ItemStack) : Output(stack), IChancedRecipeOutput { constructor(chance: Float, item: Item) : this(chance, ItemStack(item)) constructor(chance: Float, block: Block) : this(chance, ItemStack(block)) override fun getOutput(): ItemStack = if (this.chance >= Random().nextFloat()) super.getOutput() else ItemStack.EMPTY } open class OreOutput(val itemName: String, val quantity: Int) : IRecipeOutput { override fun getOutput(): ItemStack = this.getPossibleOutput() override final fun getPossibleOutput(): ItemStack { val stack = OreDictionary.getOres(this.itemName).firstOrNull() return stack?.copyWithSize(this.quantity) ?: ItemStack.EMPTY } } class SecondaryOreOutput(override val chance: Float, itemName: String, quantity: Int) : OreOutput(itemName, quantity), IChancedRecipeOutput { override fun getOutput(): ItemStack = if (this.chance >= Random().nextFloat()) super.getOutput() else ItemStack.EMPTY }
mit
af4663fc0618fef2cf424c179a787348
27.0625
85
0.687465
4.4875
false
false
false
false
TeamAmaze/AmazeFileManager
app/src/test/java/com/amaze/filemanager/filesystem/root/ListFilesCommandTest2.kt
1
5193
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem.root import android.content.SharedPreferences import android.os.Build.VERSION_CODES.JELLY_BEAN import android.os.Build.VERSION_CODES.KITKAT import android.os.Build.VERSION_CODES.P import androidx.preference.PreferenceManager import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.amaze.filemanager.exceptions.ShellCommandInvalidException import com.amaze.filemanager.fileoperations.filesystem.OpenMode import com.amaze.filemanager.filesystem.HybridFileParcelable import com.amaze.filemanager.shadows.ShadowMultiDex import com.amaze.filemanager.test.ShadowNativeOperations import com.amaze.filemanager.test.TestUtils import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants import com.topjohnwu.superuser.Shell import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.ArgumentMatchers.anyString import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import org.mockito.kotlin.argumentCaptor import org.robolectric.annotation.Config import java.io.InputStreamReader /** * Unit test for [ListFilesCommand]. This is to test the case when stat command fails. * * ls output is captured from busybox, and used as fixed outputs from mocked object * to ensure command output. * * FIXME: add toybox outputs, just to be sure? */ @RunWith(AndroidJUnit4::class) @Config( shadows = [ShadowMultiDex::class, ShadowNativeOperations::class], sdk = [JELLY_BEAN, KITKAT, P] ) class ListFilesCommandTest2 { val sharedPreferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext()) val lsLines = InputStreamReader(javaClass.getResourceAsStream("/rootCommands/ls-bin.txt")) .readLines() /** * test setup. */ @Before fun setUp() { val mockCommand = mock(ListFilesCommand.javaClass) `when`( mockCommand.listFiles( anyString(), anyBoolean(), anyBoolean(), argumentCaptor<(OpenMode) -> Unit>().capture(), argumentCaptor<(HybridFileParcelable) -> Unit>().capture() ) ).thenCallRealMethod() `when`( mockCommand.executeRootCommand( anyString(), anyBoolean(), anyBoolean() ) ).thenCallRealMethod() `when`(mockCommand.runShellCommand("pwd")).thenReturn( object : Shell.Result() { override fun getOut(): MutableList<String> = listOf("/").toMutableList() override fun getErr(): MutableList<String> = emptyList<String>().toMutableList() override fun getCode(): Int = 0 } ) `when`(mockCommand.runShellCommandToList("ls -l \"/bin\"")).thenReturn(lsLines) `when`( mockCommand.runShellCommandToList( "stat -c '%A %h %G %U %B %Y %N' /bin/*" ) ).thenThrow(ShellCommandInvalidException("Intentional exception")) TestUtils.replaceObjectInstance(ListFilesCommand.javaClass, mockCommand) } /** * Post test cleanup. */ @After fun tearDown() { TestUtils.replaceObjectInstance(ListFilesCommand.javaClass, null) } /** * Test command run. * * FIXME: Due to some (mysterious) limitations on mocking singletons, have to make both * conditions run in one go. */ @Test fun testCommandRun() { sharedPreferences.edit() .putBoolean(PreferencesConstants.PREFERENCE_ROOT_LEGACY_LISTING, false).commit() var statCount = 0 ListFilesCommand.listFiles("/bin", true, false, {}, { ++statCount }) assertEquals(lsLines.size - 1, statCount) sharedPreferences.edit() .putBoolean(PreferencesConstants.PREFERENCE_ROOT_LEGACY_LISTING, true).commit() var lsCount = 0 ListFilesCommand.listFiles("/bin", true, false, {}, { ++lsCount }) assertEquals(lsLines.size - 1, lsCount) } }
gpl-3.0
182e231bc8e6708048ff0ebd3b648f64
36.630435
107
0.6917
4.587456
false
true
false
false
facebook/flipper
android/src/main/java/com/facebook/flipper/plugins/uidebugger/descriptors/ObjectDescriptor.kt
1
1187
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.flipper.plugins.uidebugger.descriptors import android.graphics.Bitmap import com.facebook.flipper.plugins.uidebugger.model.Bounds import com.facebook.flipper.plugins.uidebugger.model.InspectableObject import com.facebook.flipper.plugins.uidebugger.model.MetadataId import com.facebook.flipper.plugins.uidebugger.util.Immediate object ObjectDescriptor : NodeDescriptor<Any> { override fun getActiveChild(node: Any): Any? = null override fun getName(node: Any): String { return node.javaClass.simpleName } override fun getQualifiedName(node: Any): String { return node::class.qualifiedName ?: "" } override fun getChildren(node: Any) = listOf<Any>() override fun getData(node: Any) = Immediate(mapOf<MetadataId, InspectableObject>()) override fun getBounds(node: Any): Bounds = Bounds(0, 0, 0, 0) override fun getTags(node: Any): Set<String> = setOf(BaseTags.Unknown) override fun getSnapshot(node: Any, bitmap: Bitmap?): Bitmap? = null }
mit
53a9afb0a1f9377f1c6c442c68735008
31.081081
85
0.757372
4.051195
false
false
false
false
LachlanMcKee/gsonpath
compiler/standard/src/main/java/gsonpath/adapter/standard/model/GsonObjectTreeFactory.kt
1
3286
package gsonpath.adapter.standard.model import gsonpath.ProcessingException import gsonpath.model.FieldInfo import java.util.regex.Pattern data class GsonTreeResult( val rootObject: GsonObject, val flattenedFields: List<GsonField> ) class GsonObjectTreeFactory(private val gsonObjectFactory: GsonObjectFactory) { @Throws(ProcessingException::class) fun createGsonObject( fieldInfoList: List<FieldInfo>, rootField: String, metadata: GsonObjectMetadata): GsonTreeResult { // Obtain the correct mapping structure beforehand. val absoluteRootObject = MutableGsonObject() val gsonPathObject = if (rootField.isNotEmpty()) { createGsonObjectFromRootField(absoluteRootObject, rootField, metadata.flattenDelimiter) } else { absoluteRootObject } for (fieldInfoIndex in fieldInfoList.indices) { gsonObjectFactory.addGsonType(gsonPathObject, fieldInfoList[fieldInfoIndex], fieldInfoIndex, metadata) } val immutableAbsoluteGsonObject = absoluteRootObject.toImmutable() val flattenedFields = getFlattenedFields(immutableAbsoluteGsonObject).sortedBy { it.fieldIndex } return GsonTreeResult(immutableAbsoluteGsonObject, flattenedFields) } private fun createGsonObjectFromRootField( rootObject: MutableGsonObject, rootField: String, flattenDelimiter: Char): MutableGsonObject { if (rootField.isEmpty()) { return rootObject } val regexSafeDelimiter = Pattern.quote(flattenDelimiter.toString()) val split = rootField.split(regexSafeDelimiter.toRegex()).dropLastWhile(String::isEmpty) if (split.isNotEmpty()) { // Keep adding branches to the tree and switching our root to the new branch. return split.fold(rootObject) { currentRoot, field -> val currentObject = MutableGsonObject() currentRoot.addObject(field, currentObject) return@fold currentObject } } else { // Add a single branch to the tree and return the new branch. val mapWithRoot = MutableGsonObject() rootObject.addObject(rootField, mapWithRoot) return mapWithRoot } } private fun getFlattenedFields(currentGsonObject: GsonObject): List<GsonField> { return currentGsonObject.entries() .flatMap { (_, gsonType) -> when (gsonType) { is GsonField -> listOf(gsonType) is GsonObject -> getFlattenedFields(gsonType) is GsonArray -> { gsonType.entries() .flatMap { (_, arrayGsonType) -> when (arrayGsonType) { is GsonField -> listOf(arrayGsonType) is GsonObject -> getFlattenedFields(arrayGsonType) } } } } } } }
mit
cbb1c4b7a181bed8d2c5e6061000852e
38.119048
114
0.580645
5.513423
false
false
false
false
vhromada/Catalog-REST
src/main/kotlin/cz/vhromada/catalog/rest/controller/SongController.kt
1
5412
package cz.vhromada.catalog.rest.controller import cz.vhromada.catalog.entity.Music import cz.vhromada.catalog.entity.Song import cz.vhromada.catalog.facade.SongFacade import cz.vhromada.common.web.controller.AbstractController import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController /** * A class represents controller for songs. * * @author Vladimir Hromada */ @RestController("songController") @RequestMapping("/catalog/music/{musicId}/songs") class SongController(private val songFacade: SongFacade) : AbstractController() { /** * Returns song with ID or null if there isn't such song. * <br></br> * Validation errors: * * * ID is null * * @param musicId music ID * @param songId song ID * @return song with ID or null if there isn't such song */ @GetMapping("/{songId}") fun getSong(@PathVariable("musicId") musicId: Int, @PathVariable("songId") songId: Int): Song? { return processResult(songFacade.get(songId)) } /** * Adds song. Sets new ID and position. * <br></br> * Validation errors: * * * Music ID is null * * Music doesn't exist in data storage * * Song ID isn't null * * Song position isn't null * * Name is null * * Name is empty string * * Length of song is negative value * * Note is null * * @param musicId music ID * @param song song */ @PutMapping("/add") @ResponseStatus(HttpStatus.CREATED) fun add(@PathVariable("musicId") musicId: Int, @RequestBody song: Song) { val music = Music(id = musicId, name = null, wikiEn = null, wikiCz = null, mediaCount = null, note = null, position = null) processResult(songFacade.add(music, song)) } /** * Updates song. * <br></br> * Validation errors: * * * ID isn't null * * Position is null * * Name is null * * Name is empty string * * Length of song is negative value * * Note is null * * Song doesn't exist in data storage * * @param musicId music ID * @param song new value of song */ @PostMapping("/update") fun update(@PathVariable("musicId") musicId: Int, @RequestBody song: Song) { processResult(songFacade.update(song)) } /** * Removes song. * <br></br> * Validation errors: * * * Song doesn't exist in song storage * * @param musicId music ID * @param id ID */ @DeleteMapping("/remove/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) fun remove(@PathVariable("musicId") musicId: Int, @PathVariable("id") id: Int) { val song = Song(id = id, name = null, length = null, note = null, position = null) processResult(songFacade.remove(song)) } /** * Duplicates song. * <br></br> * Validation errors: * * * ID is null * * Song doesn't exist in song storage * * @param musicId music ID * @param song song */ @PostMapping("/duplicate") @ResponseStatus(HttpStatus.CREATED) fun duplicate(@PathVariable("musicId") musicId: Int, @RequestBody song: Song) { processResult(songFacade.duplicate(song)) } /** * Moves song in list one position up. * <br></br> * Validation errors: * * * ID is null * * Song can't be moved up * * Song doesn't exist in song storage * * @param musicId music ID * @param song song */ @PostMapping("/moveUp") @ResponseStatus(HttpStatus.NO_CONTENT) fun moveUp(@PathVariable("musicId") musicId: Int, @RequestBody song: Song) { processResult(songFacade.moveUp(song)) } /** * Moves song in list one position down. * <br></br> * Validation errors: * * * ID is null * * Song can't be moved down * * Song doesn't exist in song storage * * @param musicId music ID * @param song song */ @PostMapping("/moveDown") @ResponseStatus(HttpStatus.NO_CONTENT) fun moveDown(@PathVariable("musicId") musicId: Int, @RequestBody song: Song) { processResult(songFacade.moveDown(song)) } /** * Returns list of songs for specified music. * <br></br> * Validation errors: * * * ID is null * * Music doesn't exist in data storage * * @param musicId music ID * @return list of songs for specified music */ @GetMapping fun findSongsByMusic(@PathVariable("musicId") musicId: Int): List<Song> { val music = Music(id = musicId, name = null, wikiEn = null, wikiCz = null, mediaCount = null, note = null, position = null) return processResult(songFacade.find(music))!! } }
mit
0a413fbd439d9c8bbae3d3bcd81604ac
28.736264
131
0.614745
4.118721
false
false
false
false
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/datastructures/NetworkResult.kt
1
2116
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham 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 com.thomas.needham.neurophidea.datastructures import org.jetbrains.annotations.NotNull import org.neuroph.core.NeuralNetwork import org.neuroph.core.learning.SupervisedTrainingElement import java.io.Serializable /** * Created by Thomas Needham on 05/06/2016. */ class NetworkResult : Serializable { var calculatedOutput: Array<Double> var expectedOutput: Array<Double> var deviance: Double companion object Output { var network: NeuralNetwork? = null var data: SupervisedTrainingElement? = null var networkInput: Array<Double> = arrayOf(0.0) var networkOutput: Array<Double> = arrayOf(0.0) } constructor(@NotNull net: NeuralNetwork?, @NotNull dat: SupervisedTrainingElement?, calculatedOutput: Array<Double>, expectedOutput: Array<Double>, deviance: Double) { network = net data = dat networkInput = dat?.input!!.toTypedArray() networkOutput = dat?.desiredOutput!!.toTypedArray() this.calculatedOutput = calculatedOutput this.expectedOutput = expectedOutput this.deviance = deviance } }
mit
03b9d14dc0557415b97364edb2cb5777
37.490909
168
0.786862
4.318367
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/migrations/MigrationsManagerImpl.kt
1
3839
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2020 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.migrations import androidx.annotation.MainThread import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.nextcloud.client.appinfo.AppInfo import com.nextcloud.client.core.AsyncRunner import com.nextcloud.client.migrations.MigrationsManager.Status internal class MigrationsManagerImpl( private val appInfo: AppInfo, private val migrationsDb: MigrationsDb, private val asyncRunner: AsyncRunner, private val migrations: Collection<Migrations.Step> ) : MigrationsManager { override val status: LiveData<Status> = MutableLiveData(Status.UNKNOWN) override val info: List<MigrationInfo> get() { val applied = migrationsDb.getAppliedMigrations() return migrations.map { MigrationInfo(id = it.id, description = it.description, applied = applied.contains(it.id)) } } @Throws(MigrationError::class) @Suppress("ReturnCount") override fun startMigration(): Int { if (migrationsDb.isFailed) { (status as MutableLiveData<Status>).value = Status.FAILED return 0 } if (migrationsDb.lastMigratedVersion >= appInfo.versionCode) { (status as MutableLiveData<Status>).value = Status.APPLIED return 0 } val applied = migrationsDb.getAppliedMigrations() val toApply = migrations.filter { !applied.contains(it.id) } if (toApply.isEmpty()) { onMigrationSuccess() return 0 } (status as MutableLiveData<Status>).value = Status.RUNNING asyncRunner.postQuickTask( task = { asyncApplyMigrations(toApply) }, onResult = { onMigrationSuccess() }, onError = { onMigrationFailed(it) } ) return toApply.size } /** * This method calls all pending migrations which can execute long-blocking code. * It should be run in a background thread. */ private fun asyncApplyMigrations(migrations: Collection<Migrations.Step>) { migrations.forEach { @Suppress("TooGenericExceptionCaught") // migration code is free to throw anything try { it.run.invoke(it) migrationsDb.addAppliedMigration(it.id) } catch (t: Throwable) { if (it.mandatory) { throw MigrationError(id = it.id, message = t.message ?: t.javaClass.simpleName) } } } } @MainThread private fun onMigrationFailed(error: Throwable) { val id = when (error) { is MigrationError -> error.id else -> -1 } migrationsDb.setFailed(id, error.message ?: error.javaClass.simpleName) (status as MutableLiveData<Status>).value = Status.FAILED } @MainThread private fun onMigrationSuccess() { migrationsDb.lastMigratedVersion = appInfo.versionCode (status as MutableLiveData<Status>).value = Status.APPLIED } }
gpl-2.0
44d192f20d60c921aa435b8e65e41a6a
35.913462
102
0.665017
4.693154
false
false
false
false
cbeust/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/archive/MetaArchive.kt
2
4120
package com.beust.kobalt.archive import com.beust.kobalt.Glob import com.beust.kobalt.misc.KFiles import org.apache.commons.compress.archivers.ArchiveEntry import org.apache.commons.compress.archivers.zip.ZipArchiveEntry import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream import java.io.Closeable import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.util.jar.Manifest import org.apache.commons.compress.archivers.zip.ZipFile as ApacheZipFile /** * Abstraction of a zip/jar/war archive that automatically manages the addition of expanded jar files. * Uses ZipArchiveOutputStream for fast inclusion of expanded jar files. */ class MetaArchive(outputFile: File, val manifest: Manifest?) : Closeable { companion object { const val MANIFEST_MF = "META-INF/MANIFEST.MF" } private val zos= ZipArchiveOutputStream(outputFile).apply { encoding = "UTF-8" } init { // If no manifest was passed, create an empty one so it's the first one in the archive val m = manifest ?: Manifest() val manifestFile = File.createTempFile("kobalt", "tmpManifest") addEntry(ZipArchiveEntry("META-INF/"), null) if (manifest != null) { FileOutputStream(manifestFile).use { fos -> m.write(fos) } } val entry = zos.createArchiveEntry(manifestFile, MetaArchive.MANIFEST_MF) addEntry(entry, FileInputStream(manifestFile)) } fun addFile(f: File, entryFile: File, path: String?) { maybeCreateParentDirectories(f) addFile2(f, entryFile, path) } private fun addFile2(f: File, entryFile: File, path: String?) { val file = f.normalize() FileInputStream(file).use { inputStream -> val actualPath = KFiles.fixSlashes(if (path != null) path + entryFile.path else entryFile.path) ZipArchiveEntry(actualPath).let { entry -> maybeCreateParentDirectories(File(actualPath)) maybeAddEntry(entry) { addEntry(entry, inputStream) } } } } private val createdDirs = hashSetOf<String>() /** * For an entry a/b/c/File, an entry needs to be created for each individual directory: * a/ * a/b/ * a/b/c * a/b/c/File */ private fun maybeCreateParentDirectories(file: File) { val toCreate = arrayListOf<String>() var current = file.parentFile while (current != null && current.path != ".") { if (!createdDirs.contains(current.path)) { toCreate.add(0, KFiles.fixSlashes(current) + "/") createdDirs.add(current.path) } current = current.parentFile } toCreate.forEach { dir -> addEntry(ZipArchiveEntry(dir), null) } } fun addArchive(jarFile: File) { ApacheZipFile(jarFile).use { jar -> val jarEntries = jar.entries for (entry in jarEntries) { maybeAddEntry(entry) { zos.addRawArchiveEntry(entry, jar.getRawInputStream(entry)) } } } } private fun okToAdd(name: String) : Boolean { val result = !KFiles.isExcluded(name, Glob("META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA", MANIFEST_MF)) // if (name.startsWith("META-INF")) println((if (result) "ADDING" else "NOT ADDING") + " $name") return result } override fun close() = zos.close() private fun addEntry(entry: ArchiveEntry, inputStream: FileInputStream?) { zos.putArchiveEntry(entry) inputStream?.use { ins -> ins.copyTo(zos, 50 * 1024) } zos.closeArchiveEntry() } private val seen = hashSetOf<String>() private fun maybeAddEntry(entry: ArchiveEntry, action:() -> Unit) { entry.name.let { name -> if (!seen.contains(name) && okToAdd(name)) { action() } seen.add(name) } } }
apache-2.0
1969231b38bd7eadc62e7aea07369646
31.96
107
0.607767
4.327731
false
false
false
false
goodwinnk/intellij-community
platform/lang-api/src/com/intellij/execution/configurations/LogFileOptions.kt
1
4294
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.configurations import com.intellij.openapi.components.BaseState import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.util.SmartList import com.intellij.util.containers.SmartHashSet import com.intellij.util.xmlb.Converter import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Tag import java.io.File import java.nio.charset.Charset import java.util.regex.Pattern /** * The information about a single log file displayed in the console when the configuration * is run. * * @since 5.1 */ @Tag("log_file") class LogFileOptions : BaseState { companion object { @JvmStatic fun collectMatchedFiles(root: File, pattern: Pattern, files: MutableList<File>) { val dirs = root.listFiles() ?: return dirs.filterTo(files) { pattern.matcher(it.name).matches() && it.isFile } } @JvmStatic fun areEqual(options1: LogFileOptions?, options2: LogFileOptions?): Boolean { return if (options1 == null || options2 == null) { options1 === options2 } else options1.name == options2.name && options1.pathPattern == options2.pathPattern && !options1.isShowAll == !options2.isShowAll && options1.isEnabled == options2.isEnabled && options1.isSkipContent == options2.isSkipContent } } @get:Attribute("alias") var name: String? by string() @get:Attribute(value = "path", converter = PathConverter::class) var pathPattern: String? by string() @get:Attribute("checked") var isEnabled: Boolean by property(true) @get:Attribute("skipped") var isSkipContent: Boolean by property(true) @get:Attribute("show_all") var isShowAll: Boolean by property(false) @get:Attribute(value = "charset", converter = CharsetConverter::class) var charset: Charset by property(Charset.defaultCharset()) fun getPaths(): Set<String> { val logFile = File(pathPattern!!) if (logFile.exists()) { return setOf(pathPattern!!) } val dirIndex = pathPattern!!.lastIndexOf(File.separator) if (dirIndex == -1) { return emptySet() } val files = SmartList<File>() collectMatchedFiles(File(pathPattern!!.substring(0, dirIndex)), Pattern.compile(FileUtil.convertAntToRegexp(pathPattern!!.substring(dirIndex + File.separator.length))), files) if (files.isEmpty()) { return emptySet() } if (isShowAll) { val result = SmartHashSet<String>() result.ensureCapacity(files.size) files.mapTo(result) { it.path } return result } else { var lastFile: File? = null for (file in files) { if (lastFile != null) { if (file.lastModified() > lastFile.lastModified()) { lastFile = file } } else { lastFile = file } } assert(lastFile != null) return setOf(lastFile!!.path) } } //read external constructor() @JvmOverloads constructor(name: String?, path: String?, enabled: Boolean = true, skipContent: Boolean = true, showAll: Boolean = false) : this(name, path, null, enabled, skipContent, showAll) @JvmOverloads constructor(name: String?, path: String?, charset: Charset?, enabled: Boolean = true, skipContent: Boolean = true, showAll: Boolean = false) { this.name = name pathPattern = path isEnabled = enabled isSkipContent = skipContent isShowAll = showAll this.charset = charset ?: Charset.defaultCharset() } fun setLast(last: Boolean) { isShowAll = !last } } private class PathConverter : Converter<String>() { override fun fromString(value: String) = FileUtilRt.toSystemDependentName(value) override fun toString(value: String) = FileUtilRt.toSystemIndependentName(value) } private class CharsetConverter : Converter<Charset>() { override fun fromString(value: String): Charset? { return try { Charset.forName(value) } catch (ignored: Exception) { Charset.defaultCharset() } } override fun toString(value: Charset) = value.name() }
apache-2.0
63f440e7154375f981c57ec82f6c96af
29.246479
179
0.676293
4.101242
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/login/LoginActivity.kt
1
1612
package de.xikolo.controllers.login import android.os.Bundle import android.view.Menu import android.view.MenuItem import com.yatatsu.autobundle.AutoBundleField import de.xikolo.R import de.xikolo.controllers.base.BaseActivity import de.xikolo.controllers.dialogs.CreateTicketDialog import de.xikolo.controllers.dialogs.CreateTicketDialogAutoBundle class LoginActivity : BaseActivity() { companion object { val TAG = LoginActivity::class.java.simpleName } @AutoBundleField(required = false) var token: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) title = null val tag = "login" val fragmentManager = supportFragmentManager if (fragmentManager.findFragmentByTag(tag) == null) { val transaction = fragmentManager.beginTransaction() transaction.replace(R.id.content, LoginFragmentAutoBundle.builder().token(token).build(), tag) transaction.commit() } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.helpdesk, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.action_helpdesk) { val dialog = CreateTicketDialogAutoBundle.builder().build() dialog.show(supportFragmentManager, CreateTicketDialog.TAG) return true } return super.onOptionsItemSelected(item) } }
bsd-3-clause
4799f1b4ddb2f70948b55b5a5dfa249e
31.24
106
0.699752
4.944785
false
false
false
false
hewking/HUILibrary
app/src/main/java/com/hewking/custom/util/RectFEx.kt
1
556
package com.hewking.custom.util import android.graphics.RectF /** * 项目名称:FlowChat * 类的描述: * 创建人员:hewking * 创建时间:2018/12/25 0025 * 修改人员:hewking * 修改时间:2018/12/25 0025 * 修改备注: * Version: 1.0.0 */ /** * 新值是之前值得scale倍数 */ fun RectF.scaleF(scale: Float) { if (scale != 1.0f) { top += top * (1 - scale) left += left * (1 - scale) right -= right * (1 - scale) bottom -= bottom * (1 - scale) } }
mit
0ebc3422e018d08a88fc4c71e44712e8
15.407407
38
0.523504
2.888889
false
false
false
false
ArdentDiscord/ArdentKotlin
src/main/kotlin/commands/statistics/StatisticsCommands.kt
1
12917
package commands.statistics import com.udojava.evalex.Expression import commands.music.getAudioManager import commands.music.getCurrentTime import events.Category import events.Command import events.ExtensibleCommand import main.* import translation.Language import translation.LanguageData import translation.tr import utils.discord.* import utils.functionality.* import utils.web.paste /* class MusicInfo : Command(Category.STATISTICS, "musicinfo", "see how many servers we're currently serving with music", "minfo") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { val embed = event.member!!.embed("Ardent | Music Status".tr(event), event.textChannel) embed.setThumbnail("https://yt3.ggpht.com/-zK8v1xKkZtY/AAAAAAAAAAI/AAAAAAAAAAA/SmyGR2XCwXw/s900-c-k-no-mo-rj-c0xffffff/photo.jpg") var total = 0 managers.forEachIndexed { index, id, manager -> val guild = getGuildById(id.toString()) if (manager.player.playingTrack != null && guild != null) { var lengthHours = 0.0 r.table("musicPlayed").filter(r.hashMap("guildId", guild.id)).run<Any>(conn).queryAsArrayList(LoggedTrack::class.java).forEach { if (it != null) lengthHours += it.position } embed.appendDescription((if (index % 2 == 0) Emoji.SMALL_ORANGE_DIAMOND else Emoji.SMALL_BLUE_DIAMOND).symbol + " " + ("**{0}**:\n" + " Now Playing: *{1}* {2}\n" + " Queue Length: *{3}*\n" + " Total playback: *{4} hours, {5} minutes*") .replace("{0}", guild.name) .replace("{1}", manager.player.playingTrack.info.title) .replace("{2}", manager.player.playingTrack.getCurrentTime()) .replace("{3}", manager.manager.queue.size.toString()) .replace("{4}", lengthHours.toInt().format()) .replace("{5}", lengthHours.toMinutes().format()) + "\n") total++ } } embed.appendDescription("\n" + "**Total Players Active**: {0}".replace("{0}", total.toString())) embed.appendDescription("\n\n" + "**" + "Total Music Played".tr(event) + ":** " + "{0} hours, {1} minutes".tr(event, internals.musicPlayed.toInt().format(), internals.musicPlayed.toMinutes())) embed.appendDescription("\n" + "**Total Tracks Played**: {0}".tr(event, internals.tracksPlayed.format())) event.channel.send(embed) } } class ServerLanguagesDistribution : Command(Category.STATISTICS, "serverlangs", "see how many Ardent servers are using which bot locale", "glangs", "slangs") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { var langs = hashMapOf<LanguageData, Int /* Usages */>() val guilds = r.table("guilds").run<Any>(conn).queryAsArrayList(GuildData::class.java) guilds.forEach { data -> if (data != null) { if (data.languageData == null) { data.languageData = Language.ENGLISH.data data.update() } if (langs.containsKey(data.languageData!!)) langs.increment(data.languageData!!) else langs.put(data.languageData!!, 1) } } langs = langs.sort(true) as HashMap<LanguageData, Int> val embed = event.member!!.embed("Ardent | Server Language".tr(event)) langs.forEachIndexed { index, l, usages -> embed.appendDescription((if (index % 2 == 0) Emoji.SMALL_BLUE_DIAMOND else Emoji.SMALL_ORANGE_DIAMOND).symbol + " **${l.readable}**: *$usages servers* (${"%.2f".format(usages * 100 / guilds.size.toFloat())}%)\n") } event.channel.send(embed) } override fun registerSubcommands() { } } class CalculateCommand : Command(Category.STATISTICS, "calculate", "evaluate a mathematical expression", "calculate", "calc") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { if (arguments.size == 0) event.channel.send("Please type an expression to evaluate. You can also use functions like **SQRT(NUMBER)** as defined at {0}" .tr(event, "<https://github.com/uklimaschewski/EvalEx#supported-functions>")) else { try { event.channel.send(Expression(arguments.concat()).eval().toPlainString()) } catch (e: Exception) { event.channel.send("The expression you entered is invalid!".tr(event)) } } } } class ShardInfo : Command(Category.STATISTICS, "shards", "see specific detail about each Ardent shard", "shar", "shard") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { val embed = event.member!!.embed("Ardent | Shard Information") jdas.forEach { jda -> embed.appendDescription("${Emoji.SMALL_BLUE_DIAMOND} __Shard **${jda.shardInfo.shardId}**__\n" + " Guilds: *${jda.guilds.size}*\n" + " Users: *${jda.users.size}*\n" + " Commands Received: *${factory.commandsByShard[jda.shardInfo.shardId] ?: "None"}*\n" + " Ping: *${jda.ping}* ms\n\n") } event.channel.send(embed) } } class CommandDistribution : Command(Category.STATISTICS, "distribution", "see how commands have been distributed on Ardent", "commanddistribution", "cdist") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { event.channel.sendMessage("Generating a command distribution overview could take up to **2** minutes... I'll delete this message once it's done".tr(event)).queue { val isOverall = !arguments.isEmpty() val data = if (arguments.size == 0) factory.commandsById.sort(true) else { val temp = hashMapOf<String, Int>() r.table("commands").run<Any>(conn).queryAsArrayList(LoggedCommand::class.java).forEach { if (it != null) if (temp.containsKey(it.commandId)) temp.increment(it.commandId) else temp.put(it.commandId, 1) } temp.sort(true) } val embed = event.member!!.embed((if (isOverall) "Ardent | Lifetime Command Distribution" else "Ardent | Current Session Command Distribution").tr(event)) embed.setThumbnail("https://www.wired.com/wp-content/uploads/blogs/magazine/wp-content/images/18-05/st_thompson_statistics_f.jpg") var total = 0 data.forEach { total += it.value } embed.appendDescription("Data generated from **{0}** individual entries".tr(event, total.format())) val iterator = data.iterator().withIndex() while (iterator.hasNext()) { val current = iterator.next() if (embed.descriptionBuilder.length >= 1900) { embed.appendDescription("\n\n" + "Type *{0}distribution all* to see the total command distribution".tr(event, event.guild.getPrefix())) event.channel.send(embed) embed.setDescription("") } else { embed.appendDescription("\n " + (if (current.index % 2 == 0) Emoji.SMALL_ORANGE_DIAMOND else Emoji.SMALL_BLUE_DIAMOND).symbol + " " + "{0}: **{1}**% ({2} commands) - [**{3}**]".tr(event, current.value.key, "%.2f".format(current.value.value * 100 / total.toFloat()), current.value.value.format(), "#" + (current.index + 1).toString())) } } if (embed.descriptionBuilder.isNotEmpty()) { embed.appendDescription("\n\n" + "Type *{0}distribution all* to see the total command distribution".tr(event, event.guild.getPrefix())) event.channel.send(embed) } it.delete().queue() } } } class GetGuilds : Command(Category.STATISTICS, "guilds", "getWithIndex a hastebin paste of servers", "servers") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { val builder = StringBuilder().append("Ardent Server Data, collected at ${System.currentTimeMillis().readableDate()}\n\n") getAllGuilds().sortedByDescending { it.members.size }.forEach { guild -> builder.append("${guild.name} - ${guild.members.size} members & ${guild.botSize()} bots\n") } event.channel.send("Click the following link to see server data:".tr(event) + " ${paste(builder.toString().removeSuffix("\n"))}") } override fun registerSubcommands() { } } class MutualGuilds : Command(Category.STATISTICS, "mutualguilds", "getWithIndex a list of servers I'm in with a specified user", "mutualservers") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { val user = if (event.message.mentionedUsers.size == 0) event.author else event.message.mentionedUsers[0] if (user.id == "339101087569281045") event.channel.send("Nice try :-)".tr(event)) val embed = event.member!!.embed("Ardent | Mutual Servers with ${user.name}") mutualGuildsWith(user).forEachIndexed { index, guild -> if (embed.descriptionBuilder.length < 1900) embed.appendDescription("${(if (index % 2 == 0) Emoji.SMALL_ORANGE_DIAMOND else Emoji.SMALL_BLUE_DIAMOND).symbol} " + "**${guild.name}** - *${guild.members.size}* members, *${guild.members.filter { it.user.isBot }.count() * 100 / guild.members.size}*% bots\n") else { if (!embed.descriptionBuilder.endsWith("...")) embed.appendDescription("...") } } event.channel.send(embed) } } class AudioAnalysisCommand : ExtensibleCommand(Category.STATISTICS, "trackanalysis", "see an audio feature analysis for tracks", "audioanalysis") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { showHelp(event) } override fun registerSubcommands() { with("current", null, "see an analysis for the currently playing track", { arguments, event -> val playing = event.guild.getAudioManager(event.textChannel).player.playingTrack if (playing == null) event.channel.send("There isn't a currently playing track..".tr(event)) else { val embed = getAnalysis(playing.info.title, event) if (embed != null) event.channel.send(embed) } }) with("search", null, "see an analysis for the specified search term", { arguments, event -> if (arguments.size == 0) event.channel.send("You need a search term!".tr(event)) else { val embed = getAnalysis(arguments.concat(), event) if (embed != null) event.channel.send(embed) } }) } private fun getAnalysis(trackName: String, event: MessageReceivedEvent): EmbedBuilder? { try { val track = spotifyApi.search.searchTrack(trackName, 1).items[0] val features = spotifyApi.tracks.getAudioFeatures(track.id) return event.member!!.embed("Audio Analysis | {0}".tr(event, track.name), event.textChannel) .addField("Acousticness", features.acousticness.times(100).format() + "%", true) .addField("Energy", features.energy.times(100).format() + "%", true) .addField("Liveness", features.liveness.times(100).format() + "%", true) .addField("Danceability", features.danceability.times(100).format() + "%", true) .addField("Instrumentalness", features.instrumentalness.times(100).format() + "%", true) .addField("Loudness", features.loudness.times(100).format() + "%", true) .addField("Speechiness", features.speechiness.times(100).format() + "%", true) .addField("Valence", features.valence.times(100).format() + "%", true) .addField("Tempo", features.tempo.format() + " bpm", true) .addField("Duration", features.duration_ms.toLong().toMinutesAndSeconds(), true) .addField("Track Link", "https://open.spotify.com/track/${features.id}", true) .addField("Analysis URL", features.analysis_url, true) } catch (e: Exception) { event.channel.send("A track wasn't found by the name of **{0}**!".tr(event, trackName)) } return null } } */
apache-2.0
fcbf445c01dfb594d0bfa1705999cc0b
58.529954
236
0.598746
4.247616
false
false
false
false
ryanmhoffman/BibleWrap
src/main/kotlin/Bible.kt
1
651
/** * Created by RMH on 1/1/18. */ class Bible(){ // Required fields. /** * The chronological number of the book. */ private var bookNumber: Int = 0 /** * The name of the book. */ private var bookName: String = "" /** * The total number of chapters in the book. */ private var numberOfChapters: Int = 0 fun setBookNumber(number: Int) { bookNumber = number } fun setBookName(name: String) { bookName = name } fun setNumberOfChapters(chapters: Int) { numberOfChapters = chapters } fun getBookNumber(): Int = bookNumber fun getBookName(): String = bookName fun getNumberOfChapters(): Int = numberOfChapters }
mit
8611221e2c0932b23a1e5024f62be418
15.3
50
0.663594
3.390625
false
false
false
false
RocketChat/Rocket.Chat.Android.Lily
app/src/main/java/chat/rocket/android/directory/adapter/DirectoryAdapter.kt
2
4055
package chat.rocket.android.directory.adapter import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import chat.rocket.android.R import chat.rocket.android.directory.uimodel.DirectoryUiModel import chat.rocket.android.util.extensions.inflate private const val VIEW_TYPE_CHANNELS = 0 private const val VIEW_TYPE_USERS = 1 private const val VIEW_TYPE_GLOBAL_USERS = 2 class DirectoryAdapter(private val selector: Selector) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var isSortByChannels: Boolean = true private var isSearchForGlobalUsers: Boolean = true private var dataSet: List<DirectoryUiModel> = ArrayList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = when (viewType) { VIEW_TYPE_CHANNELS -> DirectoryChannelViewHolder( parent.inflate(R.layout.item_directory_channel) ) VIEW_TYPE_USERS -> DirectoryUsersViewHolder( parent.inflate(R.layout.item_directory_user) ) VIEW_TYPE_GLOBAL_USERS -> DirectoryGlobalUsersViewHolder( parent.inflate(R.layout.item_directory_user) ) else -> throw IllegalStateException("viewType must be either VIEW_TYPE_CHANNELS, VIEW_TYPE_USERS or VIEW_TYPE_GLOBAL_USERS") } override fun getItemCount(): Int = dataSet.size override fun getItemViewType(position: Int): Int { return if (isSortByChannels) { VIEW_TYPE_CHANNELS } else { if (isSearchForGlobalUsers) { VIEW_TYPE_GLOBAL_USERS } else { VIEW_TYPE_USERS } } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) = when (holder) { is DirectoryChannelViewHolder -> bindDirectoryChannelViewHolder(holder, position) is DirectoryUsersViewHolder -> bindDirectoryUsersViewHolder(holder, position) is DirectoryGlobalUsersViewHolder -> bindDirectoryGlobalUsersViewHolder( holder, position ) else -> throw IllegalStateException("Unable to bind ViewHolder. ViewHolder must be either DirectoryChannelViewHolder, DirectoryUsersViewHolder or DirectoryGlobalUsersViewHolder") } private fun bindDirectoryChannelViewHolder(holder: DirectoryChannelViewHolder, position: Int) { with(dataSet[position]) { holder.bind(this) holder.itemView.setOnClickListener { selector.onChannelSelected(id, name) } } } private fun bindDirectoryUsersViewHolder(holder: DirectoryUsersViewHolder, position: Int) { with(dataSet[position]) { holder.bind(this) holder.itemView.setOnClickListener { selector.onUserSelected(username, name) } } } private fun bindDirectoryGlobalUsersViewHolder( holder: DirectoryGlobalUsersViewHolder, position: Int ) { with(dataSet[position]) { holder.bind(this) holder.itemView.setOnClickListener { selector.onGlobalUserSelected(username, name) } } } fun clearData() { dataSet = emptyList() notifyDataSetChanged() } fun setSorting(isSortByChannels: Boolean, isSearchForGlobalUsers: Boolean) { this.isSortByChannels = isSortByChannels this.isSearchForGlobalUsers = isSearchForGlobalUsers } fun prependData(dataSet: List<DirectoryUiModel>) { this.dataSet = dataSet notifyItemRangeInserted(0, dataSet.size) } fun appendData(dataSet: List<DirectoryUiModel>) { val previousDataSetSize = this.dataSet.size this.dataSet += dataSet notifyItemRangeInserted(previousDataSetSize, dataSet.size) } } interface Selector { fun onChannelSelected(channelId: String, channelName: String) fun onUserSelected(username: String, name: String) fun onGlobalUserSelected(username: String, name: String) }
mit
bc679879c1bd8d48a08f6488e3517667
36.555556
190
0.679655
4.921117
false
false
false
false
Cleverdesk/cleverdesk
src/main/java/net/cleverdesk/cleverdesk/plugin/PluginLoader.kt
1
3906
/** * 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.plugin import net.cleverdesk.cleverdesk.launcher.Launcher import java.io.File import java.io.FilenameFilter import java.net.URL import java.net.URLClassLoader import java.util.* import java.util.jar.JarEntry import java.util.jar.JarFile class PluginLoader { public fun loadPlugins(launcher: Launcher): List<Plugin> { return loadPlugins(launcher, "plugins") } public fun loadPlugins(launcher: Launcher, suffix: String): List<Plugin> { val plugin_folder = File(launcher.dataFolder, "${suffix}/") println("Loading plugins from ${plugin_folder.absolutePath}") val plugins: MutableList<Plugin> = LinkedList<Plugin>() for (jar_name: String in plugin_folder.list(FilenameFilter { file, name -> name.endsWith(".jar", true) })) { println("Found ${jar_name}") val jar: JarFile = JarFile(File(plugin_folder, jar_name)) val entries: Enumeration<JarEntry> = jar.entries() val urls: Array<URL> = arrayOf(URL("jar:file:${File(plugin_folder, jar_name).absolutePath}!/")) println("-> ${urls}") val cl: URLClassLoader = URLClassLoader.newInstance(urls) val classes: HashMap<String, Class<*>> = LinkedHashMap(); var plugin: Plugin? = null while (entries.hasMoreElements()) { val entry: JarEntry = entries.nextElement() if (entry.isDirectory || !entry.name.endsWith(".class")) { continue } var className = entry.name.substring(0, entry.name.length - 6) className = className.replace('/', '.') val c: Class<*> = cl.loadClass(className) classes.put(className, c) println("Loading: ${c.name}") if (Plugin::class.java.isAssignableFrom(c)) { if (plugin != null) { continue } println("Found Plugin-Instance: ${c.name}") plugin = c.newInstance() as Plugin } if (plugin == null) { continue } var plInfo: PluginInfo? = null for (anno in plugin.javaClass.annotations) { if (anno is PluginInfo) { plInfo = anno as PluginInfo } } if (plInfo == null) { println("Error can't find @PluginInfo") continue } plugin!!.description = object : PluginDescription { override val name: String get() = (plInfo as PluginInfo).name override val description: String get() = (plInfo as PluginInfo).description override val author: String get() = (plInfo as PluginInfo).author } plugin!!.launcher = launcher println("Loaded ${(plugin.description as PluginDescription).name}") plugins.add(plugin) } } return plugins } }
gpl-3.0
166762388c496ac333eb4ea125e1bf98
33.883929
116
0.561444
5.00128
false
false
false
false
alexcustos/linkasanote
app/src/main/java/com/bytesforge/linkasanote/manageaccounts/ManageAccountsFragment.kt
1
10342
/* * LaaNo Android application * * @author Aleksandr Borisenko <[email protected]> * Copyright (C) 2017 Aleksandr Borisenko * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.bytesforge.linkasanote.manageaccounts import android.accounts.* import android.app.Activity import android.app.Dialog import android.content.DialogInterface import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Handler import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.VisibleForTesting import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bytesforge.linkasanote.R import com.bytesforge.linkasanote.addeditaccount.AddEditAccountActivity import com.bytesforge.linkasanote.addeditaccount.nextcloud.NextcloudFragment import com.bytesforge.linkasanote.databinding.FragmentManageAccountsBinding import com.bytesforge.linkasanote.settings.Settings import com.bytesforge.linkasanote.utils.CloudUtils import com.google.android.material.snackbar.Snackbar import io.reactivex.Single import java.io.IOException import java.util.* class ManageAccountsFragment : Fragment(), ManageAccountsContract.View { @get:VisibleForTesting var presenter: ManageAccountsContract.Presenter? = null private set private var adapter: AccountsAdapter? = null private var binding: FragmentManageAccountsBinding? = null private var accountManager: AccountManager? = null override fun onResume() { super.onResume() presenter!!.subscribe() } override fun onPause() { super.onPause() presenter!!.unsubscribe() } override val isActive: Boolean get() = isAdded override fun setPresenter(presenter: ManageAccountsContract.Presenter) { this.presenter = presenter } override fun setAccountManager(accountManager: AccountManager) { this.accountManager = accountManager } override fun finishActivity() { requireActivity().onBackPressed() } override fun cancelActivity() { requireActivity().setResult(Activity.RESULT_CANCELED) requireActivity().finish() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { presenter!!.result(requestCode, resultCode) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentManageAccountsBinding.inflate(inflater, container, false) // RecyclerView setupAccountsRecyclerView(binding!!.rvAccounts) return binding!!.root } private fun setupAccountsRecyclerView(rvAccounts: RecyclerView) { val accountItems: MutableList<AccountItem> = ArrayList() adapter = AccountsAdapter((presenter as ManageAccountsPresenter?)!!, accountItems) rvAccounts.adapter = adapter val layoutManager = LinearLayoutManager(context) rvAccounts.layoutManager = layoutManager val dividerItemDecoration = DividerItemDecoration( rvAccounts.context, layoutManager.orientation ) rvAccounts.addItemDecoration(dividerItemDecoration) } override fun loadAccountItems(): Single<List<AccountItem>> { return Single.fromCallable { val accounts = accountsWithPermissionCheck ?: throw NullPointerException("Required permission was not granted") val accountItems: MutableList<AccountItem> = LinkedList() for (account in accounts) { val accountItem = CloudUtils.getAccountItem(account, requireContext()) accountItems.add(accountItem) } if (Settings.GLOBAL_MULTIACCOUNT_SUPPORT || accounts.isEmpty()) { accountItems.add(AccountItem()) } accountItems } } override fun showNotEnoughPermissionsSnackbar() { Snackbar.make( binding!!.rvAccounts, R.string.snackbar_no_permission, Snackbar.LENGTH_LONG ) .addCallback(object : Snackbar.Callback() { override fun onDismissed(transientBottomBar: Snackbar, event: Int) { super.onDismissed(transientBottomBar, event) cancelActivity() } }).show() } override fun showSuccessfullyUpdatedSnackbar() { Snackbar.make( binding!!.rvAccounts, R.string.manage_accounts_account_updated, Snackbar.LENGTH_SHORT ).show() } override fun addAccount() { accountManager!!.addAccount( CloudUtils.getAccountType(requireContext()), null, null, null, activity, addAccountCallback, handler ) } override fun editAccount(account: Account?) { val updateAccountIntent = Intent(context, AddEditAccountActivity::class.java) val requestCode = AddEditAccountActivity.REQUEST_UPDATE_NEXTCLOUD_ACCOUNT updateAccountIntent.putExtra(NextcloudFragment.ARGUMENT_EDIT_ACCOUNT_ACCOUNT, account) updateAccountIntent.putExtra(AddEditAccountActivity.ARGUMENT_REQUEST_CODE, requestCode) startActivityForResult(updateAccountIntent, requestCode) } override fun confirmAccountRemoval(account: Account) { val dialog = AccountRemovalConfirmationDialog.newInstance(account) dialog.setTargetFragment(this, AccountRemovalConfirmationDialog.DIALOG_REQUEST_CODE) val fragmentManager = parentFragmentManager dialog.show( fragmentManager, AccountRemovalConfirmationDialog.DIALOG_TAG ) } fun removeAccount(account: Account?) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { accountManager!!.removeAccount(account, activity, removeAccountCallback, handler) } else { accountManager!!.removeAccount(account, removeAccountCallbackCompat, handler) } } class AccountRemovalConfirmationDialog : DialogFragment() { private var account: Account? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) account = requireArguments().getParcelable(ARGUMENT_REMOVAL_CONFIRMATION_ACCOUNT) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return AlertDialog.Builder(requireContext()) .setTitle(R.string.manage_accounts_removal_confirmation_title) .setMessage( resources.getString( R.string.manage_accounts_removal_confirmation_message, account!!.name ) ) .setIcon(R.drawable.ic_warning) .setPositiveButton(R.string.dialog_button_delete) { dialog: DialogInterface?, which: Int -> (targetFragment as ManageAccountsFragment?)!!.removeAccount( account ) } .setNegativeButton(R.string.dialog_button_cancel, null) .create() } companion object { private const val ARGUMENT_REMOVAL_CONFIRMATION_ACCOUNT = "ACCOUNT" const val DIALOG_TAG = "ACCOUNT_REMOVAL_CONFIRMATION" const val DIALOG_REQUEST_CODE = 0 fun newInstance(account: Account): AccountRemovalConfirmationDialog { val args = Bundle() args.putParcelable(ARGUMENT_REMOVAL_CONFIRMATION_ACCOUNT, account) val dialog = AccountRemovalConfirmationDialog() dialog.arguments = args return dialog } } } private val removeAccountCallback = AccountManagerCallback { future: AccountManagerFuture<Bundle?> -> if (future.isDone) { // NOTE: sync successfully completes if account is removed in the middle presenter!!.loadAccountItems(true) } } private val removeAccountCallbackCompat = AccountManagerCallback { future: AccountManagerFuture<Boolean?> -> if (future.isDone) { presenter!!.loadAccountItems(true) } } private val addAccountCallback = AccountManagerCallback { future: AccountManagerFuture<Bundle?> -> try { future.result // NOTE: see exceptions presenter!!.loadAccountItems(true) } catch (e: OperationCanceledException) { Log.d(TAG, "Account creation canceled") } catch (e: IOException) { Log.e(TAG, "Account creation finished with an exception", e) } catch (e: AuthenticatorException) { Log.e(TAG, "Account creation finished with an exception", e) } } override val accountsWithPermissionCheck: Array<Account>? get() = CloudUtils.getAccountsWithPermissionCheck(requireContext(), accountManager!!) override fun swapItems(accountItems: List<AccountItem>) { adapter!!.swapItems(accountItems) } companion object { private val TAG = ManageAccountsFragment::class.java.simpleName private val handler = Handler() fun newInstance(): ManageAccountsFragment { return ManageAccountsFragment() } } }
gpl-3.0
8322853fa627c686cd0bdb2ab3b2cab7
37.737828
107
0.669986
5.330928
false
false
false
false
exponent/exponent
packages/expo-image-manipulator/android/src/main/java/expo/modules/imagemanipulator/actions/CropAction.kt
2
1160
package expo.modules.imagemanipulator.actions import android.graphics.Bitmap private const val KEY_ORIGIN_X = "originX" private const val KEY_ORIGIN_Y = "originY" private const val KEY_WIDTH = "width" private const val KEY_HEIGHT = "height" class CropAction(private val originX: Int, private val originY: Int, private val width: Int, private val height: Int) : Action { override fun run(bitmap: Bitmap): Bitmap { require( originX <= bitmap.width && originY <= bitmap.height && originX + width <= bitmap.width && originY + height <= bitmap.height ) { "Invalid crop options have been passed. Please make sure the requested crop rectangle is inside source image." } return Bitmap.createBitmap(bitmap, originX, originY, width, height) } companion object { fun fromObject(o: Any): CropAction { require(o is Map<*, *>) val originX = (o[KEY_ORIGIN_X] as Double).toInt() val originY = (o[KEY_ORIGIN_Y] as Double).toInt() val width = (o[KEY_WIDTH] as Double).toInt() val height = (o[KEY_HEIGHT] as Double).toInt() return CropAction(originX, originY, width, height) } } }
bsd-3-clause
dd47226b40daf42008b3bf74d763a280
36.419355
128
0.675
3.905724
false
false
false
false
AndroidX/androidx
lint-checks/src/main/java/androidx/build/lint/SampledAnnotationDetector.kt
3
16122
/* * 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. */ @file:Suppress("UnstableApiUsage") package androidx.build.lint import androidx.build.lint.SampledAnnotationDetector.Companion.INVALID_SAMPLES_LOCATION import androidx.build.lint.SampledAnnotationDetector.Companion.MULTIPLE_FUNCTIONS_FOUND import androidx.build.lint.SampledAnnotationDetector.Companion.OBSOLETE_SAMPLED_ANNOTATION import androidx.build.lint.SampledAnnotationDetector.Companion.SAMPLED_ANNOTATION import androidx.build.lint.SampledAnnotationDetector.Companion.SAMPLED_ANNOTATION_FQN import androidx.build.lint.SampledAnnotationDetector.Companion.SAMPLED_FUNCTION_MAP import androidx.build.lint.SampledAnnotationDetector.Companion.SAMPLES_DIRECTORY import androidx.build.lint.SampledAnnotationDetector.Companion.SAMPLE_KDOC_ANNOTATION import androidx.build.lint.SampledAnnotationDetector.Companion.SAMPLE_LINK_MAP import androidx.build.lint.SampledAnnotationDetector.Companion.UNRESOLVED_SAMPLE_LINK import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Context import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Incident import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.LintMap import com.android.tools.lint.detector.api.Location import com.android.tools.lint.detector.api.PartialResult import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import org.jetbrains.kotlin.backend.jvm.ir.psiElement import org.jetbrains.kotlin.descriptors.MemberDescriptor import org.jetbrains.kotlin.kdoc.psi.api.KDoc import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.KtPropertyAccessor import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.multiplatform.ExpectedActualResolver import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.UMethod import org.jetbrains.uast.kotlin.KotlinUastResolveProviderService /** * Detector responsible for enforcing @Sampled annotation usage * * This detector enforces that: * * - Functions referenced with @sample are annotated with @Sampled - [UNRESOLVED_SAMPLE_LINK] * - Functions annotated with @Sampled are referenced with @sample - [OBSOLETE_SAMPLED_ANNOTATION] * - Functions annotated with @Sampled are inside a valid samples directory, matching module / * directory structure guidelines - [INVALID_SAMPLES_LOCATION] * - There are never multiple functions with the same fully qualified name that could be resolved * by an @sample link - [MULTIPLE_FUNCTIONS_FOUND] */ class SampledAnnotationDetector : Detector(), SourceCodeScanner { override fun getApplicableUastTypes() = listOf(UDeclaration::class.java) override fun createUastHandler(context: JavaContext) = object : UElementHandler() { override fun visitDeclaration(node: UDeclaration) { KDocSampleLinkHandler(context).visitDeclaration(node) if (node is UMethod) { SampledAnnotationHandler(context).visitMethod(node) } } } override fun checkPartialResults(context: Context, partialResults: PartialResult) { val sampleLinks = mutableMapOf<String, MutableList<Location>>() val sampledFunctions = mutableMapOf<String, MutableList<Location>>() partialResults.maps().forEach { map -> map.getMap(SAMPLE_LINK_MAP)?.run { iterator().forEach { key -> sampleLinks.getOrPut(key) { mutableListOf() }.add(getLocation(key)!!) } } map.getMap(SAMPLED_FUNCTION_MAP)?.run { iterator().forEach { key -> sampledFunctions.getOrPut(key) { mutableListOf() }.add(getLocation(key)!!) } } } // Only report errors on the sample module if (context.project.name != "samples") return /** * Returns whether this [Location] represents a file that we want to report errors for. We * only want to report an error for files in the parent module of this samples module, to * avoid reporting the same errors multiple times if multiple sample modules depend * on a library that has @sample links. */ fun Location.shouldReport(): Boolean { // Path of the parent module that the sample module has samples for val sampleParentPath = context.project.dir.parentFile.toPath().toRealPath() val locationPath = file.toPath().toRealPath() return locationPath.startsWith(sampleParentPath) } sampleLinks.forEach { (link, locations) -> val functionLocations = sampledFunctions[link] when { functionLocations == null -> { locations.forEach { location -> if (location.shouldReport()) { val incident = Incident(context) .issue(UNRESOLVED_SAMPLE_LINK) .location(location) .message("Couldn't find a valid @Sampled function matching $link") context.report(incident) } } } // This probably should never happen, but theoretically there could be multiple // samples with the same FQN across separate sample projects, so check here as well. functionLocations.size > 1 -> { locations.forEach { location -> if (location.shouldReport()) { val incident = Incident(context) .issue(MULTIPLE_FUNCTIONS_FOUND) .location(location) .message("Found multiple functions matching $link") context.report(incident) } } } } } sampledFunctions.forEach { (link, locations) -> if (sampleLinks[link] == null) { locations.forEach { location -> if (location.shouldReport()) { val incident = Incident(context) .issue(OBSOLETE_SAMPLED_ANNOTATION) .location(location) .message("$link is annotated with @$SAMPLED_ANNOTATION, but is not " + "linked to from a @$SAMPLE_KDOC_ANNOTATION tag.") context.report(incident) } } } } } companion object { // The name of the @sample tag in KDoc const val SAMPLE_KDOC_ANNOTATION = "sample" // The name of the @Sampled annotation that samples must be annotated with const val SAMPLED_ANNOTATION = "Sampled" const val SAMPLED_ANNOTATION_FQN = "androidx.annotation.$SAMPLED_ANNOTATION" // The name of the samples directory inside a project const val SAMPLES_DIRECTORY = "samples" const val SAMPLE_LINK_MAP = "SampleLinkMap" const val SAMPLED_FUNCTION_MAP = "SampledFunctionMap" val OBSOLETE_SAMPLED_ANNOTATION = Issue.create( id = "ObsoleteSampledAnnotation", briefDescription = "Obsolete @$SAMPLED_ANNOTATION annotation", explanation = "This function is annotated with @$SAMPLED_ANNOTATION, but is not " + "linked to from a @$SAMPLE_KDOC_ANNOTATION tag. Either remove this annotation, " + "or add a valid @$SAMPLE_KDOC_ANNOTATION tag linking to it.", category = Category.CORRECTNESS, priority = 5, severity = Severity.ERROR, implementation = Implementation( SampledAnnotationDetector::class.java, Scope.JAVA_FILE_SCOPE ) ) val UNRESOLVED_SAMPLE_LINK = Issue.create( id = "UnresolvedSampleLink", briefDescription = "Unresolved @$SAMPLE_KDOC_ANNOTATION annotation", explanation = "Couldn't find a valid @Sampled function matching the function " + "specified in the $SAMPLE_KDOC_ANNOTATION link. If there is a function with the " + "same fully qualified name, make sure it is annotated with @Sampled.", category = Category.CORRECTNESS, priority = 5, severity = Severity.ERROR, implementation = Implementation( SampledAnnotationDetector::class.java, Scope.JAVA_FILE_SCOPE ) ) val MULTIPLE_FUNCTIONS_FOUND = Issue.create( id = "MultipleSampledFunctions", briefDescription = "Multiple matching functions found", explanation = "Found multiple functions matching the $SAMPLE_KDOC_ANNOTATION link.", category = Category.CORRECTNESS, priority = 5, severity = Severity.ERROR, implementation = Implementation( SampledAnnotationDetector::class.java, Scope.JAVA_FILE_SCOPE ) ) val INVALID_SAMPLES_LOCATION = Issue.create( id = "InvalidSamplesLocation", briefDescription = "Invalid samples location", explanation = "This function is annotated with @$SAMPLED_ANNOTATION, but is not " + "inside a project/directory named $SAMPLES_DIRECTORY.", category = Category.CORRECTNESS, priority = 5, severity = Severity.ERROR, implementation = Implementation( SampledAnnotationDetector::class.java, Scope.JAVA_FILE_SCOPE ) ) } } /** * Handles KDoc with @sample links * * Checks KDoc in all applicable UDeclarations - this includes classes, functions, fields... */ private class KDocSampleLinkHandler(private val context: JavaContext) { fun visitDeclaration(node: UDeclaration) { val source = node.sourcePsi // TODO: remove workaround when https://youtrack.jetbrains.com/issue/KTIJ-19043 is fixed if (source is KtPropertyAccessor) { source.property.docComment?.let { handleSampleLink(it) } } else { node.comments .mapNotNull { it.sourcePsi as? KDoc } .forEach { handleSampleLink(it) } // Expect declarations are not visible in UAST, but they may have sample links on them. // If we are looking at an actual declaration, also manually find the corresponding // expect declaration for analysis. if ((source as? KtModifierListOwner)?.hasActualModifier() == true) { val service = node.project.getService(KotlinUastResolveProviderService::class.java) val member = service.getBindingContext(source) .get(BindingContext.DECLARATION_TO_DESCRIPTOR, source) as? MemberDescriptor // Should never be null since `actual` is only applicable to members ?: return val expected = ExpectedActualResolver.findExpectedForActual(member) ?: return // There may be multiple possible candidates, we want to check them all regardless. expected.values.toList().flatten().forEach { descriptor -> val element = descriptor.psiElement (element as? KtDeclaration)?.docComment?.let { handleSampleLink(it) } } } } } private fun handleSampleLink(kdoc: KDoc) { val sections: List<KDocSection> = kdoc.children.mapNotNull { it as? KDocSection } // map of a KDocTag (which contains the location used when reporting issues) to the // method link specified in @sample val sampleTags = sections.flatMap { section -> section.findTagsByName(SAMPLE_KDOC_ANNOTATION) .mapNotNull { sampleTag -> val linkText = sampleTag.getSubjectLink()?.getLinkText() if (linkText == null) { null } else { sampleTag to linkText } } }.distinct() sampleTags.forEach { (docTag, link) -> // TODO: handle suppressions (if needed) with LintDriver.isSuppressed val mainLintMap = context.getPartialResults(UNRESOLVED_SAMPLE_LINK).map() val sampleLinkLintMap = mainLintMap.getMap(SAMPLE_LINK_MAP) ?: LintMap().also { mainLintMap.put(SAMPLE_LINK_MAP, it) } // This overrides any identical links in the same project - no need to report the // same error multiple times in different places, and it is tricky to do so in any case. sampleLinkLintMap.put(link, context.getNameLocation(docTag)) } } } /** * Handles sample functions annotated with @Sampled */ private class SampledAnnotationHandler(private val context: JavaContext) { fun visitMethod(node: UMethod) { if (node.hasAnnotation(SAMPLED_ANNOTATION_FQN)) { handleSampleCode(node) } } private fun handleSampleCode(node: UMethod) { val currentPath = context.psiFile!!.virtualFile.path if (SAMPLES_DIRECTORY !in currentPath) { val incident = Incident(context) .issue(INVALID_SAMPLES_LOCATION) .location(context.getNameLocation(node)) .message("${node.name} is annotated with @$SAMPLED_ANNOTATION" + ", but is not inside a project/directory named $SAMPLES_DIRECTORY.") .scope(node) context.report(incident) return } // The package name of the file we are in val parentFqName = (node.containingFile as KtFile).packageFqName.asString() // The full name of the current function that will be referenced in a @sample tag val fullFqName = "$parentFqName.${node.name}" val mainLintMap = context.getPartialResults(UNRESOLVED_SAMPLE_LINK).map() val sampledFunctionLintMap = mainLintMap.getMap(SAMPLED_FUNCTION_MAP) ?: LintMap().also { mainLintMap.put(SAMPLED_FUNCTION_MAP, it) } val location = context.getNameLocation(node) if (sampledFunctionLintMap.getLocation(fullFqName) != null) { val incident = Incident(context) .issue(MULTIPLE_FUNCTIONS_FOUND) .location(location) .message("Found multiple functions matching $fullFqName") context.report(incident) } sampledFunctionLintMap.put(fullFqName, location) } }
apache-2.0
4ae6db2908f0e866ec446717ace3c2ef
43.908078
100
0.627652
5.044431
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/highlight/RsHighlightExitPointsHandlerFactory.kt
2
3663
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.highlight import com.intellij.codeInsight.highlighting.HighlightUsagesHandlerBase import com.intellij.codeInsight.highlighting.HighlightUsagesHandlerFactoryBase import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.Consumer import org.rust.lang.core.dfa.ExitPoint import org.rust.lang.core.macros.isExpandedFromMacro import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsElementTypes.* import org.rust.lang.core.psi.ext.* class RsHighlightExitPointsHandlerFactory : HighlightUsagesHandlerFactoryBase() { override fun createHighlightUsagesHandler(editor: Editor, file: PsiFile, target: PsiElement): HighlightUsagesHandlerBase<*>? { if (file !is RsFile) return null val createHandler: (PsiElement) -> RsHighlightExitPointsHandler? = { element -> val elementType = element.elementType val shouldHighlightExitPoints = elementType == RETURN || elementType == Q && element.parent is RsTryExpr || elementType == BREAK || elementType == FN && element.parent is RsFunction || elementType == ARROW && element.parent.let { it is RsRetType && it.parent is RsFunctionOrLambda } if (shouldHighlightExitPoints) { RsHighlightExitPointsHandler(editor, file, element) } else { null } } val prevToken = PsiTreeUtil.prevLeaf(target) ?: return null return createHandler(target) ?: createHandler(prevToken) } } private class RsHighlightExitPointsHandler( editor: Editor, file: PsiFile, val target: PsiElement ) : HighlightUsagesHandlerBase<PsiElement>(editor, file) { override fun getTargets() = listOf(target) override fun selectTargets(targets: List<PsiElement>, selectionConsumer: Consumer<in List<PsiElement>>) { selectionConsumer.consume(targets) } override fun computeUsages(targets: List<PsiElement>) { val usages = mutableListOf<PsiElement>() val sink: (ExitPoint) -> Unit = { exitPoint -> val element = when (exitPoint) { is ExitPoint.Return -> exitPoint.e is ExitPoint.TryExpr -> if (exitPoint.e is RsTryExpr) exitPoint.e.q else exitPoint.e is ExitPoint.DivergingExpr -> exitPoint.e is ExitPoint.TailExpr -> exitPoint.e is ExitPoint.InvalidTailStatement -> null } if (element != null && !element.isExpandedFromMacro) { usages += element } } for (ancestor in target.ancestors) { if (ancestor is RsBlockExpr && ancestor.isTry && target.elementType == Q) { break } else if (ancestor is RsBlockExpr && ancestor.isAsync) { ExitPoint.process(ancestor.block, sink) break } else if (ancestor is RsFunction) { ExitPoint.process(ancestor, sink) break } else if (ancestor is RsLambdaExpr) { ExitPoint.process(ancestor, sink) break } } // highlight only if target inside exit point val targetAncestors = target.ancestors.toSet() if (usages.any { it in targetAncestors } || target.elementType == FN || target.elementType == ARROW) { usages.forEach(this::addOccurrence) } } }
mit
e665223b50903551b1dddfe53b633da9
39.252747
130
0.642097
4.690141
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/generate/setter/GenerateSetterHandler.kt
2
1912
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring.generate.setter import com.intellij.openapi.editor.Editor import org.rust.ide.refactoring.generate.BaseGenerateAction import org.rust.ide.refactoring.generate.BaseGenerateHandler import org.rust.ide.refactoring.generate.GenerateAccessorHandler import org.rust.ide.refactoring.generate.StructMember import org.rust.lang.core.psi.* import org.rust.lang.core.types.Substitution import org.rust.openapiext.checkWriteAccessAllowed class GenerateSetterAction : BaseGenerateAction() { override val handler: BaseGenerateHandler = GenerateSetterHandler() } class GenerateSetterHandler : GenerateAccessorHandler() { override val dialogTitle: String = "Select Fields to Generate Setters" override fun generateAccessors( struct: RsStructItem, implBlock: RsImplItem?, chosenFields: List<StructMember>, substitution: Substitution, editor: Editor ): List<RsFunction>? { checkWriteAccessAllowed() val project = editor.project ?: return null val structName = struct.name ?: return null val psiFactory = RsPsiFactory(project) val impl = getOrCreateImplBlock(implBlock, psiFactory, structName, struct) return chosenFields.mapNotNull { val fieldName = it.argumentIdentifier val typeStr = it.typeReferenceText val fnSignature = "pub fn ${methodName(it)}(&mut self, $fieldName: $typeStr)" val fnBody = "self.$fieldName = $fieldName;" val accessor = RsPsiFactory(project).createTraitMethodMember("$fnSignature {\n$fnBody\n}") impl.members?.addBefore(accessor, impl.members?.rbrace) as RsFunction } } override fun methodName(member: StructMember): String = "set_${member.argumentIdentifier}" }
mit
08850f6bcbf8e74c67d74e52a81c6ad9
36.490196
102
0.721757
4.541568
false
false
false
false
jiangzehui/kotlindemo
app/src/main/java/com/jiangzehui/kotlindemo/CityModel.kt
1
804
package com.jiangzehui.kotlindemo /** * Created by jiangzehui on 17/5/31. */ class CityModel { var msg: String? = null var retCode: String? = null var result: List<ResultBean>? = null class ResultBean { var province: String? = null /** * city : 合肥 * district : [{"district":"合肥"},{"district":"长丰"},{"district":"肥东"},{"district":"肥西"},{"district":"巢湖"},{"district":"庐江"}] */ var city: List<CityBean>? = null class CityBean { var city: String? = null /** * district : 合肥 */ var district: List<DistrictBean>? = null class DistrictBean { var district: String? = null } } } }
apache-2.0
f0108c2a08a87b7e40206da5ab385886
19.864865
131
0.485751
3.89899
false
false
false
false
taigua/exercism
kotlin/phone-number/src/main/kotlin/PhoneNumber.kt
1
542
class PhoneNumber(s: String) { companion object { val ERROR_NUMBER = "0000000000" fun parse(s: String) : String { val s1 = s.filter { it.isDigit() } return when (s1.length) { 10 -> s1 11 -> if (s1[0] == '1') s1.drop(1) else ERROR_NUMBER else -> ERROR_NUMBER } } } val number = parse(s) val areaCode = number.take(3) override fun toString() = "($areaCode) ${number.substring(3, 6)}-${number.substring(6, 10)}" }
mit
0e3c87bac92b8eaf8b2d4a7feb2b9743
29.166667
97
0.498155
3.662162
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/net/social/Attachment.kt
1
4510
/* * Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.net.social import android.content.ContentResolver import android.net.Uri import org.andstatus.app.context.MyContextHolder import org.andstatus.app.data.DownloadData import org.andstatus.app.data.DownloadType import org.andstatus.app.data.FileProvider import org.andstatus.app.data.MyContentType import org.andstatus.app.util.IsEmpty import org.andstatus.app.util.UriUtils import java.util.* class Attachment : Comparable<Attachment>, IsEmpty { val uri: Uri val mimeType: String val contentType: MyContentType var previewOf = EMPTY var downloadData: DownloadData = DownloadData.EMPTY private var optNewDownloadNumber: Optional<Long> = Optional.empty() /** #previewOf cannot be set here */ internal constructor(downloadData: DownloadData) { this.downloadData = downloadData uri = downloadData.getUri() mimeType = downloadData.getMimeType() contentType = downloadData.getContentType() } private constructor(contentResolver: ContentResolver?, uri: Uri, mimeType: String) { this.uri = uri this.mimeType = MyContentType.uri2MimeType(contentResolver, uri, mimeType) contentType = MyContentType.fromUri(DownloadType.ATTACHMENT, contentResolver, uri, mimeType) } fun setPreviewOf(previewOf: Attachment): Attachment { this.previewOf = previewOf return this } fun isValid(): Boolean { return nonEmpty && contentType != MyContentType.UNKNOWN } override fun hashCode(): Int { val prime = 31 var result = 1 result = prime * result + contentType.hashCode() result = prime * result + uri.hashCode() result = prime * result + mimeType.hashCode() return result } fun getDownloadNumber(): Long { return optNewDownloadNumber.orElse(downloadData.getDownloadNumber()) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Attachment) return false return contentType == other.contentType && uri == other.uri && mimeType == other.mimeType } override fun toString(): String { return "Attachment [uri='$uri', $contentType, mime=$mimeType]" } fun mediaUriToPost(): Uri? { return if (downloadData.isEmpty || UriUtils.isDownloadable(uri)) { Uri.EMPTY } else FileProvider.downloadFilenameToUri(downloadData.file.getFilename()) } override operator fun compareTo(other: Attachment): Int { if (previewOf == other) return -1 if (other.previewOf == this) return 1 return if (contentType != other.contentType) { if (contentType.attachmentsSortOrder > other.contentType.attachmentsSortOrder) 1 else -1 } else 0 } override val isEmpty: Boolean get() { return uri === Uri.EMPTY } fun getDownloadId(): Long { return downloadData.downloadId } fun setDownloadNumber(downloadNumber: Long) { optNewDownloadNumber = Optional.of(downloadNumber) } companion object { val EMPTY: Attachment = Attachment(null, Uri.EMPTY, "") fun fromUri(uriString: String?): Attachment { return fromUriAndMimeType(uriString, "") } fun fromUri(uriIn: Uri): Attachment { return fromUriAndMimeType(uriIn, "") } fun fromUriAndMimeType(uriString: String?, mimeTypeIn: String): Attachment { return fromUriAndMimeType(Uri.parse(uriString), mimeTypeIn) } fun fromUriAndMimeType(uriIn: Uri, mimeTypeIn: String): Attachment { Objects.requireNonNull(uriIn) Objects.requireNonNull(mimeTypeIn) return Attachment( MyContextHolder.myContextHolder.getNow().context?.getContentResolver(), uriIn, mimeTypeIn) } } }
apache-2.0
f6f7e91227e85cbc2dd9666f541c0b53
33.692308
121
0.676718
4.587996
false
false
false
false
wealthfront/magellan
magellan-library/src/test/java/com/wealthfront/magellan/core/JourneyTest.kt
1
4134
package com.wealthfront.magellan.core import android.content.Context import androidx.appcompat.app.AppCompatActivity import com.google.common.truth.Truth.assertThat import com.wealthfront.magellan.Direction import com.wealthfront.magellan.ScreenContainer import com.wealthfront.magellan.internal.test.DummyStep import com.wealthfront.magellan.internal.test.databinding.MagellanDummyLayoutBinding import com.wealthfront.magellan.navigation.DefaultLinearNavigator import com.wealthfront.magellan.navigation.LinearNavigator import com.wealthfront.magellan.navigation.NavigableCompat import com.wealthfront.magellan.navigation.NavigationEvent import com.wealthfront.magellan.transitions.NoAnimationTransition import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.android.controller.ActivityController @RunWith(RobolectricTestRunner::class) class JourneyTest { private lateinit var activityController: ActivityController<FakeActivity> private lateinit var context: Context private lateinit var screenContainer: ScreenContainer private lateinit var navigator: LinearNavigator private lateinit var journey: Journey<*> @Before fun setUp() { activityController = Robolectric.buildActivity(FakeActivity::class.java) context = activityController.get() screenContainer = ScreenContainer(context) navigator = DefaultLinearNavigator(container = { screenContainer }) journey = DummyJourney().apply { navigator = [email protected] } } @Test fun givenEmptyBackStack_currentNavigable_isSelf() { assertThat(journey.currentNavigable).isEqualTo(journey) } @Test fun givenSingleLeafBackStack_currentNavigable_isThatLeaf() { val singleLeaf = DummyStep() navigator.set(singleLeaf) assertThat(journey.currentNavigable).isEqualTo(singleLeaf) } @Test fun givenSingleBranchBackStack_currentNavigable_isTopLeaf() { val topLeaf = DummyStep() val singleBranch = DummyJourney().apply { navigator = DefaultLinearNavigator(container = { screenContainer }).apply { set(topLeaf) } } navigator.set(singleBranch) assertThat(journey.currentNavigable).isEqualTo(topLeaf) } @Test fun givenMultiBranchBackStack_currentNavigable_isTopLeaf() { val topLeaf = DummyStep() val bottomBranch = DummyJourney().apply { navigator = DefaultLinearNavigator(container = { screenContainer }).apply { set(DummyStep()) } } val nestedBranch = DummyJourney().apply { navigator = DefaultLinearNavigator(container = { screenContainer }).apply { set(topLeaf) } } val multiBranch = DummyJourney().apply { navigator = DefaultLinearNavigator(container = { screenContainer }).apply { set(nestedBranch) } } navigator.navigate(Direction.FORWARD) { backStack -> backStack.clear() val transition = NoAnimationTransition() backStack.push(NavigationEvent(bottomBranch, transition)) backStack.push(NavigationEvent(multiBranch, transition)) transition } assertThat(journey.currentNavigable).isEqualTo(topLeaf) } @Test fun givenCustomNavigable_currentNavigable_defersToCustomNavigable() { val customLeaf = DummyStep() val customNavigable = mock(NavigableCompat::class.java) `when`(customNavigable.currentNavigable).thenReturn(customLeaf) navigator.set(customNavigable) assertThat(journey.currentNavigable).isEqualTo(customLeaf) } private open class FakeActivity : AppCompatActivity() private open class DummyJourney : Journey<MagellanDummyLayoutBinding>( MagellanDummyLayoutBinding::inflate, MagellanDummyLayoutBinding::container ) fun LinearNavigator.set(navigable: NavigableCompat) { navigate(Direction.BACKWARD) { backStack -> backStack.clear() NavigationEvent(navigable, NoAnimationTransition()).run { backStack.push(this) magellanTransition } } } }
apache-2.0
bb26f7b97de8823ad50303015b109b27
33.45
84
0.762941
4.676471
false
true
false
false
czyzby/ktx
graphics/src/test/kotlin/ktx/graphics/TextUtilitiesTest.kt
1
1426
package ktx.graphics import com.badlogic.gdx.Gdx import com.badlogic.gdx.backends.lwjgl.LwjglFiles import com.badlogic.gdx.graphics.g2d.BitmapFont import com.nhaarman.mockitokotlin2.mock import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import com.badlogic.gdx.utils.Array as GdxArray class TextUtilitiesTest { @Before fun `setup files`() { Gdx.files = LwjglFiles() } @Test fun `should center text on a rectangle`() { val font = FakeFont() val width = 100f val height = 200f val position = font.center("text", width, height) assertEquals(38.5f, position.x, 0.1f) assertEquals(105.5f, position.y, 0.1f) } @Test fun `should center text on a rectangle at given position`() { val font = FakeFont() val position = font.center("text", x = 100f, y = 200f, width = 100f, height = 200f) assertEquals(138.5f, position.x, 0.1f) assertEquals(305.5f, position.y, 0.1f) } @After fun `dispose of files`() { Gdx.files = null } /** * Loads the .fnt settings file of the default libGDX Arial font, but * omits loading the textures. For testing purposes. */ class FakeFont : BitmapFont( BitmapFontData(Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.fnt"), true), GdxArray.with(mock()), true ) { override fun load(data: BitmapFontData?) { // Do nothing. } } }
cc0-1.0
1e98f77448494ca353d1c3afbaddb269
23.586207
87
0.680224
3.419664
false
true
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/nine/module/image/ImageEntity.kt
1
754
package com.intfocus.template.subject.nine.module.image import org.json.JSONObject /** * @author liuruilin * @data 2017/11/3 * @describe */ class ImageEntity { /** * title : 页面截图(最多3张) * sub_title : * hint : * limit : 3 * value : ["",""] */ var title: String = "" var sub_title: String = "" var hint: String = "" var limit: Int = 0 var value: List<String>? = null override fun toString(): String { var imageJson = JSONObject() imageJson.put("title", title) imageJson.put("sub_title", sub_title) imageJson.put("hint", hint) imageJson.put("limit", limit) imageJson.put("value", value) return imageJson.toString() } }
gpl-3.0
ee25c2149f717ffba24b6eb5636749a2
21.424242
55
0.566216
3.52381
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/refactoring/XPathNamesValidator.kt
1
1506
/* * Copyright (C) 2020-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xpath.lang.refactoring import com.intellij.lang.refactoring.NamesValidator import com.intellij.openapi.project.Project import uk.co.reecedunn.intellij.plugin.xpath.lexer.XPathLexer import xqt.platform.intellij.lexer.token.INCNameTokenType import xqt.platform.intellij.xpath.XPathTokenProvider class XPathNamesValidator : NamesValidator { private val lexer = XPathLexer() override fun isKeyword(name: String, project: Project?): Boolean = false override fun isIdentifier(name: String, project: Project?): Boolean { lexer.start(name) if (lexer.tokenType === XPathTokenProvider.S.elementType) lexer.advance() val isNCName = lexer.tokenType is INCNameTokenType lexer.advance() if (lexer.tokenType === XPathTokenProvider.S.elementType) lexer.advance() return lexer.tokenType == null && isNCName } }
apache-2.0
96b9de3eb0601930e6f02bb15c6460f6
37.615385
81
0.746348
4.278409
false
false
false
false
ilya-g/kotlinx.collections.experimental
kotlinx-collections-experimental/benchmarks/src/main/kotlin/sequences/SequenceMapFilterFusionOperations.kt
1
1065
package kotlinx.collections.experimental.sequences.benchmarks import kotlinx.collections.experimental.sequences.* import org.openjdk.jmh.annotations.* import org.openjdk.jmh.infra.Blackhole @State(Scope.Benchmark) @BenchmarkMode(Mode.AverageTime) open class SequenceMapFilterFusionOperations : SequenceBenchmarksBase() { @Benchmark fun map_filter_std(blackhole: Blackhole) { sequence.map_std { if (it % 3 == 0) it else null }.filter_std { it != null }.consume(blackhole) } @Benchmark fun map_filter_fused(blackhole: Blackhole) { sequence.map_fused { if (it % 3 == 0) it else null }.filter_fused { it != null }.consume(blackhole) } @Benchmark fun map_map_filter_std(blackhole: Blackhole) { sequence.map_std { it / 100 }.map_std { if (it % 3 == 0) it else null }.filter_std { it != null }.consume(blackhole) } @Benchmark fun map_map_filter_fused(blackhole: Blackhole) { sequence.map_fused { it / 100 }.map_fused { if (it % 3 == 0) it else null }.filter_fused { it != null }.consume(blackhole) } }
apache-2.0
a476877984950077406e40b495a77c99
38.481481
130
0.684507
3.503289
false
false
false
false
schneppd/lab.schneppd.android2017.opengl2
MyApplication/app/src/main/java/com/schneppd/myopenglapp/OpenGL2v1/Triangle.kt
1
4043
package com.schneppd.myopenglapp.OpenGL2v1 import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.FloatBuffer import android.opengl.GLES20 /** * Created by schneppd on 7/9/17. */ class Triangle { companion object Static { // This matrix member variable provides a hook to manipulate // the coordinates of the objects that use this vertex shader // the matrix must be included as a modifier of gl_Position // Note that the uMVPMatrix factor *must be first* in order // for the matrix multiplication product to be correct. val vertexShaderCode:String = """ uniform mat4 uMVPMatrix; attribute vec4 vPosition; void main() { gl_Position = uMVPMatrix * vPosition; }""" val fragmentShaderCode = """ precision mediump float; uniform vec4 vColor; void main() { gl_FragColor = vColor; } """ // number of coordinates per vertex in this array val COORDS_PER_VERTEX = 3 val triangleCoords:FloatArray = floatArrayOf( // in counterclockwise order: 0.0f, 0.622008459f, 0.0f, // top -0.5f, -0.311004243f, 0.0f, // bottom left 0.5f, -0.311004243f, 0.0f // bottom right ) val vertexCount:Int = triangleCoords.size / COORDS_PER_VERTEX val vertexStride:Int = COORDS_PER_VERTEX * 4 // 4 bytes per vertex val color:FloatArray = floatArrayOf( 0.63671875f, 0.76953125f, 0.22265625f, 0.9f ) } private var vertexBuffer:FloatBuffer private var mProgram:Int = 0 private var mPositionHandle:Int = 0 private var mColorHandle:Int = 0 private var mMVPMatrixHandle:Int = 0 init{ // initialize vertex byte buffer for shape coordinates var bb:ByteBuffer = ByteBuffer.allocateDirect( // (number of coordinate values * 4 bytes per float) triangleCoords.size * 4) // use the device hardware's native byte order bb.order(ByteOrder.nativeOrder()) // create a floating point buffer from the ByteBuffer vertexBuffer = bb.asFloatBuffer() // add the coordinates to the FloatBuffer vertexBuffer.put(triangleCoords) // set the buffer to read the first coordinate vertexBuffer.position(0) // prepare shaders and OpenGL program val vertexShader = CustomGLRenderer.loadShader( GLES20.GL_VERTEX_SHADER, vertexShaderCode ) val fragmentShader = CustomGLRenderer.loadShader( GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode ) mProgram = GLES20.glCreateProgram() // create empty OpenGL Program GLES20.glAttachShader(mProgram, vertexShader) // add the vertex shader to program GLES20.glAttachShader(mProgram, fragmentShader) // add the fragment shader to program GLES20.glLinkProgram(mProgram) // create OpenGL program executables } /** * Encapsulates the OpenGL ES instructions for drawing this shape. * * @param mvpMatrix - The Model View Project matrix in which to draw * this shape. */ fun draw(mvpMatrix:FloatArray){ // Add program to OpenGL environment GLES20.glUseProgram(mProgram) // get handle to vertex shader's vPosition member mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition") // Enable a handle to the triangle vertices GLES20.glEnableVertexAttribArray(mPositionHandle) // Prepare the triangle coordinate data GLES20.glVertexAttribPointer( mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride, vertexBuffer) // get handle to fragment shader's vColor member mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor") // Set color for drawing the triangle GLES20.glUniform4fv(mColorHandle, 1, color, 0) // get handle to shape's transformation matrix mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix") CustomGLRenderer.checkGlError("glGetUniformLocation") // Apply the projection and view transformation GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0) CustomGLRenderer.checkGlError("glUniformMatrix4fv") // Draw the triangle GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount) // Disable vertex array GLES20.glDisableVertexAttribArray(mPositionHandle) } }
gpl-3.0
d73825f6787b75961d35929bfa20af21
33.862069
87
0.745733
3.743519
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/step_quiz_choice/mapper/ChoiceStepQuizOptionsMapper.kt
2
1231
package org.stepik.android.view.step_quiz_choice.mapper import org.stepic.droid.util.TextUtil import org.stepik.android.model.Submission import org.stepik.android.model.feedback.ChoiceFeedback import org.stepik.android.view.step_quiz_choice.model.Choice class ChoiceStepQuizOptionsMapper { fun mapChoices(options: List<String>, choices: List<Boolean>?, submission: Submission?, isQuizEnabled: Boolean): List<Choice> { val feedback = submission?.feedback as? ChoiceFeedback return options.mapIndexed { i, option -> val isCorrect = if (choices?.getOrNull(i) == true) { when (submission?.status) { Submission.Status.CORRECT -> true Submission.Status.WRONG -> false else -> null } } else { null } Choice( option = option, feedback = feedback?.optionsFeedback?.getOrNull(i)?.let(TextUtil::linkify), correct = isCorrect, isEnabled = isQuizEnabled ) } } }
apache-2.0
8183f9b54f9c4de0710ad3f8411e3e89
38.741935
131
0.536149
5.283262
false
false
false
false
BloodWorkXGaming/ExNihiloCreatio
src/main/java/exnihilocreatio/util/ItemUtil.kt
1
1268
@file:JvmName("ItemUtil") package exnihilocreatio.util import exnihilocreatio.items.tools.ICrook import exnihilocreatio.items.tools.IHammer import net.minecraft.init.Items import net.minecraft.item.Item import net.minecraft.item.ItemStack fun isCrook(stack: ItemStack?): Boolean { if (stack == null || stack.isEmpty) return false if (stack.item === Items.AIR) return false if (stack.item is ICrook) return (stack.item as ICrook).isCrook(stack) // Inspirations compatibility // Using ToolClass is the recommended method for compatible mods. return (stack.item.getToolClasses(stack).contains("crook")) } fun isCrook(item: Item): Boolean { return isCrook(ItemStack(item)) } fun isHammer(stack: ItemStack?): Boolean { if (stack == null) return false if (stack.item === Items.AIR) return false if (stack.item is IHammer) return (stack.item as IHammer).isHammer(stack) return false } fun isHammer(item: Item): Boolean { return isHammer(ItemStack(item)) } /** * Compares Items, Damage, and NBT */ fun areStacksEquivalent(left: ItemStack, right: ItemStack) : Boolean{ return ItemStack.areItemsEqual(right, left) && ItemStack.areItemStackTagsEqual(left, right) }
mit
db3749ce34f4c300a94b9d3facf29989
23.403846
95
0.702681
3.707602
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/course_list/ui/fragment/CourseListWishFragment.kt
1
6896
package org.stepik.android.view.course_list.ui.fragment import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import kotlinx.android.synthetic.main.empty_search.* import kotlinx.android.synthetic.main.error_no_connection_with_button.* import kotlinx.android.synthetic.main.fragment_course_list.* import kotlinx.android.synthetic.main.fragment_course_list.courseListCoursesRecycler import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.App import org.stepic.droid.core.ScreenManager import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.ui.util.initCenteredToolbar import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course_payments.mapper.DefaultPromoCodeMapper import org.stepik.android.domain.last_step.model.LastStep import org.stepik.android.domain.wishlist.analytic.WishlistOpenedEvent import org.stepik.android.model.Course import org.stepik.android.presentation.course_continue.model.CourseContinueInteractionSource import org.stepik.android.presentation.course_list.CourseListView import org.stepik.android.presentation.course_list.CourseListWishPresenter import org.stepik.android.presentation.course_list.CourseListWishView import org.stepik.android.view.course.mapper.DisplayPriceMapper import org.stepik.android.view.course_list.delegate.CourseContinueViewDelegate import org.stepik.android.view.course_list.delegate.CourseListViewDelegate import org.stepik.android.view.ui.delegate.ViewStateDelegate import ru.nobird.android.core.model.PaginationDirection import ru.nobird.android.view.base.ui.extension.setOnPaginationListener import javax.inject.Inject class CourseListWishFragment : Fragment(R.layout.fragment_course_list), CourseListWishView { companion object { fun newInstance(): Fragment = CourseListWishFragment() } @Inject internal lateinit var analytic: Analytic @Inject internal lateinit var screenManager: ScreenManager @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory @Inject internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper @Inject internal lateinit var defaultPromoCodeMapper: DefaultPromoCodeMapper @Inject internal lateinit var displayPriceMapper: DisplayPriceMapper private lateinit var courseListViewDelegate: CourseListViewDelegate private val courseListWishPresenter: CourseListWishPresenter by viewModels { viewModelFactory } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) injectComponent() analytic.report(WishlistOpenedEvent) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initCenteredToolbar(R.string.wishlist_title, true) with(courseListCoursesRecycler) { layoutManager = GridLayoutManager(context, resources.getInteger(R.integer.course_list_columns)) itemAnimator = null setOnPaginationListener { pageDirection -> if (pageDirection == PaginationDirection.NEXT) { courseListWishPresenter.fetchNextPage() } } } goToCatalog.setOnClickListener { screenManager.showCatalog(requireContext()) } courseListSwipeRefresh.setOnRefreshListener { courseListWishPresenter.fetchCourses(forceUpdate = true) } tryAgain.setOnClickListener { courseListWishPresenter.fetchCourses(forceUpdate = true) } val viewStateDelegate = ViewStateDelegate<CourseListView.State>() viewStateDelegate.addState<CourseListView.State.Idle>() viewStateDelegate.addState<CourseListView.State.Loading>(courseListCoursesRecycler) viewStateDelegate.addState<CourseListView.State.Content>(courseListCoursesRecycler) viewStateDelegate.addState<CourseListView.State.Empty>(courseListCoursesEmpty) viewStateDelegate.addState<CourseListView.State.NetworkError>(courseListCoursesLoadingErrorVertical) courseListViewDelegate = CourseListViewDelegate( analytic = analytic, courseContinueViewDelegate = CourseContinueViewDelegate( activity = requireActivity(), analytic = analytic, screenManager = screenManager ), courseListSwipeRefresh = courseListSwipeRefresh, courseItemsRecyclerView = courseListCoursesRecycler, courseListViewStateDelegate = viewStateDelegate, onContinueCourseClicked = { courseListItem -> courseListWishPresenter .continueCourse( course = courseListItem.course, viewSource = CourseViewSource.Visited, interactionSource = CourseContinueInteractionSource.COURSE_WIDGET ) }, defaultPromoCodeMapper = defaultPromoCodeMapper, displayPriceMapper = displayPriceMapper, itemAdapterDelegateType = CourseListViewDelegate.ItemAdapterDelegateType.STANDARD ) courseListWishPresenter.fetchCourses() } private fun injectComponent() { App.component() .courseListWishComponentBuilder() .build() .inject(this) } override fun setState(state: CourseListWishView.State) { when (state) { is CourseListWishView.State.Idle, is CourseListWishView.State.Loading -> courseListViewDelegate.setState(CourseListView.State.Loading) is CourseListWishView.State.Data -> courseListViewDelegate.setState(state.courseListViewState) is CourseListWishView.State.NetworkError -> courseListViewDelegate.setState(CourseListView.State.NetworkError) } } override fun showCourse(course: Course, source: CourseViewSource, isAdaptive: Boolean) { courseListViewDelegate.showCourse(course, source, isAdaptive) } override fun showSteps(course: Course, source: CourseViewSource, lastStep: LastStep) { courseListViewDelegate.showSteps(course, source, lastStep) } override fun setBlockingLoading(isLoading: Boolean) { courseListViewDelegate.setBlockingLoading(isLoading) } override fun showNetworkError() { courseListViewDelegate.showNetworkError() } override fun onStart() { super.onStart() courseListWishPresenter.attachView(this) } override fun onStop() { courseListWishPresenter.detachView(this) super.onStop() } }
apache-2.0
20ec11e87593a588da4b5169dd94a85a
40.299401
112
0.736949
5.490446
false
false
false
false
walleth/walleth
app/src/main/java/org/walleth/walletconnect/WalletConnectService.kt
1
4063
package org.walleth.walletconnect import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Intent import android.os.Binder import android.os.Build import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.lifecycle.LifecycleService import com.squareup.moshi.Moshi import okhttp3.OkHttpClient import org.koin.android.ext.android.inject import org.ligi.kaxt.getNotificationManager import org.walletconnect.Session import org.walletconnect.Session.MethodCall import org.walletconnect.Session.MethodCall.* import org.walletconnect.impls.WCSessionStore import org.walleth.R import org.walleth.notifications.NOTIFICATION_CHANNEL_ID_WALLETCONNECT import org.walleth.notifications.NOTIFICATION_ID_WALLETCONNECT class WalletConnectService : LifecycleService() { val moshi: Moshi by inject() private val okhttp: OkHttpClient by inject() private val sessionStore: WCSessionStore by inject() val handler by lazy { WalletConnectHandler(moshi, okhttp, sessionStore) } private var binder: LocalBinder? = LocalBinder() var uiPendingCallback: (() -> Unit)? = null var uiPendingCall: MethodCall? = null var uiPendingStatus: Session.Status? = null fun takeCall(action: (c: MethodCall) -> Unit) { uiPendingCall?.let { action(it) getNotificationManager().cancel(NOTIFICATION_ID_WALLETCONNECT) uiPendingCall = null } } private val sessionCallback = object : Session.Callback { override fun onMethodCall(call: MethodCall) { uiPendingCall = call uiPendingCallback?.invoke() if (uiPendingCallback == null && (call is Custom || call is SignMessage || call is SendTransaction)) { val wcIntent = Intent(baseContext, WalletConnectConnectionActivity::class.java) val contentIntent = PendingIntent.getActivity(baseContext, 0, wcIntent, PendingIntent.FLAG_UPDATE_CURRENT) if (Build.VERSION.SDK_INT > 25) { val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID_WALLETCONNECT, "WalletConnect", NotificationManager.IMPORTANCE_HIGH) channel.description = "WalletConnectNotifications" getNotificationManager().createNotificationChannel(channel) } val notification = NotificationCompat.Builder(this@WalletConnectService, NOTIFICATION_CHANNEL_ID_WALLETCONNECT).apply { setContentTitle("WalletConnect Interaction") if (call is Custom || call is SignMessage) { setContentText("Please sign the message") } else { setContentText("Please sign the transaction") } setAutoCancel(true) setContentIntent(contentIntent) if (Build.VERSION.SDK_INT > 19) { setSmallIcon(R.drawable.ic_walletconnect_logo) } }.build() getNotificationManager().notify(NOTIFICATION_ID_WALLETCONNECT, notification) } } override fun onStatus(status: Session.Status) { uiPendingStatus = status uiPendingCallback?.invoke() } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { intent?.data.let { handler.processURI(it.toString()) handler.session?.addCallback(sessionCallback) } return super.onStartCommand(intent, flags, startId) } override fun onDestroy() { super.onDestroy() handler.session?.reject() handler.session?.kill() binder = null } inner class LocalBinder : Binder() { fun getService(): WalletConnectService = this@WalletConnectService } override fun onBind(intent: Intent): IBinder { super.onBind(intent) return binder!! } }
gpl-3.0
7b279c2d6e64cf7a8858262882e1b764
34.649123
146
0.657888
5.143038
false
false
false
false
walleth/walleth
app/src/main/java/org/walleth/info/WarningActivity.kt
1
3418
package org.walleth.info import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.Menu import android.view.MenuItem import kotlinx.android.synthetic.main.activity_info.* import org.ligi.compat.HtmlCompat import org.ligi.kaxtui.alert import org.walleth.R import org.walleth.base_activities.BaseSubActivity const val SHARE_HINT = "\n\nPlease contact the contract authors (e.g. via the share icon on the top right) and let them know about the problem!" class WarningActivity : BaseSubActivity() { private val payload by lazy { intent?.data.toString().substringAfter("wallethwarn:") } private val currentWarning by lazy { currentWarning() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_warning) supportActionBar?.setSubtitle(R.string.warning_subtitle) intro_text.text = HtmlCompat.fromHtml(currentWarning + SHARE_HINT) intro_text.movementMethod = LinkMovementMethod() } private fun currentWarning(): String { return when { payload.startsWith("userdocnotfound") -> getUserdocWarningText(payload) payload.startsWith("contractnotfound") -> getContractWarning(payload) else -> "Warning not found: $payload" } } private fun getUserdocWarningText(payload: String): String { val address = payload.split("||").getOrNull(1) ?: "unknown" val method = payload.split("||").getOrNull(2) ?: "unknown" return "The contract (at address $address) you tried to interact with did not contain any @notice on the method ($method) you tried to invoke. " } private fun getContractWarning(payload: String): String { val address = payload.split("||").getOrNull(1) ?: "unknown" return "The contract (at address $address) you tried to interact is not verified. Without knowing this it is dangerous to interact with this contract. It can be verified on https://verification.komputing.org" } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_warning, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_share -> true.also { startIntentWithCatch(Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, currentWarning) type = "text/plain" }) } R.id.menu_mail -> true.also { startIntentWithCatch(Intent.createChooser(Intent(Intent.ACTION_SEND).apply { type = "plain/text"; putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]")) putExtra(Intent.EXTRA_SUBJECT, "[WallETH Warning]"); putExtra(Intent.EXTRA_TEXT, currentWarning); }, "Send mail")) } } return super.onOptionsItemSelected(item) } private fun startIntentWithCatch(intent: Intent) { try { startActivity(intent) } catch (e: ActivityNotFoundException) { alert("Did not find any app to share with.") } } }
gpl-3.0
d2a8d43ab8d29afa750bb9079f65d16f
37.840909
216
0.655939
4.663029
false
false
false
false
square/wire
wire-library/wire-schema-tests/src/main/java/com/squareup/wire/WireTestLogger.kt
1
1802
/* * Copyright 2022 Block Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire import com.squareup.wire.schema.ProtoType import okio.Path class WireTestLogger : WireLogger { val artifactHandled = ArrayDeque<Triple<Path, String, String>>() override fun artifactHandled(outputPath: Path, qualifiedName: String, targetName: String) { this.artifactHandled.add(Triple(outputPath, qualifiedName, targetName)) } val artifactSkipped = ArrayDeque<Pair<ProtoType, String>>() override fun artifactSkipped(type: ProtoType, targetName: String) { this.artifactSkipped.add(type to targetName) } val unusedRoots = ArrayDeque<Set<String>>() override fun unusedRoots(unusedRoots: Set<String>) { this.unusedRoots.add(unusedRoots) } val unusedPrunes = ArrayDeque<Set<String>>() override fun unusedPrunes(unusedPrunes: Set<String>) { this.unusedPrunes.add(unusedPrunes) } val unusedIncludesInTarget = ArrayDeque<Set<String>>() override fun unusedIncludesInTarget(unusedIncludes: Set<String>) { this.unusedIncludesInTarget.add(unusedIncludes) } val unusedExcludesInTarget = ArrayDeque<Set<String>>() override fun unusedExcludesInTarget(unusedExcludes: Set<String>) { this.unusedExcludesInTarget.add(unusedExcludes) } }
apache-2.0
e5bf211c395125ddb51acbda12aa6425
33.653846
93
0.756382
4.171296
false
false
false
false
cyclestreets/android
libraries/cyclestreets-view/src/main/java/net/cyclestreets/views/overlay/LockScreenOnOverlay.kt
1
2591
package net.cyclestreets.views.overlay import android.content.SharedPreferences import android.graphics.Canvas import android.graphics.drawable.Drawable import android.util.Log import android.view.LayoutInflater import android.widget.Toast import com.google.android.material.floatingactionbutton.FloatingActionButton import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial import net.cyclestreets.iconics.IconicsHelper.materialIcon import net.cyclestreets.util.Theme.highlightColor import net.cyclestreets.util.Theme.lowlightColor import net.cyclestreets.view.R import net.cyclestreets.views.CycleMapView import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Overlay class LockScreenOnOverlay(private val mapView: CycleMapView) : Overlay(), PauseResumeListener { companion object { private const val LOCK_PREF = "lockScreen" } private val screenLockButton: FloatingActionButton private val onIcon: Drawable private val offIcon: Drawable init { val context = mapView.context onIcon = materialIcon(context, GoogleMaterial.Icon.gmd_phonelink_lock, highlightColor(context)) offIcon = materialIcon(context, GoogleMaterial.Icon.gmd_phonelink_lock, lowlightColor(context)) val liveRideButtonView = LayoutInflater.from(context).inflate(R.layout.liveride_buttons, null) screenLockButton = liveRideButtonView.findViewById<FloatingActionButton>(R.id.liveride_screenlock_button).apply { setOnClickListener { _ -> screenLockButtonTapped() } setImageDrawable(offIcon) } mapView.addView(liveRideButtonView) mapView.keepScreenOn = false } private fun screenLockButtonTapped() { setScreenLockState(!mapView.keepScreenOn) } private fun setScreenLockState(state: Boolean) { Log.d("LiveRide", "Setting keepScreenOn state to $state") screenLockButton.setImageDrawable(if (state) onIcon else offIcon) val message = if (state) R.string.liveride_keep_screen_on_enabled else R.string.liveride_keep_screen_on_disabled Toast.makeText(mapView.context, message, Toast.LENGTH_LONG).show() mapView.keepScreenOn = state } override fun draw(c: Canvas, osmv: MapView, shadow: Boolean) {} ///////////////////////////////////////// override fun onResume(prefs: SharedPreferences) { mapView.keepScreenOn = prefs.getBoolean(LOCK_PREF, false) } override fun onPause(prefs: SharedPreferences.Editor) { prefs.putBoolean(LOCK_PREF, mapView.keepScreenOn) } }
gpl-3.0
413dd26acdd402e61463c8905da2e819
37.102941
121
0.740641
4.467241
false
false
false
false
cyclestreets/android
libraries/cyclestreets-view/src/main/java/net/cyclestreets/views/overlay/CircularRoutePOIOverlay.kt
1
2031
package net.cyclestreets.views.overlay import android.content.SharedPreferences import net.cyclestreets.Undoable import net.cyclestreets.routing.Journey import net.cyclestreets.routing.Route import net.cyclestreets.routing.Waypoints import net.cyclestreets.util.Logging import net.cyclestreets.views.CycleMapView import org.osmdroid.api.IGeoPoint import org.osmdroid.events.ScrollEvent import org.osmdroid.events.ZoomEvent import org.osmdroid.util.BoundingBox private val TAG = Logging.getTag(CircularRoutePOIOverlay::class.java) class CircularRoutePOIOverlay(mapView: CycleMapView): PauseResumeListener, Route.Listener, ItemizedOverlay<POIOverlay.POIOverlayItem>(mapView.mapView(), ArrayList()), Undoable { private var currentJourney: Journey? = null override fun onResume(prefs: SharedPreferences) { Route.registerListener(this) } override fun onPause(prefs: SharedPreferences.Editor) { Route.unregisterListener(this) } override fun onNewJourney(journey: Journey, waypoints: Waypoints) { removePois() currentJourney = journey for (poi in currentJourney!!.circularRoutePois) { items().add(POIOverlay.POIOverlayItem(poi)) } } override fun onResetJourney() { removePois() } private fun removePois() { Bubble.hideBubble(this) // Remove Circular Route POI's from display if (currentJourney != null) { items().clear() currentJourney = null } } override fun onItemSingleTap(item: POIOverlay.POIOverlayItem?): Boolean { Bubble.hideOrShowBubble(item, this) mapView().postInvalidate() return true } override fun onBackPressed(): Boolean { Bubble.hideBubble(this) mapView().postInvalidate() return true } }
gpl-3.0
2bfa00352c3e2434fa09ed21497327ea
30.261538
131
0.642048
5.052239
false
false
false
false
Maccimo/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/ReviewListCellRenderer.kt
3
14729
// 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.collaboration.ui.codereview.list import com.intellij.collaboration.messages.CollaborationToolsBundle.message import com.intellij.ide.IdeTooltip import com.intellij.ide.IdeTooltipManager import com.intellij.openapi.ui.popup.Balloon import com.intellij.ui.JBColor import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.components.JBList import com.intellij.ui.scale.JBUIScale import com.intellij.util.IconUtil import com.intellij.util.containers.nullize import com.intellij.util.text.DateFormatUtil import com.intellij.util.ui.* import icons.CollaborationToolsIcons import java.awt.* import java.awt.geom.RoundRectangle2D import java.awt.image.BufferedImage import javax.swing.* import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt class ReviewListCellRenderer<T>(private val presenter: (T) -> ReviewListItemPresentation) : ListCellRenderer<T>, JPanel(null) { private val toolTipManager get() = IdeTooltipManager.getInstance() private val title = JLabel().apply { minimumSize = JBDimension(30, 0) } private val info = JLabel() private val tags = JLabel() private val state = JLabel().apply { border = JBUI.Borders.empty(0, 4) foreground = stateForeground } private val statePanel = StatePanel(state).apply { background = stateBackground } private val nonMergeable = JLabel() private val buildStatus = JLabel() private val userGroup1 = JLabel() private val userGroup2 = JLabel() private val comments = JLabel() init { val firstLinePanel = JPanel(HorizontalSidesLayout(6)).apply { isOpaque = false add(title, SwingConstants.LEFT as Any) add(tags, SwingConstants.LEFT as Any) add(statePanel, SwingConstants.RIGHT as Any) add(nonMergeable, SwingConstants.RIGHT as Any) add(buildStatus, SwingConstants.RIGHT as Any) add(userGroup1, SwingConstants.RIGHT as Any) add(userGroup2, SwingConstants.RIGHT as Any) add(comments, SwingConstants.RIGHT as Any) } layout = BorderLayout() border = JBUI.Borders.empty(6) add(firstLinePanel, BorderLayout.CENTER) add(info, BorderLayout.SOUTH) UIUtil.forEachComponentInHierarchy(this) { it.isFocusable = false } } override fun getListCellRendererComponent(list: JList<out T>, value: T, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { background = ListUiUtil.WithTallRow.background(list, isSelected, list.hasFocus()) val primaryTextColor = ListUiUtil.WithTallRow.foreground(isSelected, list.hasFocus()) val secondaryTextColor = ListUiUtil.WithTallRow.secondaryForeground(isSelected, list.hasFocus()) val presentation = presenter(value) title.apply { text = presentation.title foreground = primaryTextColor } info.apply { val author = presentation.author if (author != null) { text = message("review.list.info.author", presentation.id, DateFormatUtil.formatPrettyDate(presentation.createdDate), author.getPresentableName()) } else { text = message("review.list.info", presentation.id, DateFormatUtil.formatPrettyDate(presentation.createdDate)) } foreground = secondaryTextColor } val tagGroup = presentation.tagGroup tags.apply { icon = CollaborationToolsIcons.Branch isVisible = tagGroup != null }.also { if (tagGroup != null) { val tooltip = LazyIdeToolTip(it) { createTitledList(tagGroup) { label, tag, _ -> label.text = tag.name val color = tag.color if (color != null) { //TODO: need a separate untinted icon to color properly label.icon = IconUtil.colorize(CollaborationToolsIcons.Branch, color) } else { label.icon = CollaborationToolsIcons.Branch } } } toolTipManager.setCustomTooltip(it, tooltip) } else { toolTipManager.setCustomTooltip(it, null) } } state.apply { font = JBUI.Fonts.smallFont() text = presentation.state isVisible = presentation.state != null } statePanel.isVisible = presentation.state != null nonMergeable.apply { val status = presentation.mergeableStatus icon = status?.icon toolTipText = status?.tooltip isVisible = status != null } buildStatus.apply { val status = presentation.buildStatus icon = status?.icon toolTipText = status?.tooltip isVisible = status != null } showUsersIcon(userGroup1, presentation.userGroup1) showUsersIcon(userGroup2, presentation.userGroup2) comments.apply { val counter = presentation.commentsCounter icon = CollaborationToolsIcons.Comment text = counter?.count.toString() toolTipText = counter?.tooltip isVisible = counter != null } return this } private fun <T> createTitledList(collection: NamedCollection<T>, customizer: SimpleListCellRenderer.Customizer<T>): JComponent { val title = JLabel().apply { font = JBUI.Fonts.smallFont() foreground = UIUtil.getContextHelpForeground() text = collection.namePlural border = JBUI.Borders.empty(0, 10, 4, 0) } val list = JBList(collection.items).apply { isOpaque = false cellRenderer = SimpleListCellRenderer.create(customizer) } return JPanel(BorderLayout()).apply { isOpaque = false add(title, BorderLayout.NORTH) add(list, BorderLayout.CENTER) } } private fun showUsersIcon(label: JLabel, users: NamedCollection<UserPresentation>?) { val icons = users?.items?.map { it.avatarIcon }?.nullize() if (icons == null) { label.isVisible = false label.icon = null } else { label.isVisible = true label.icon = OverlaidOffsetIconsIcon(icons) } if (users != null) { val tooltip = LazyIdeToolTip(label) { createTitledList(users) { label, user, _ -> label.text = user.getPresentableName() label.icon = user.avatarIcon } } toolTipManager.setCustomTooltip(label, tooltip) } } companion object { // TODO: register metadata provider somehow? private val stateForeground = JBColor.namedColor("ReviewList.state.foreground", 0x797979) private val stateBackground = JBColor.namedColor("ReviewList.state.background", 0xDFE1E5) /** * Paints [icons] in a stack - one over the other with a slight offset * Assumes that icons all have the same size */ private class OverlaidOffsetIconsIcon( private val icons: List<Icon>, private val offsetRate: Float = 0.4f ) : Icon { override fun getIconHeight(): Int = icons.maxOfOrNull { it.iconHeight } ?: 0 override fun getIconWidth(): Int { if (icons.isEmpty()) return 0 val iconWidth = icons.first().iconWidth val width = iconWidth + (icons.size - 1) * iconWidth * offsetRate return max(width.roundToInt(), 0) } override fun paintIcon(c: Component?, g: Graphics, x: Int, y: Int) { val bufferImage = ImageUtil.createImage(g, iconWidth, iconHeight, BufferedImage.TYPE_INT_ARGB) val bufferGraphics = bufferImage.createGraphics() try { paintToBuffer(bufferGraphics) } finally { bufferGraphics.dispose() } StartupUiUtil.drawImage(g, bufferImage, x, y, null) } private fun paintToBuffer(g: Graphics2D) { var rightEdge = iconWidth icons.reversed().forEachIndexed { index, icon -> val currentX = rightEdge - icon.iconWidth // cut out the part of the painted icon slightly bigger then the next one to create a visual gap if (index > 0) { val g2 = g.create() as Graphics2D try { val scaleX = 1.1 val scaleY = 1.1 // paint a bit higher, so that the cutout is centered g2.translate(0, -((iconHeight * scaleY - iconHeight) / 2).roundToInt()) g2.scale(scaleX, scaleY) g2.composite = AlphaComposite.DstOut icon.paintIcon(null, g2, currentX, 0) } finally { g2.dispose() } } icon.paintIcon(null, g, currentX, 0) rightEdge -= (icon.iconWidth * offsetRate).roundToInt() } } } /** * Draws a background with rounded corners */ private class StatePanel(stateLabel: JLabel) : JPanel(BorderLayout()) { init { add(stateLabel, BorderLayout.CENTER) isOpaque = false } override fun paintComponent(g: Graphics) { g as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE) g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB) val insets = insets val bounds = bounds JBInsets.removeFrom(bounds, insets) val arc = JBUIScale.scale(6) val rect = RoundRectangle2D.Float(0f, 0f, bounds.width.toFloat(), bounds.height.toFloat(), arc.toFloat(), arc.toFloat()) g.color = background g.fill(rect) super.paintComponent(g) } } /** * Lays out the components horizontally in two groups - [SwingConstants.LEFT] and [SwingConstants.RIGHT] anchored to the left and right sides respectively. * Respects the minimal sizes and does not force the components to grow. */ private class HorizontalSidesLayout(gap: Int) : AbstractLayoutManager() { private val gap = JBValue.UIInteger("", max(0, gap)) private val leftComponents = mutableListOf<Component>() private val rightComponents = mutableListOf<Component>() override fun addLayoutComponent(comp: Component, constraints: Any?) { when (constraints) { SwingConstants.RIGHT -> rightComponents.add(comp) else -> leftComponents.add(comp) } } override fun addLayoutComponent(name: String?, comp: Component) { addLayoutComponent(comp, SwingConstants.LEFT) } override fun removeLayoutComponent(comp: Component) { leftComponents.remove(comp) rightComponents.remove(comp) } override fun minimumLayoutSize(parent: Container): Dimension = getSize(leftComponents + rightComponents, Component::getMinimumSize) override fun preferredLayoutSize(parent: Container): Dimension = getSize(leftComponents + rightComponents, Component::getPreferredSize) private fun getSize(components: List<Component>, dimensionGetter: (Component) -> Dimension): Dimension { val visibleComponents = components.asSequence().filter(Component::isVisible) val dimension = visibleComponents.fold(Dimension()) { acc, component -> val size = dimensionGetter(component) acc.width += size.width acc.height = max(acc.height, size.height) acc } dimension.width += gap.get() * max(0, visibleComponents.count() - 1) return dimension } override fun layoutContainer(parent: Container) { val bounds = Rectangle(Point(0, 0), parent.size) JBInsets.removeFrom(bounds, parent.insets) val height = bounds.height val widthDeltaFraction = getWidthDeltaFraction(minimumLayoutSize(parent).width, preferredLayoutSize(parent).width, bounds.width) val leftMinWidth = getSize(leftComponents, Component::getMinimumSize).width val leftPrefWidth = getSize(leftComponents, Component::getPreferredSize).width val leftWidth = leftMinWidth + ((leftPrefWidth - leftMinWidth) * widthDeltaFraction).toInt() val leftWidthDeltaFraction = getWidthDeltaFraction(leftMinWidth, leftPrefWidth, leftWidth) layoutGroup(leftComponents, bounds.location, height, leftWidthDeltaFraction) val rightMinWidth = getSize(rightComponents, Component::getMinimumSize).width val rightPrefWidth = getSize(rightComponents, Component::getPreferredSize).width val rightWidth = min(bounds.width - leftWidth - gap.get(), rightPrefWidth) val rightX = bounds.x + max(leftWidth + gap.get(), bounds.width - rightWidth) val rightWidthDeltaFraction = getWidthDeltaFraction(rightMinWidth, rightPrefWidth, rightWidth) layoutGroup(rightComponents, Point(rightX, bounds.y), height, rightWidthDeltaFraction) } private fun getWidthDeltaFraction(minWidth: Int, prefWidth: Int, currentWidth: Int): Float { if (prefWidth <= minWidth) { return 0f } return ((currentWidth - minWidth) / (prefWidth - minWidth).toFloat()) .coerceAtLeast(0f) .coerceAtMost(1f) } private fun layoutGroup(components: List<Component>, startPoint: Point, height: Int, groupWidthDeltaFraction: Float) { var x = startPoint.x components.asSequence().filter(Component::isVisible).forEach { val minSize = it.minimumSize val prefSize = it.preferredSize val width = minSize.width + ((prefSize.width - minSize.width) * groupWidthDeltaFraction).toInt() val size = Dimension(width, min(prefSize.height, height)) val y = startPoint.y + (height - size.height) / 2 val location = Point(x, y) it.bounds = Rectangle(location, size) x += size.width + gap.get() } } } private class LazyIdeToolTip(component: JComponent, private val tipFactory: () -> JComponent) : IdeTooltip(component, Point(0, 0), null, component) { init { isToCenter = true layer = Balloon.Layer.top preferredPosition = Balloon.Position.atRight } override fun beforeShow(): Boolean { tipComponent = tipFactory() return true } } } }
apache-2.0
e5c56959b67179919b613712db94d077
34.491566
159
0.641727
4.696747
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinUnusedImportInspection.kt
1
11119
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.actions.OptimizeImportsProcessor import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerEx import com.intellij.codeInsight.daemon.impl.DaemonListeners import com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInspection.* import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.ProgressWrapper import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiEditorUtil import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.DocumentUtil import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.codeInsight.KotlinCodeInsightWorkspaceSettings import org.jetbrains.kotlin.idea.core.targetDescriptors import org.jetbrains.kotlin.idea.imports.KotlinImportOptimizer import org.jetbrains.kotlin.idea.imports.OptimizedImportsBuilder import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.KtInvokeFunctionReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.ImportPath class KotlinUnusedImportInspection : AbstractKotlinInspection() { class ImportData(val unusedImports: List<KtImportDirective>, val optimizerData: OptimizedImportsBuilder.InputData) companion object { fun analyzeImports(file: KtFile): ImportData? { if (file is KtCodeFragment) return null if (!RootKindFilter.projectSources.copy(includeScriptsOutsideSourceRoots = true).matches(file)) return null if (file.importDirectives.isEmpty()) return null val optimizerData = KotlinImportOptimizer.collectDescriptorsToImport(file) val directives = file.importDirectives val explicitlyImportedFqNames = directives .asSequence() .mapNotNull { it.importPath } .filter { !it.isAllUnder && !it.hasAlias() } .map { it.fqName } .toSet() val fqNames = optimizerData.namesToImport val parentFqNames = HashSet<FqName>() for ((_, fqName) in optimizerData.descriptorsToImport) { // we don't add parents of explicitly imported fq-names because such imports are not needed if (fqName in explicitlyImportedFqNames) continue val parentFqName = fqName.parent() if (!parentFqName.isRoot) { parentFqNames.add(parentFqName) } } val invokeFunctionCallFqNames = optimizerData.references.mapNotNull { val reference = (it.element as? KtCallExpression)?.mainReference as? KtInvokeFunctionReference ?: return@mapNotNull null (reference.resolve() as? KtNamedFunction)?.descriptor?.importableFqName } val importPaths = HashSet<ImportPath>(directives.size) val unusedImports = ArrayList<KtImportDirective>() val resolutionFacade = file.getResolutionFacade() for (directive in directives) { val importPath = directive.importPath ?: continue val isUsed = when { importPath.importedName in optimizerData.unresolvedNames -> true !importPaths.add(importPath) -> false importPath.isAllUnder -> optimizerData.unresolvedNames.isNotEmpty() || importPath.fqName in parentFqNames importPath.fqName in fqNames -> importPath.importedName?.let { it in fqNames.getValue(importPath.fqName) } ?: false importPath.fqName in invokeFunctionCallFqNames -> true // case for type alias else -> directive.targetDescriptors(resolutionFacade).firstOrNull()?.let { it.importableFqName in fqNames } ?: false } if (!isUsed) { unusedImports += directive } } return ImportData(unusedImports, optimizerData) } } override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<out ProblemDescriptor>? { if (file !is KtFile) return null val data = analyzeImports(file) ?: return null val problems = data.unusedImports.map { val fixes = arrayListOf<LocalQuickFix>() fixes.add(KotlinOptimizeImportsQuickFix(file)) if (!KotlinCodeInsightWorkspaceSettings.getInstance(file.project).optimizeImportsOnTheFly) { fixes.add(EnableOptimizeImportsOnTheFlyFix(file)) } manager.createProblemDescriptor( it, KotlinBundle.message("unused.import.directive"), isOnTheFly, fixes.toTypedArray(), ProblemHighlightType.LIKE_UNUSED_SYMBOL ) } if (isOnTheFly && !isUnitTestMode()) { scheduleOptimizeImportsOnTheFly(file, data.optimizerData) } return problems.toTypedArray() } private fun scheduleOptimizeImportsOnTheFly(file: KtFile, data: OptimizedImportsBuilder.InputData) { if (!KotlinCodeInsightWorkspaceSettings.getInstance(file.project).optimizeImportsOnTheFly) return val optimizedImports = KotlinImportOptimizer.prepareOptimizedImports(file, data) ?: return // return if already optimized // unwrap progress indicator val progress = generateSequence(ProgressManager.getInstance().progressIndicator) { (it as? ProgressWrapper)?.originalProgressIndicator }.last() as DaemonProgressIndicator val project = file.project val modificationCount = PsiModificationTracker.getInstance(project).modificationCount val invokeFixLater = Disposable { // later because should invoke when highlighting is finished ApplicationManager.getApplication().invokeLater { if (project.isDisposed) return@invokeLater val editor = PsiEditorUtil.findEditor(file) val currentModificationCount = PsiModificationTracker.getInstance(project).modificationCount if (editor != null && currentModificationCount == modificationCount && timeToOptimizeImportsOnTheFly( file, editor, project ) ) { optimizeImportsOnTheFly(file, optimizedImports, editor, project) } } } if (Disposer.isDisposed(progress)) return Disposer.register(progress, invokeFixLater) if (progress.isCanceled) { Disposer.dispose(invokeFixLater) Disposer.dispose(progress) progress.checkCanceled() } } private fun timeToOptimizeImportsOnTheFly(file: KtFile, editor: Editor, project: Project): Boolean { if (project.isDisposed || !file.isValid || editor.isDisposed || !file.isWritable) return false // do not optimize imports on the fly during undo/redo val undoManager = UndoManager.getInstance(project) if (undoManager.isUndoInProgress || undoManager.isRedoInProgress) return false // if we stand inside import statements, do not optimize val importList = file.importList ?: return false val leftSpace = importList.siblings(forward = false, withItself = false).firstOrNull() as? PsiWhiteSpace val rightSpace = importList.siblings(forward = true, withItself = false).firstOrNull() as? PsiWhiteSpace val left = leftSpace ?: importList val right = rightSpace ?: importList val importsRange = TextRange(left.textRange.startOffset, right.textRange.endOffset) if (importsRange.containsOffset(editor.caretModel.offset)) return false val codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project) if (!codeAnalyzer.isHighlightingAvailable(file)) return false if (!codeAnalyzer.isErrorAnalyzingFinished(file)) return false val document = editor.document var hasErrors = false DaemonCodeAnalyzerEx.processHighlights(document, project, HighlightSeverity.ERROR, 0, document.textLength) { highlightInfo -> if (!importsRange.containsRange(highlightInfo.startOffset, highlightInfo.endOffset)) { hasErrors = true false } else { true } } if (hasErrors) return false return DaemonListeners.canChangeFileSilently(file) } private fun optimizeImportsOnTheFly(file: KtFile, optimizedImports: List<ImportPath>, editor: Editor, project: Project) { val documentManager = PsiDocumentManager.getInstance(file.project) val doc = documentManager.getDocument(file) ?: editor.document documentManager.commitDocument(doc) DocumentUtil.writeInRunUndoTransparentAction { KotlinImportOptimizer.replaceImports(file, optimizedImports) PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(doc) } } private class EnableOptimizeImportsOnTheFlyFix(file: KtFile) : LocalQuickFixOnPsiElement(file), LowPriorityAction { override fun getText(): String = QuickFixBundle.message("enable.optimize.imports.on.the.fly") override fun getFamilyName() = name override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) { KotlinCodeInsightWorkspaceSettings.getInstance(project).optimizeImportsOnTheFly = true OptimizeImportsProcessor( project, file ).run() // we optimize imports manually because on-the-fly import optimization won't work while the caret is in imports } } }
apache-2.0
381193afbc83e6ba3750dacd9075f00b
46.926724
136
0.694577
5.518114
false
false
false
false
JohnnyShieh/Gank
app/src/main/kotlin/com/johnny/gank/model/GankType.kt
1
1085
package com.johnny.gank.model /* * Copyright (C) 2016 Johnny Shieh 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. */ /** * 干货类型: 福利 | Android | iOS | 休息视频 | 拓展资源 | 前端 | 瞎推荐 | App * * @author Johnny Shieh * @version 1.0 */ object GankType { const val WELFARE = "福利" const val ANDROID = "Android" const val IOS = "iOS" const val VIDEO = "休息视频" const val EXTRA = "拓展资源" const val FRONTEND = "前端" const val CASUAL = "瞎推荐" const val APP = "App" }
apache-2.0
32ae5e6d70f5d932730f25942d8f439c
27.25
75
0.679449
3.39
false
false
false
false
duncte123/SkyBot
src/main/kotlin/ml/duncte123/skybot/commands/essentials/CommandDumpCommand.kt
1
4157
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.commands.essentials import com.fasterxml.jackson.databind.json.JsonMapper import com.fasterxml.jackson.databind.node.ObjectNode import ml.duncte123.skybot.CommandManager import ml.duncte123.skybot.Settings import ml.duncte123.skybot.objects.command.Command import ml.duncte123.skybot.objects.command.CommandCategory import ml.duncte123.skybot.objects.command.CommandContext import ml.duncte123.skybot.utils.CommandUtils.isDev class CommandDumpCommand : Command() { init { this.category = CommandCategory.UNLISTED this.name = "commanddump" } override fun execute(ctx: CommandContext) { if (!isDev(ctx.author)) { return } val jackson = ctx.variables.jackson val data = parseCommandsToJson(ctx.commandManager, jackson) ctx.channel.sendFile(data, "commands.json").queue() } private fun parseCommandsToJson(commandManager: CommandManager, mapper: JsonMapper): ByteArray { val commands = commandManager.getFilteredCommands().sortedBy { it.name } // category -> List<Command> val map = mutableMapOf<String, MutableList<ObjectNode>>() for (command in commands) { val categoryList = map.getOrPut(command.category.display) { arrayListOf() } categoryList.add(command.toJson(mapper)) } return mapper.writeValueAsBytes(map.toSortedMap(compareBy { it })) } private fun Command.parseHelp(): String { val ownHelp = this.getHelp(this.name, Settings.PREFIX).mdToHtml() var s = "$ownHelp<br />Usage: ${this.getUsageInstructions(Settings.PREFIX, this.name).mdToHtml()}" if (this.aliases.isNotEmpty()) { val aliasHelp = getHelp(this.aliases[0], Settings.PREFIX).mdToHtml() s += if (aliasHelp == ownHelp) { "<br />Aliases: " + Settings.PREFIX + this.aliases.joinToString(", " + Settings.PREFIX) } else { buildString { [email protected] { append("<br />${Settings.PREFIX}$it => ${getHelp(it, Settings.PREFIX).mdToHtml()}") append("<br />Usage: ${getUsageInstructions(Settings.PREFIX, it).mdToHtml()}") } } } } return s } private fun String.mdToHtml(): String { return this.replace("&".toRegex(), "&amp;") .replace("<".toRegex(), "&lt;") .replace(">".toRegex(), "&gt;") .replace("\\n".toRegex(), "<br />") .replace("\\`\\`\\`(.*)\\`\\`\\`".toRegex(), "<pre class=\"code-block\"><code>$1</code></pre>") .replace("\\`([^\\`]+)\\`".toRegex(), "<code>$1</code>") .replace("\\*\\*(.*)\\*\\*".toRegex(), "<strong>$1</strong>") } private fun Command.toJson(mapper: JsonMapper): ObjectNode { val obj = mapper.createObjectNode() obj.put("name", this.name) .put("help", this.parseHelp()) val aliases = obj.putArray("aliases") this.aliases.forEach { aliases.add(it) } return obj } private fun CommandManager.getFilteredCommands(): List<Command> { return this.commandsList.filter { it.category != CommandCategory.UNLISTED }.map { it as Command } } }
agpl-3.0
ae2ad0d814e6e1c064d351e8aa3b574e
37.137615
107
0.6293
4.285567
false
false
false
false
blindpirate/gradle
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/ConfigurationCacheBuildTreeLifecycleControllerFactory.kt
1
4105
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.configurationcache import org.gradle.composite.internal.BuildTreeWorkGraphController import org.gradle.configurationcache.extensions.get import org.gradle.internal.build.BuildLifecycleController import org.gradle.internal.buildtree.BuildModelParameters import org.gradle.internal.buildtree.BuildTreeFinishExecutor import org.gradle.internal.buildtree.BuildTreeLifecycleController import org.gradle.internal.buildtree.BuildTreeLifecycleControllerFactory import org.gradle.internal.buildtree.BuildTreeWorkExecutor import org.gradle.internal.buildtree.DefaultBuildTreeLifecycleController import org.gradle.internal.model.StateTransitionControllerFactory import org.gradle.internal.operations.BuildOperationExecutor import org.gradle.internal.resources.ProjectLeaseRegistry class ConfigurationCacheBuildTreeLifecycleControllerFactory( buildModelParameters: BuildModelParameters, buildOperationExecutor: BuildOperationExecutor, projectLeaseRegistry: ProjectLeaseRegistry, private val cache: BuildTreeConfigurationCache, private val taskGraph: BuildTreeWorkGraphController, private val stateTransitionControllerFactory: StateTransitionControllerFactory ) : BuildTreeLifecycleControllerFactory { private val vintageFactory = VintageBuildTreeLifecycleControllerFactory(buildModelParameters, taskGraph, buildOperationExecutor, projectLeaseRegistry, stateTransitionControllerFactory) override fun createRootBuildController(targetBuild: BuildLifecycleController, workExecutor: BuildTreeWorkExecutor, finishExecutor: BuildTreeFinishExecutor): BuildTreeLifecycleController { // Some temporary wiring: the cache implementation is still scoped to the root build rather than the build tree cache.attachRootBuild(targetBuild.gradle.services.get()) cache.initializeCacheEntry() // Currently, apply the decoration only to the root build, as the cache implementation is still scoped to the root build (that is, it assumes it is only applied to the root build) return createController(true, targetBuild, workExecutor, finishExecutor) } override fun createController(targetBuild: BuildLifecycleController, workExecutor: BuildTreeWorkExecutor, finishExecutor: BuildTreeFinishExecutor): BuildTreeLifecycleController { return createController(false, targetBuild, workExecutor, finishExecutor) } private fun createController(applyCaching: Boolean, targetBuild: BuildLifecycleController, workExecutor: BuildTreeWorkExecutor, finishExecutor: BuildTreeFinishExecutor): BuildTreeLifecycleController { val defaultWorkPreparer = vintageFactory.createWorkPreparer(targetBuild) val workPreparer = if (applyCaching) { ConfigurationCacheAwareBuildTreeWorkPreparer(defaultWorkPreparer, cache) } else { defaultWorkPreparer } val defaultModelCreator = vintageFactory.createModelCreator(targetBuild) val modelCreator = if (applyCaching) { ConfigurationCacheAwareBuildTreeModelCreator(defaultModelCreator, cache) } else { defaultModelCreator } val finisher = if (applyCaching) { ConfigurationCacheAwareFinishExecutor(finishExecutor, cache) } else { finishExecutor } return DefaultBuildTreeLifecycleController(targetBuild, taskGraph, workPreparer, workExecutor, modelCreator, finisher, stateTransitionControllerFactory) } }
apache-2.0
0fa67004eba32874fe513fa118e25d46
49.060976
196
0.794153
5.202788
false
true
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/mysite/MySiteSourceManager.kt
1
5489
package org.wordpress.android.ui.mysite import androidx.lifecycle.LiveData import kotlinx.coroutines.CoroutineScope import org.wordpress.android.analytics.AnalyticsTracker.Stat import org.wordpress.android.ui.mysite.MySiteSource.MySiteRefreshSource import org.wordpress.android.ui.mysite.MySiteSource.SiteIndependentSource import org.wordpress.android.ui.mysite.MySiteUiState.PartialState import org.wordpress.android.ui.mysite.cards.dashboard.CardsSource import org.wordpress.android.ui.mysite.cards.dashboard.bloggingprompts.BloggingPromptCardSource import org.wordpress.android.ui.mysite.cards.domainregistration.DomainRegistrationSource import org.wordpress.android.ui.mysite.cards.quickstart.QuickStartCardSource import org.wordpress.android.ui.mysite.dynamiccards.DynamicCardMenuViewModel.DynamicCardMenuInteraction import org.wordpress.android.ui.mysite.dynamiccards.DynamicCardMenuViewModel.DynamicCardMenuInteraction.Hide import org.wordpress.android.ui.mysite.dynamiccards.DynamicCardMenuViewModel.DynamicCardMenuInteraction.Pin import org.wordpress.android.ui.mysite.dynamiccards.DynamicCardMenuViewModel.DynamicCardMenuInteraction.Unpin import org.wordpress.android.ui.mysite.dynamiccards.DynamicCardsSource import org.wordpress.android.ui.quickstart.QuickStartTracker import javax.inject.Inject class MySiteSourceManager @Inject constructor( private val quickStartTracker: QuickStartTracker, private val currentAvatarSource: CurrentAvatarSource, private val domainRegistrationSource: DomainRegistrationSource, private val dynamicCardsSource: DynamicCardsSource, private val quickStartCardSource: QuickStartCardSource, private val scanAndBackupSource: ScanAndBackupSource, private val selectedSiteSource: SelectedSiteSource, cardsSource: CardsSource, siteIconProgressSource: SiteIconProgressSource, private val bloggingPromptCardSource: BloggingPromptCardSource, private val selectedSiteRepository: SelectedSiteRepository ) { private val mySiteSources: List<MySiteSource<*>> = listOf( selectedSiteSource, siteIconProgressSource, quickStartCardSource, currentAvatarSource, domainRegistrationSource, scanAndBackupSource, dynamicCardsSource, cardsSource, bloggingPromptCardSource ) private val showDashboardCards: Boolean get() = selectedSiteRepository.getSelectedSite()?.isUsingWpComRestApi == true private val allSupportedMySiteSources: List<MySiteSource<*>> get() = if (showDashboardCards) { mySiteSources } else { mySiteSources.filterNot(CardsSource::class.java::isInstance) } private val siteIndependentSources: List<SiteIndependentSource<*>> get() = mySiteSources.filterIsInstance(SiteIndependentSource::class.java) fun build(coroutineScope: CoroutineScope, siteLocalId: Int?): List<LiveData<out PartialState>> { return if (siteLocalId != null) { allSupportedMySiteSources.map { source -> source.build(coroutineScope, siteLocalId) } } else { siteIndependentSources.map { source -> source.build(coroutineScope) } } } fun isRefreshing(): Boolean { val source = if (selectedSiteRepository.hasSelectedSite()) { allSupportedMySiteSources } else { siteIndependentSources } source.filterIsInstance(MySiteRefreshSource::class.java).forEach { if (it.isRefreshing() == true) { return true } } return false } fun refresh() { allSupportedMySiteSources.filterIsInstance(MySiteRefreshSource::class.java).forEach { if (it is SiteIndependentSource || selectedSiteRepository.hasSelectedSite()) it.refresh() } } fun onResume(isSiteSelected: Boolean) { when (isSiteSelected) { true -> refreshSubsetOfAllSources() false -> refresh() } } fun clear() { domainRegistrationSource.clear() scanAndBackupSource.clear() selectedSiteSource.clear() } private fun refreshSubsetOfAllSources() { selectedSiteSource.updateSiteSettingsIfNecessary() currentAvatarSource.refresh() if (selectedSiteRepository.hasSelectedSite()) quickStartCardSource.refresh() } fun refreshBloggingPrompts(onlyCurrentPrompt: Boolean) { if (onlyCurrentPrompt) { bloggingPromptCardSource.refreshTodayPrompt() } else { bloggingPromptCardSource.refresh() } } /* QUICK START */ fun refreshQuickStart() { quickStartCardSource.refresh() } suspend fun onQuickStartMenuInteraction(interaction: DynamicCardMenuInteraction) { when (interaction) { is DynamicCardMenuInteraction.Remove -> { quickStartTracker.track(Stat.QUICK_START_REMOVE_CARD_TAPPED) dynamicCardsSource.removeItem(interaction.cardType) quickStartCardSource.refresh() } is Pin -> dynamicCardsSource.pinItem(interaction.cardType) is Unpin -> dynamicCardsSource.unpinItem() is Hide -> { quickStartTracker.track(Stat.QUICK_START_HIDE_CARD_TAPPED) dynamicCardsSource.hideItem(interaction.cardType) quickStartCardSource.refresh() } } } }
gpl-2.0
f4b9ece46fdb948115e408aa23a72384
39.360294
109
0.715249
4.980944
false
false
false
false
ingokegel/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/buildtool/quickfix/InstallMaven2QuickFix.kt
4
2775
// 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.idea.maven.buildtool.quickfix import com.intellij.build.issue.BuildIssue import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.ide.plugins.PluginManagerConfigurable import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.Project import com.intellij.pom.Navigatable import org.jetbrains.idea.maven.MavenVersionSupportUtil import org.jetbrains.idea.maven.project.MavenProjectBundle import java.util.concurrent.CompletableFuture class InstallMaven2BuildIssue : BuildIssue { override val title = getTitle() override val description = getDescription() override val quickFixes = listOf(InstallMaven2QuickFix(), EnableMaven2QuickFix()) override fun getNavigatable(project: Project): Navigatable? = null companion object { private fun getTitle(): String { if (MavenVersionSupportUtil.isMaven2PluginDisabled()) return MavenProjectBundle.message("label.invalid.enable.maven2plugin") else return MavenProjectBundle.message("label.invalid.install.maven2plugin") } private fun getDescription(): String { if (MavenVersionSupportUtil.isMaven2PluginDisabled()) return MavenProjectBundle.message("label.invalid.enable.maven2plugin.with.link", EnableMaven2QuickFix.ID) else return MavenProjectBundle.message("label.invalid.install.maven2plugin.with.link", InstallMaven2QuickFix.ID) } } } private const val MAVEN2_SEARCH_STRING = "Maven2 Support" class InstallMaven2QuickFix : BuildIssueQuickFix { override val id = ID override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { ApplicationManager.getApplication().invokeLater { ShowSettingsUtil.getInstance().showSettingsDialog(project, PluginManagerConfigurable::class.java) { it.openMarketplaceTab(MAVEN2_SEARCH_STRING) } } return CompletableFuture.completedFuture(null) } companion object { const val ID = "install_maven_2_quick_fix" } } class EnableMaven2QuickFix : BuildIssueQuickFix { override val id = ID override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { ApplicationManager.getApplication().invokeLater { ShowSettingsUtil.getInstance().showSettingsDialog(project, PluginManagerConfigurable::class.java) { it.openInstalledTab(MAVEN2_SEARCH_STRING) } } return CompletableFuture.completedFuture(null) } companion object { const val ID = "enable_maven_2_quick_fix" } }
apache-2.0
6f297093cf9dd9f0369b4c1d14cbc158
35.051948
120
0.774414
4.671717
false
false
false
false
mdaniel/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/SourceFolderManagerImpl.kt
1
13874
// 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.externalSystem.service.project.manage import com.intellij.ProjectTopics import com.intellij.ide.projectView.actions.MarkRootActionBase import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.externalSystem.util.PathPrefixTreeMap import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.ModuleListener import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.SourceFolder import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.MultiMap import com.intellij.util.xmlb.annotations.XCollection import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.impl.legacyBridge.RootConfigurationAccessorForWorkspaceModel import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.toBuilder import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType import java.util.concurrent.Future @State(name = "sourceFolderManager", storages = [Storage(StoragePathMacros.CACHE_FILE)]) class SourceFolderManagerImpl(private val project: Project) : SourceFolderManager, Disposable, PersistentStateComponent<SourceFolderManagerState> { private val moduleNamesToSourceFolderState: MultiMap<String, SourceFolderModelState> = MultiMap.create() private var isDisposed = false private val mutex = Any() private var sourceFolders = PathPrefixTreeMap<SourceFolderModel>() private var sourceFoldersByModule = HashMap<String, ModuleModel>() private val operationsStates = mutableListOf<Future<*>>() override fun addSourceFolder(module: Module, url: String, type: JpsModuleSourceRootType<*>) { synchronized(mutex) { sourceFolders[url] = SourceFolderModel(module, url, type) addUrlToModuleModel(module, url) } ApplicationManager.getApplication().invokeLater(Runnable { VirtualFileManager.getInstance().refreshAndFindFileByUrl(url) }, project.disposed) } override fun setSourceFolderPackagePrefix(url: String, packagePrefix: String?) { synchronized(mutex) { val sourceFolder = sourceFolders[url] ?: return sourceFolder.packagePrefix = packagePrefix } } override fun setSourceFolderGenerated(url: String, generated: Boolean) { synchronized(mutex) { val sourceFolder = sourceFolders[url] ?: return sourceFolder.generated = generated } } override fun removeSourceFolders(module: Module) { synchronized(mutex) { val moduleModel = sourceFoldersByModule.remove(module.name) ?: return moduleModel.sourceFolders.forEach { sourceFolders.remove(it) } } } override fun dispose() { assert(!isDisposed) { "Source folder manager already disposed" } isDisposed = true } @TestOnly fun isDisposed() = isDisposed @TestOnly fun getSourceFolders(moduleName: String) = synchronized(mutex) { sourceFoldersByModule[moduleName]?.sourceFolders } private fun removeSourceFolder(url: String) { synchronized(mutex) { val sourceFolder = sourceFolders.remove(url) ?: return val module = sourceFolder.module val moduleModel = sourceFoldersByModule[module.name] ?: return val sourceFolders = moduleModel.sourceFolders sourceFolders.remove(url) if (sourceFolders.isEmpty()) { sourceFoldersByModule.remove(module.name) } } } private data class SourceFolderModel( val module: Module, val url: String, val type: JpsModuleSourceRootType<*>, var packagePrefix: String? = null, var generated: Boolean = false ) private data class ModuleModel( val module: Module, val sourceFolders: MutableSet<String> = CollectionFactory.createFilePathSet() ) init { project.messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { val sourceFoldersToChange = HashMap<Module, ArrayList<Pair<VirtualFile, SourceFolderModel>>>() val virtualFileManager = VirtualFileManager.getInstance() for (event in events) { if (event !is VFileCreateEvent) { continue } val allDescendantValues = synchronized(mutex) { sourceFolders.getAllDescendantValues(VfsUtilCore.pathToUrl(event.path)) } for (sourceFolder in allDescendantValues) { val sourceFolderFile = virtualFileManager.refreshAndFindFileByUrl(sourceFolder.url) if (sourceFolderFile != null && sourceFolderFile.isValid) { sourceFoldersToChange.computeIfAbsent(sourceFolder.module) { ArrayList() }.add(Pair(event.file!!, sourceFolder)) removeSourceFolder(sourceFolder.url) } } } val application = ApplicationManager.getApplication() val future = application.executeOnPooledThread { updateSourceFolders(sourceFoldersToChange) } if (application.isUnitTestMode) { ApplicationManager.getApplication().assertIsDispatchThread() operationsStates.removeIf { it.isDone } operationsStates.add(future) } } }) project.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener { override fun modulesAdded(project: Project, modules: List<Module>) { synchronized(mutex) { for (module in modules) { moduleNamesToSourceFolderState[module.name].forEach { loadSourceFolderState(it, module) } moduleNamesToSourceFolderState.remove(module.name) } } } }) } fun rescanAndUpdateSourceFolders() { val sourceFoldersToChange = HashMap<Module, ArrayList<Pair<VirtualFile, SourceFolderModel>>>() val virtualFileManager = VirtualFileManager.getInstance() val values = synchronized(mutex) { sourceFolders.values } for (sourceFolder in values) { val sourceFolderFile = virtualFileManager.refreshAndFindFileByUrl(sourceFolder.url) if (sourceFolderFile != null && sourceFolderFile.isValid) { sourceFoldersToChange.computeIfAbsent(sourceFolder.module) { ArrayList() }.add(Pair(sourceFolderFile, sourceFolder)) removeSourceFolder(sourceFolder.url) } } updateSourceFolders(sourceFoldersToChange) } private fun updateSourceFolders(sourceFoldersToChange: Map<Module, List<Pair<VirtualFile, SourceFolderModel>>>) { sourceFoldersToChange.keys.groupBy { it.project }.forEach { (key, values) -> batchUpdateModels(key, values) { model -> val p = sourceFoldersToChange[model.module] ?: error("Value for the module ${model.module.name} should be available") for ((eventFile, sourceFolders) in p) { val (_, url, type, packagePrefix, generated) = sourceFolders val contentEntry = MarkRootActionBase.findContentEntry(model, eventFile) ?: model.addContentEntry(url) val sourceFolder = contentEntry.addSourceFolder(url, type) if (!packagePrefix.isNullOrEmpty()) { sourceFolder.packagePrefix = packagePrefix } setForGeneratedSources(sourceFolder, generated) } } } } private fun batchUpdateModels(project: Project, modules: Collection<Module>, modifier: (ModifiableRootModel) -> Unit) { val diffBuilder = WorkspaceModel.getInstance(project).entityStorage.current.toBuilder() val modifiableRootModels = modules.asSequence().filter { !it.isDisposed }.map { module -> val moduleRootComponentBridge = ModuleRootManager.getInstance(module) as ModuleRootComponentBridge val modifiableRootModel = moduleRootComponentBridge.getModifiableModelForMultiCommit(ExternalSystemRootConfigurationAccessor(diffBuilder), false) modifiableRootModel as ModifiableRootModelBridge modifier.invoke(modifiableRootModel) modifiableRootModel.prepareForCommit() modifiableRootModel }.toList() ApplicationManager.getApplication().invokeAndWait { WriteAction.run<RuntimeException> { if (project.isDisposed) return@run WorkspaceModel.getInstance(project).updateProjectModel { updater -> updater.addDiff(diffBuilder) } modifiableRootModels.forEach { it.postCommit() } } } } private fun setForGeneratedSources(folder: SourceFolder, generated: Boolean) { val jpsElement = folder.jpsElement val properties = jpsElement.getProperties(JavaModuleSourceRootTypes.SOURCES) if (properties != null) properties.isForGeneratedSources = generated } override fun getState(): SourceFolderManagerState { synchronized(mutex) { return SourceFolderManagerState(sourceFolders.valueSequence .mapNotNull { model -> val modelTypeName = dictionary.entries.find { it.value == model.type }?.key ?: return@mapNotNull null SourceFolderModelState(model.module.name, model.url, modelTypeName, model.packagePrefix, model.generated) } .toList()) } } override fun loadState(state: SourceFolderManagerState) { synchronized(mutex) { resetModuleAddedListeners() if (isDisposed) { return } sourceFolders = PathPrefixTreeMap() sourceFoldersByModule = HashMap() val moduleManager = ModuleManager.getInstance(project) state.sourceFolders.forEach { model -> val module = moduleManager.findModuleByName(model.moduleName) if (module == null) { listenToModuleAdded(model) return@forEach } loadSourceFolderState(model, module) } } } private fun resetModuleAddedListeners() = moduleNamesToSourceFolderState.clear() private fun listenToModuleAdded(model: SourceFolderModelState) = moduleNamesToSourceFolderState.putValue(model.moduleName, model) private fun loadSourceFolderState(model: SourceFolderModelState, module: Module) { val rootType: JpsModuleSourceRootType<*> = dictionary[model.type] ?: return val url = model.url sourceFolders[url] = SourceFolderModel(module, url, rootType, model.packagePrefix, model.generated) addUrlToModuleModel(module, url) } private fun addUrlToModuleModel(module: Module, url: String) { val moduleModel = sourceFoldersByModule.getOrPut(module.name) { ModuleModel(module).also { Disposer.register(module, Disposable { removeSourceFolders(module) }) } } moduleModel.sourceFolders.add(url) } @TestOnly @Throws(Exception::class) fun consumeBulkOperationsState(stateConsumer: (Future<*>) -> Unit) { ApplicationManager.getApplication().assertIsDispatchThread() assert(ApplicationManager.getApplication().isUnitTestMode) for (operationsState in operationsStates) { stateConsumer.invoke(operationsState) } } companion object { val dictionary = mapOf<String, JpsModuleSourceRootType<*>>( "SOURCE" to JavaSourceRootType.SOURCE, "TEST_SOURCE" to JavaSourceRootType.TEST_SOURCE, "RESOURCE" to JavaResourceRootType.RESOURCE, "TEST_RESOURCE" to JavaResourceRootType.TEST_RESOURCE ) } } class ExternalSystemRootConfigurationAccessor(override val actualDiffBuilder: MutableEntityStorage) : RootConfigurationAccessor(), RootConfigurationAccessorForWorkspaceModel data class SourceFolderManagerState(@get:XCollection(style = XCollection.Style.v2) val sourceFolders: Collection<SourceFolderModelState>) { constructor() : this(mutableListOf()) } data class SourceFolderModelState(var moduleName: String, var url: String, var type: String, var packagePrefix: String?, var generated: Boolean) { constructor(): this("", "", "", null, false) }
apache-2.0
669f53b35d9a5df91319c37924a65c7c
41.95356
147
0.701384
5.367118
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-13/app-code/app/src/main/java/dev/mfazio/abl/settings/SaveSettingsWorker.kt
2
1397
package dev.mfazio.abl.settings import android.content.Context import android.util.Log import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import dev.mfazio.abl.api.models.AppSettingsApiModel import dev.mfazio.abl.api.services.getDefaultABLService class SaveSettingsWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) { override suspend fun doWork(): Result = try { val userName = inputData.getString(userNameKey) if (userName != null) { Log.i(TAG, "Saving user settings for $userName") getDefaultABLService().saveAppSettings( AppSettingsApiModel( userName, inputData.getString(favoriteTeamKey) ?: "", inputData.getBoolean(favoriteTeamColorCheckKey, false), inputData.getString(startingScreenKey) ?: "" ) ) } Result.success() } catch (ex: Exception) { Log.e(TAG, "Exception saving settings to API") Result.failure() } companion object { const val TAG = "SaveSettingsWorker" const val userNameKey = "userName" const val favoriteTeamKey = "favoriteTeam" const val favoriteTeamColorCheckKey = "favoriteTeamColorCheck" const val startingScreenKey = "startingScreenKey" } }
apache-2.0
30cd77e7e48e876a0eb9e2f5714c9b58
33.097561
75
0.652112
4.953901
false
false
false
false
squanchy-dev/squanchy-android
app/src/main/java/net/squanchy/favorites/view/FavoritesListView.kt
1
1237
package net.squanchy.favorites.view import android.content.Context import android.util.AttributeSet import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import net.squanchy.R import net.squanchy.support.view.CardSpacingItemDecorator import net.squanchy.support.view.setAdapterIfNone internal class FavoritesListView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : RecyclerView(context, attrs, defStyle) { private val adapter = FavoritesAdapter(context) override fun onFinishInflate() { super.onFinishInflate() val layoutManager = LinearLayoutManager(context) setLayoutManager(layoutManager) val horizontalSpacing = getResources().getDimensionPixelSize(R.dimen.card_horizontal_margin) val verticalSpacing = getResources().getDimensionPixelSize(R.dimen.card_vertical_margin) addItemDecoration(CardSpacingItemDecorator(horizontalSpacing, verticalSpacing)) } fun updateWith(newData: List<FavoritesItem>, showRoom: Boolean, listener: OnFavoriteClickListener) { setAdapterIfNone(adapter) adapter.updateWith(newData, showRoom, listener) } }
apache-2.0
3c0bf963490c4979e98d170ad113ce0c
35.382353
104
0.774454
4.967871
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/serialonly/TartuTransitFactory.kt
1
3722
/* * TartuTransitData.kt * * Copyright 2018 Google Inc. * * Authors: Vladimir Serbinenko * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.serialonly import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.classic.ClassicCard import au.id.micolous.metrodroid.card.classic.ClassicCardTransitFactory import au.id.micolous.metrodroid.card.classic.ClassicSector import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.CardInfo import au.id.micolous.metrodroid.transit.TransitData import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.transit.TransitRegion import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray /** * Transit data type for Tartu bus card. * * * This is a very limited implementation of reading TartuBus, because only * little data is stored on the card * * * Documentation of format: https://github.com/micolous/metrodroid/wiki/TartuBus */ object TartuTransitFactory : ClassicCardTransitFactory { private const val NAME = "Tartu Bus" private val CARD_INFO = CardInfo( name = NAME, cardType = CardType.MifareClassic, imageId = R.drawable.tartu, imageAlphaId = R.drawable.iso7810_id1_alpha, locationId = R.string.location_tartu, region = TransitRegion.ESTONIA, resourceExtraNote = R.string.card_note_card_number_only) override fun earlyCheck(sectors: List<ClassicSector>): Boolean { val sector0 = sectors[0] if (sector0[1].data.byteArrayToInt(2, 4) != 0x03e103e1) return false val sector1 = sectors[1] if (!sector1[0].data.sliceOffLen(7, 9) .contentEquals(ImmutableByteArray.fromASCII("pilet.ee:"))) return false if (!sector1[1].data.sliceOffLen(0, 6) .contentEquals(ImmutableByteArray.fromASCII("ekaart"))) return false return true } override val earlySectors get() = 2 override fun parseTransitIdentity(card: ClassicCard) = TransitIdentity(NAME, parseSerial(card).substring(8)) override fun parseTransitData(card: ClassicCard): TransitData = TartuTransitData(mSerial = parseSerial(card)) override val allCards get() = listOf(CARD_INFO) @Parcelize private data class TartuTransitData (private val mSerial: String): SerialOnlyTransitData() { override val extraInfo: List<ListItem> get() = listOf(ListItem(R.string.full_serial_number, mSerial)) override val reason: SerialOnlyTransitData.Reason get() = SerialOnlyTransitData.Reason.NOT_STORED override val serialNumber get() = mSerial.substring(8) override val cardName get() = NAME } private fun parseSerial(card: ClassicCard) = card[2, 0].data.sliceOffLen(7, 9).readASCII() + card[2, 1].data.sliceOffLen(0, 10).readASCII() }
gpl-3.0
ced0f17e35b2b28e1f8ce3137df732e3
36.59596
96
0.702311
4.103638
false
false
false
false
square/picasso
picasso/src/test/java/com/squareup/picasso3/TestUtils.kt
1
15335
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.picasso3 import android.app.Notification import android.content.ContentResolver import android.content.Context import android.content.pm.PackageManager import android.content.pm.PackageManager.NameNotFoundException import android.content.res.Resources import android.graphics.Bitmap.Config.ALPHA_8 import android.graphics.Bitmap.Config.ARGB_8888 import android.graphics.drawable.Drawable import android.net.NetworkInfo import android.net.Uri import android.os.IBinder import android.provider.ContactsContract.Contacts.CONTENT_URI import android.provider.ContactsContract.Contacts.Photo import android.provider.MediaStore.Images import android.provider.MediaStore.Video import android.util.TypedValue import android.view.ViewTreeObserver import android.widget.ImageView import android.widget.RemoteViews import com.squareup.picasso3.BitmapHunterTest.TestableBitmapHunter import com.squareup.picasso3.Picasso.LoadedFrom.MEMORY import com.squareup.picasso3.Picasso.Priority import com.squareup.picasso3.Picasso.RequestTransformer import com.squareup.picasso3.RequestHandler.Result import com.squareup.picasso3.RequestHandler.Result.Bitmap import okhttp3.Call import okhttp3.Response import okio.Timeout import org.mockito.ArgumentCaptor import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.Mockito.doAnswer import org.mockito.Mockito.doReturn import org.mockito.Mockito.mock import org.mockito.invocation.InvocationOnMock import java.io.File import java.io.IOException import java.util.concurrent.Callable import java.util.concurrent.ExecutorService import java.util.concurrent.Future import java.util.concurrent.TimeUnit internal object TestUtils { val URI_1: Uri = Uri.parse("http://example.com/1.png") val URI_2: Uri = Uri.parse("http://example.com/2.png") const val STABLE_1 = "stableExampleKey1" val SIMPLE_REQUEST: Request = Request.Builder(URI_1).build() val URI_KEY_1: String = SIMPLE_REQUEST.key val URI_KEY_2: String = Request.Builder(URI_2).build().key val STABLE_URI_KEY_1: String = Request.Builder(URI_1).stableKey(STABLE_1).build().key private val FILE_1 = File("C:\\windows\\system32\\logo.exe") val FILE_KEY_1: String = Request.Builder(Uri.fromFile(FILE_1)).build().key val FILE_1_URL: Uri = Uri.parse("file:///" + FILE_1.path) val FILE_1_URL_NO_AUTHORITY: Uri = Uri.parse("file:/" + FILE_1.parent) val MEDIA_STORE_CONTENT_1_URL: Uri = Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendPath("1").build() val MEDIA_STORE_CONTENT_2_URL: Uri = Video.Media.EXTERNAL_CONTENT_URI.buildUpon().appendPath("1").build() val MEDIA_STORE_CONTENT_KEY_1: String = Request.Builder(MEDIA_STORE_CONTENT_1_URL).build().key val MEDIA_STORE_CONTENT_KEY_2: String = Request.Builder(MEDIA_STORE_CONTENT_2_URL).build().key val CONTENT_1_URL: Uri = Uri.parse("content://zip/zap/zoop.jpg") val CONTENT_KEY_1: String = Request.Builder(CONTENT_1_URL).build().key val CONTACT_URI_1: Uri = CONTENT_URI.buildUpon().appendPath("1234").build() val CONTACT_KEY_1: String = Request.Builder(CONTACT_URI_1).build().key val CONTACT_PHOTO_URI_1: Uri = CONTENT_URI.buildUpon().appendPath("1234").appendPath(Photo.CONTENT_DIRECTORY).build() val CONTACT_PHOTO_KEY_1: String = Request.Builder(CONTACT_PHOTO_URI_1).build().key const val RESOURCE_ID_1 = 1 val RESOURCE_ID_KEY_1: String = Request.Builder(RESOURCE_ID_1).build().key val ASSET_URI_1: Uri = Uri.parse("file:///android_asset/foo/bar.png") val ASSET_KEY_1: String = Request.Builder(ASSET_URI_1).build().key private const val RESOURCE_PACKAGE = "com.squareup.picasso3" private const val RESOURCE_TYPE = "drawable" private const val RESOURCE_NAME = "foo" val RESOURCE_ID_URI: Uri = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(RESOURCE_PACKAGE) .appendPath(RESOURCE_ID_1.toString()) .build() val RESOURCE_ID_URI_KEY: String = Request.Builder(RESOURCE_ID_URI).build().key val RESOURCE_TYPE_URI: Uri = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(RESOURCE_PACKAGE) .appendPath(RESOURCE_TYPE) .appendPath(RESOURCE_NAME) .build() val RESOURCE_TYPE_URI_KEY: String = Request.Builder(RESOURCE_TYPE_URI).build().key val CUSTOM_URI: Uri = Uri.parse("foo://bar") val CUSTOM_URI_KEY: String = Request.Builder(CUSTOM_URI).build().key const val BITMAP_RESOURCE_VALUE = "foo.png" const val XML_RESOURCE_VALUE = "foo.xml" private val DEFAULT_CONFIG = ARGB_8888 private const val DEFAULT_CACHE_SIZE = 123 const val CUSTOM_HEADER_NAME = "Cache-Control" const val CUSTOM_HEADER_VALUE = "no-cache" fun mockPackageResourceContext(): Context { val context = mock(Context::class.java) val pm = mock(PackageManager::class.java) val res = mock(Resources::class.java) doReturn(pm).`when`(context).packageManager try { doReturn(res).`when`(pm).getResourcesForApplication(RESOURCE_PACKAGE) } catch (e: NameNotFoundException) { throw RuntimeException(e) } doReturn(RESOURCE_ID_1).`when`(res) .getIdentifier(RESOURCE_NAME, RESOURCE_TYPE, RESOURCE_PACKAGE) return context } fun mockResources(resValueString: String): Resources { val resources = mock(Resources::class.java) doAnswer { invocation: InvocationOnMock -> val args = invocation.arguments (args[1] as TypedValue).string = resValueString null }.`when`(resources).getValue(anyInt(), any(TypedValue::class.java), anyBoolean()) return resources } fun mockRequest(uri: Uri): Request = Request.Builder(uri).build() fun mockAction( picasso: Picasso, key: String, uri: Uri? = null, target: Any = mockBitmapTarget(), resourceId: Int = 0, priority: Priority? = null, tag: String? = null, headers: Map<String, String> = emptyMap(), ): FakeAction { val builder = Request.Builder(uri, resourceId, DEFAULT_CONFIG).stableKey(key) if (priority != null) { builder.priority(priority) } if (tag != null) { builder.tag(tag) } headers.forEach { (key, value) -> builder.addHeader(key, value) } val request = builder.build() return mockAction(picasso, request, target) } fun mockAction(picasso: Picasso, request: Request, target: Any = mockBitmapTarget()) = FakeAction(picasso, request, target) fun mockImageViewTarget(): ImageView = mock(ImageView::class.java) fun mockRemoteViews(): RemoteViews = mock(RemoteViews::class.java) fun mockNotification(): Notification = mock(Notification::class.java) fun mockFitImageViewTarget(alive: Boolean): ImageView { val observer = mock(ViewTreeObserver::class.java) `when`(observer.isAlive).thenReturn(alive) val mock = mock(ImageView::class.java) `when`(mock.windowToken).thenReturn(mock(IBinder::class.java)) `when`(mock.viewTreeObserver).thenReturn(observer) return mock } fun mockBitmapTarget(): BitmapTarget = mock(BitmapTarget::class.java) fun mockDrawableTarget(): DrawableTarget = mock(DrawableTarget::class.java) fun mockCallback(): Callback = mock(Callback::class.java) fun mockDeferredRequestCreator( creator: RequestCreator?, target: ImageView ): DeferredRequestCreator { val observer = mock(ViewTreeObserver::class.java) `when`(target.viewTreeObserver).thenReturn(observer) return DeferredRequestCreator(creator!!, target, null) } fun mockRequestCreator(picasso: Picasso) = RequestCreator(picasso, null, 0) fun mockNetworkInfo(isConnected: Boolean = false): NetworkInfo { val mock = mock(NetworkInfo::class.java) `when`(mock.isConnected).thenReturn(isConnected) `when`(mock.isConnectedOrConnecting).thenReturn(isConnected) return mock } fun mockHunter( picasso: Picasso, result: Result, action: Action, e: Exception? = null, shouldRetry: Boolean = false, supportsReplay: Boolean = false, dispatcher: Dispatcher = mock(Dispatcher::class.java), ): BitmapHunter = TestableBitmapHunter( picasso = picasso, dispatcher = dispatcher, cache = PlatformLruCache(0), action = action, result = (result as Bitmap).bitmap, exception = e, shouldRetry = shouldRetry, supportsReplay = supportsReplay ) fun mockPicasso(context: Context): Picasso { // Inject a RequestHandler that can handle any request. val requestHandler: RequestHandler = object : RequestHandler() { override fun canHandleRequest(data: Request): Boolean { return true } override fun load(picasso: Picasso, request: Request, callback: Callback) { val defaultResult = makeBitmap() val result = RequestHandler.Result.Bitmap(defaultResult, MEMORY) callback.onSuccess(result) } } return mockPicasso(context, requestHandler) } fun mockPicasso(context: Context, requestHandler: RequestHandler): Picasso { return Picasso.Builder(context) .callFactory(UNUSED_CALL_FACTORY) .withCacheSize(0) .addRequestHandler(requestHandler) .build() } fun makeBitmap( width: Int = 10, height: Int = 10 ): android.graphics.Bitmap = android.graphics.Bitmap.createBitmap(width, height, ALPHA_8) fun makeLoaderWithDrawable(drawable: Drawable?): DrawableLoader = DrawableLoader { drawable } internal class FakeAction( picasso: Picasso, request: Request, private val target: Any ) : Action(picasso, request) { var completedResult: Result? = null var errorException: Exception? = null override fun complete(result: Result) { completedResult = result } override fun error(e: Exception) { errorException = e } override fun getTarget(): Any = target } val UNUSED_CALL_FACTORY = Call.Factory { throw AssertionError() } val NOOP_REQUEST_HANDLER: RequestHandler = object : RequestHandler() { override fun canHandleRequest(data: Request): Boolean = false override fun load(picasso: Picasso, request: Request, callback: Callback) = Unit } val NOOP_TRANSFORMER = RequestTransformer { Request.Builder(0).build() } private val NOOP_LISTENER = Picasso.Listener { _: Picasso, _: Uri?, _: Exception -> } val NO_TRANSFORMERS: List<RequestTransformer> = emptyList() val NO_HANDLERS: List<RequestHandler> = emptyList() val NO_EVENT_LISTENERS: List<EventListener> = emptyList() fun defaultPicasso( context: Context, hasRequestHandlers: Boolean, hasTransformers: Boolean ): Picasso { val builder = Picasso.Builder(context) if (hasRequestHandlers) { builder.addRequestHandler(NOOP_REQUEST_HANDLER) } if (hasTransformers) { builder.addRequestTransformer(NOOP_TRANSFORMER) } return builder .callFactory(UNUSED_CALL_FACTORY) .defaultBitmapConfig(DEFAULT_CONFIG) .executor(PicassoExecutorService()) .indicatorsEnabled(true) .listener(NOOP_LISTENER) .loggingEnabled(true) .withCacheSize(DEFAULT_CACHE_SIZE) .build() } internal class EventRecorder : EventListener { var maxCacheSize = 0 var cacheSize = 0 var cacheHits = 0 var cacheMisses = 0 var downloadSize: Long = 0 var decodedBitmap: android.graphics.Bitmap? = null var transformedBitmap: android.graphics.Bitmap? = null var closed = false override fun cacheMaxSize(maxSize: Int) { maxCacheSize = maxSize } override fun cacheSize(size: Int) { cacheSize = size } override fun cacheHit() { cacheHits++ } override fun cacheMiss() { cacheMisses++ } override fun downloadFinished(size: Long) { downloadSize = size } override fun bitmapDecoded(bitmap: android.graphics.Bitmap) { decodedBitmap = bitmap } override fun bitmapTransformed(bitmap: android.graphics.Bitmap) { transformedBitmap = bitmap } override fun close() { closed = true } } internal class PremadeCall( private val request: okhttp3.Request, private val response: Response ) : Call { override fun request(): okhttp3.Request = request override fun execute(): Response = response override fun enqueue(responseCallback: okhttp3.Callback) { try { responseCallback.onResponse(this, response) } catch (e: IOException) { throw AssertionError(e) } } override fun cancel(): Unit = throw AssertionError() override fun isExecuted(): Boolean = throw AssertionError() override fun isCanceled(): Boolean = throw AssertionError() override fun clone(): Call = throw AssertionError() override fun timeout(): Timeout = throw AssertionError() } class TestDelegatingService(private val delegate: ExecutorService) : ExecutorService { var submissions = 0 override fun shutdown() = delegate.shutdown() override fun shutdownNow(): List<Runnable> = throw AssertionError("Not implemented.") override fun isShutdown(): Boolean = delegate.isShutdown override fun isTerminated(): Boolean = throw AssertionError("Not implemented.") override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean = delegate.awaitTermination(timeout, unit) override fun <T> submit(task: Callable<T>): Future<T> = throw AssertionError("Not implemented.") override fun <T> submit(task: Runnable, result: T): Future<T> = throw AssertionError("Not implemented.") override fun submit(task: Runnable): Future<*> { submissions++ return delegate.submit(task) } override fun <T> invokeAll(tasks: Collection<Callable<T>?>): List<Future<T>> = throw AssertionError("Not implemented.") override fun <T> invokeAll( tasks: Collection<Callable<T>?>, timeout: Long, unit: TimeUnit ): List<Future<T>> = throw AssertionError("Not implemented.") override fun <T> invokeAny(tasks: Collection<Callable<T>?>): T = throw AssertionError("Not implemented.") override fun <T> invokeAny(tasks: Collection<Callable<T>?>, timeout: Long, unit: TimeUnit): T = throw AssertionError("Not implemented.") override fun execute(command: Runnable) = delegate.execute(command) } fun <T> any(type: Class<T>): T = Mockito.any(type) fun <T : Any> eq(value: T): T = Mockito.eq(value) ?: value inline fun <reified T : Any> argumentCaptor(): KArgumentCaptor<T> { return KArgumentCaptor(ArgumentCaptor.forClass(T::class.java)) } class KArgumentCaptor<T>( private val captor: ArgumentCaptor<T>, ) { val value: T get() = captor.value fun capture(): T = captor.capture() } }
apache-2.0
96ca640c067fc6c9fd497141ab8ff7be
34.252874
108
0.712749
4.090424
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/OpcodeReportingMethodVisitor.kt
4
2365
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto import org.jetbrains.org.objectweb.asm.Handle import org.jetbrains.org.objectweb.asm.Label import org.jetbrains.org.objectweb.asm.MethodVisitor import org.jetbrains.org.objectweb.asm.Opcodes /** * This class pipes all visit*Insn calls to the [reportOpcode] function. The derived class can process all visited opcodes * by overriding only [reportOpcode] function. */ open class OpcodeReportingMethodVisitor( private val delegate: OpcodeReportingMethodVisitor? = null ) : MethodVisitor(Opcodes.API_VERSION, delegate) { protected open fun reportOpcode(opcode: Int) { delegate?.reportOpcode(opcode) } override fun visitInsn(opcode: Int) = reportOpcode(opcode) override fun visitLdcInsn(value: Any?) = reportOpcode(Opcodes.LDC) override fun visitLookupSwitchInsn(dflt: Label?, keys: IntArray?, labels: Array<out Label>?) = reportOpcode(Opcodes.LOOKUPSWITCH) override fun visitMultiANewArrayInsn(descriptor: String?, numDimensions: Int) = reportOpcode(Opcodes.MULTIANEWARRAY) override fun visitIincInsn(variable: Int, increment: Int) = reportOpcode(Opcodes.IINC) override fun visitIntInsn(opcode: Int, operand: Int) = reportOpcode(opcode) override fun visitVarInsn(opcode: Int, variable: Int) = reportOpcode(opcode) override fun visitTypeInsn(opcode: Int, type: String?) = reportOpcode(opcode) override fun visitFieldInsn(opcode: Int, owner: String?, name: String?, descriptor: String?) = reportOpcode(opcode) override fun visitJumpInsn(opcode: Int, label: Label?) = reportOpcode(opcode) override fun visitTableSwitchInsn(min: Int, max: Int, dflt: Label?, vararg labels: Label?) = reportOpcode(Opcodes.TABLESWITCH) override fun visitMethodInsn(opcode: Int, owner: String, name: String, descriptor: String, isInterface: Boolean) = reportOpcode(opcode) override fun visitInvokeDynamicInsn( name: String?, descriptor: String?, bootstrapMethodHandle: Handle?, vararg bootstrapMethodArguments: Any? ) = reportOpcode(Opcodes.INVOKEDYNAMIC) }
apache-2.0
f41f525cf0cf4258ef503a0fd90daa50
46.3
158
0.730655
4.323583
false
false
false
false
GunoH/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyExtendedCompletionContributor.kt
9
4680
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.project.DumbAware import com.intellij.patterns.StandardPatterns import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiNamedElement import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.codeInsight.imports.AddImportHelper import com.jetbrains.python.psi.* import com.jetbrains.python.psi.resolve.QualifiedNameFinder /** * Provides basic functionality for extended completion. * * Extended code completion is actually a basic code completion that shows the names of classes, functions, modules and variables. * * To provide variants for extended completion override [doFillCompletionVariants] */ abstract class PyExtendedCompletionContributor : CompletionContributor(), DumbAware { protected val importingInsertHandler: InsertHandler<LookupElement> = InsertHandler { context, item -> addImportForLookupElement(context, item, context.tailOffset - 1) } protected val functionInsertHandler: InsertHandler<LookupElement> = object : PyFunctionInsertHandler() { override fun handleInsert(context: InsertionContext, item: LookupElement) { val tailOffset = context.tailOffset - 1 super.handleInsert(context, item) // adds parentheses, modifies tail offset context.commitDocument() addImportForLookupElement(context, item, tailOffset) } } protected val stringLiteralInsertHandler: InsertHandler<LookupElement> = InsertHandler { context, item -> val element = item.psiElement if (element == null) return@InsertHandler if (element is PyQualifiedNameOwner) { insertStringLiteralPrefix(element.qualifiedName, element.name, context) } else { val importPath = QualifiedNameFinder.findCanonicalImportPath(element, null) if (importPath != null) { insertStringLiteralPrefix(importPath.toString(), importPath.lastComponent.toString(), context) } } } private fun insertStringLiteralPrefix(qualifiedName: String?, name: String?, context: InsertionContext) { if (qualifiedName != null && name != null) { val qualifiedNamePrefix = qualifiedName.substring(0, qualifiedName.length - name.length) context.document.insertString(context.startOffset, qualifiedNamePrefix) } } /** * Checks whether completion should be performed for a given [parameters] and delegates actual work to [doFillCompletionVariants]. */ final override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) { if (!shouldDoCompletion(parameters, result)) return doFillCompletionVariants(parameters, result) } /** * Subclasses should override the method to provide completion variants. */ protected abstract fun doFillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) private fun shouldDoCompletion(parameters: CompletionParameters, result: CompletionResultSet): Boolean { if (!parameters.isExtendedCompletion) { return false } if (result.prefixMatcher.prefix.isEmpty()) { result.restartCompletionOnPrefixChange(StandardPatterns.string().longerThan(0)) return false } val element = parameters.position val parent = element.parent if (parent is PyReferenceExpression && parent.isQualified) { return false } if (parent is PyStringLiteralExpression) { val prefix = parent.text.substring(0, parameters.offset - parent.textRange.startOffset) if (prefix.contains(".")) { return false } } return PsiTreeUtil.getParentOfType(element, PyImportStatementBase::class.java) == null } } private fun addImportForLookupElement(context: InsertionContext, item: LookupElement, tailOffset: Int) { val manager = PsiDocumentManager.getInstance(context.project) val document = manager.getDocument(context.file) if (document != null) { manager.commitDocument(document) } val ref = context.file.findReferenceAt(tailOffset) if (ref == null || ref.resolve() === item.psiElement) { // no import statement needed return } WriteCommandAction.writeCommandAction(context.project, context.file).run<RuntimeException> { val psiElement = item.psiElement if (psiElement is PsiNamedElement) { AddImportHelper.addImport(psiElement, context.file, ref.element as PyElement) } } }
apache-2.0
ffe9e90ff40afa4bb0f7b3abb4444303
39.695652
140
0.758547
4.941922
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/entity/SystemPartition.kt
1
1354
package com.onyx.entity import com.onyx.descriptor.PartitionDescriptor import com.onyx.persistence.ManagedEntity import com.onyx.persistence.annotations.Attribute import com.onyx.persistence.annotations.Entity import com.onyx.persistence.annotations.Identifier import com.onyx.persistence.annotations.Relationship import com.onyx.persistence.annotations.values.CascadePolicy import com.onyx.persistence.annotations.values.FetchPolicy import com.onyx.persistence.annotations.values.RelationshipType import java.util.concurrent.CopyOnWriteArrayList /** * Created by timothy.osborn on 3/2/15. * * Partition information for an entity */ @Entity(fileName = "system") data class SystemPartition @JvmOverloads constructor( @Identifier var id: String = "", @Attribute var name: String = "", @Attribute var entityClass: String = "" ) : ManagedEntity() { constructor(descriptor: PartitionDescriptor, entity: SystemEntity):this ( id = entity.name + descriptor.name, name = descriptor.name, entityClass = entity.name ) @Relationship(type = RelationshipType.ONE_TO_MANY, cascadePolicy = CascadePolicy.SAVE, inverse = "partition", inverseClass = SystemPartitionEntry::class, fetchPolicy = FetchPolicy.EAGER) var entries: CopyOnWriteArrayList<SystemPartitionEntry> = CopyOnWriteArrayList() }
agpl-3.0
31868956053ce706ccdc90fc6ff5ad3e
31.238095
190
0.769572
4.453947
false
false
false
false
armcha/Ribble
app/src/main/kotlin/io/armcha/ribble/presentation/screen/shot/ShotFragment.kt
1
3026
package io.armcha.ribble.presentation.screen.shot import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.view.View import io.armcha.ribble.R import io.armcha.ribble.domain.entity.Shot import io.armcha.ribble.presentation.adapter.ShotRecyclerViewAdapter import io.armcha.ribble.presentation.adapter.listener.ShotClickListener import io.armcha.ribble.presentation.base_mvp.base.BaseFragment import io.armcha.ribble.presentation.screen.shot_detail.ShotDetailFragment import io.armcha.ribble.presentation.utils.S import io.armcha.ribble.presentation.utils.extensions.extraWithKey import io.armcha.ribble.presentation.utils.extensions.isPortrait import io.armcha.ribble.presentation.utils.extensions.takeColor import kotlinx.android.synthetic.main.fragment_shot.* import kotlinx.android.synthetic.main.progress_bar.* import javax.inject.Inject class ShotFragment : BaseFragment<ShotContract.View, ShotContract.Presenter>(), ShotContract.View, ShotClickListener { companion object { private const val SHOT_TYPE = "shot_type" fun newInstance(shotFragmentType: String) = ShotFragment().apply { arguments = Bundle().apply { putString(SHOT_TYPE, shotFragmentType) } } } @Inject protected lateinit var shotPresenter: ShotPresenter private var recyclerAdapter: ShotRecyclerViewAdapter? = null override fun initPresenter() = shotPresenter override val layoutResId = R.layout.fragment_shot override fun injectDependencies() = activityComponent.inject(this) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) progressBar.backgroundCircleColor = takeColor(R.color.colorPrimary) } override fun getShotType() = extraWithKey<String>(SHOT_TYPE) private fun updateAdapter(shotList: List<Shot>) { recyclerAdapter?.update(shotList) ?: this setUpRecyclerView shotList } private infix fun setUpRecyclerView(shotList: List<Shot>) { recyclerAdapter = ShotRecyclerViewAdapter(shotList, this) with(shotRecyclerView) { layoutManager = GridLayoutManager(activity, if (isPortrait()) 2 else 3) setHasFixedSize(true) adapter = recyclerAdapter scheduleLayoutAnimation() } } override fun onShotClicked(shot: Shot) { val bundle = ShotDetailFragment.getBundle(shot) goTo<ShotDetailFragment>( keepState = false, withCustomAnimation = true, arg = bundle) } override fun showLoading() { progressBar.start() } override fun hideLoading() { progressBar.stop() } override fun showError(message: String?) { showErrorDialog(message) } override fun showNoShots() { noShotsText.setAnimatedText(getString(S.no_shots)) } override fun onShotListReceive(shotList: List<Shot>) { updateAdapter(shotList) } }
apache-2.0
744dd8b8155fea80cc1738369fb82a54
32.622222
83
0.721414
4.655385
false
false
false
false
mdanielwork/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/CodeAnalysisBeforeCheckinShowOnlyNew.kt
1
5545
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.checkin import com.intellij.codeInsight.CodeSmellInfo import com.intellij.diff.tools.util.text.LineOffsetsUtil import com.intellij.diff.util.Range import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.CodeSmellDetector import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager import com.intellij.openapi.vcs.changes.shelf.ShelvedChangeList import com.intellij.openapi.vcs.ex.compareLines import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.MultiMap internal object CodeAnalysisBeforeCheckinShowOnlyNew { val LOG = Logger.getInstance(CodeAnalysisBeforeCheckinShowOnlyNew.javaClass) @JvmStatic fun runAnalysis(project: Project, selectedFiles: List<VirtualFile>, progressIndicator: ProgressIndicator) : List<CodeSmellInfo> { val codeSmellDetector = CodeSmellDetector.getInstance(project) val newCodeSmells = codeSmellDetector.findCodeSmells(selectedFiles) val location2CodeSmell = MultiMap<Pair<VirtualFile, Int>, CodeSmellInfo>() val file2Changes = HashMap<VirtualFile, List<Range>>() val changeListManager = ChangeListManager.getInstance(project) newCodeSmells.forEach { codeSmellInfo -> val virtualFile = FileDocumentManager.getInstance().getFile(codeSmellInfo.document) ?: return@forEach val unchanged = file2Changes.getOrPut(virtualFile) { try { val contentFromVcs = changeListManager.getChange(virtualFile)?.beforeRevision?.content ?: return@getOrPut emptyList() val documentContent = codeSmellInfo.document.immutableCharSequence ContainerUtil.newArrayList(compareLines(documentContent, contentFromVcs, LineOffsetsUtil.create(documentContent), LineOffsetsUtil.create(contentFromVcs)).iterateUnchanged()) } catch (e: VcsException) { LOG.warn("Couldn't load content", e) emptyList() } } val startLine = codeSmellInfo.startLine val range = unchanged.firstOrNull { it.start1 <= startLine && startLine < it.end1 } ?: return@forEach location2CodeSmell.putValue(Pair(virtualFile, range.start2 + startLine - range.start1), codeSmellInfo) } val commonCodeSmells = HashSet<CodeSmellInfo>() runAnalysisAfterShelvingSync(project, progressIndicator) { codeSmellDetector.findCodeSmells(selectedFiles.filter { it.exists() }).forEach { oldCodeSmell -> val file = FileDocumentManager.getInstance().getFile(oldCodeSmell.document) ?: return@forEach location2CodeSmell[Pair(file, oldCodeSmell.startLine)].forEach inner@{ newCodeSmell -> if (oldCodeSmell.description == newCodeSmell.description) { commonCodeSmells.add(newCodeSmell) return@inner } } } } return newCodeSmells.filter { !commonCodeSmells.contains(it) } } private fun runAnalysisAfterShelvingSync(project: Project, progressIndicator: ProgressIndicator, afterShelve: () -> Unit) { val operation = ShelveOperation(project) VcsFreezingProcess(project, VcsBundle.message("searching.for.code.smells.freezing.process")) { val progressManager = ProgressManager.getInstance() progressManager.executeNonCancelableSection { operation.save(progressIndicator) } try { afterShelve() } finally { progressManager.executeNonCancelableSection { operation.load(progressIndicator) } } }.execute() } private class ShelveOperation(project: Project) { val changeListManager = ChangeListManager.getInstance(project) as ChangeListManagerEx private val shelveChangeManager = ShelveChangesManager.getInstance(project) private var shelvedChangeListPairs = ArrayList<Pair<LocalChangeList, ShelvedChangeList>>() fun save(progressIndicator: ProgressIndicator): List<Change> { val changes = ArrayList<Change>() var i = 0 val changeLists = changeListManager.changeLists val size = changeLists.size changeLists.filter { it.changes.isNotEmpty() }.forEach { progressIndicator.fraction = (i++).toDouble() / size.toDouble() progressIndicator.text = VcsBundle.message("searching.for.code.smells.shelving", it.name) val shelveChanges = shelveChangeManager.shelveChanges(it.changes, it.name, true, true) changes.addAll(it.changes) shelvedChangeListPairs.add(Pair(it, shelveChanges)) } return changes } fun load(progressIndicator: ProgressIndicator) { var i = 0 val size = shelvedChangeListPairs.size shelvedChangeListPairs.forEach { (local, shelved) -> progressIndicator.fraction = (i++).toDouble() / size.toDouble() progressIndicator.text = VcsBundle.message("searching.for.code.smells.unshelving", shelved.name) shelveChangeManager.unshelveChangeList(shelved, null, null, local, false, true, false, null, null) } } } }
apache-2.0
45e9557e9b615881387ea30b4b4929b3
46.810345
140
0.734896
4.792567
false
false
false
false
iSoron/uhabits
uhabits-android/src/main/java/org/isoron/uhabits/widgets/views/CheckmarkWidgetView.kt
1
5834
/* * 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.widgets.views import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.view.View import android.widget.TextView import org.isoron.uhabits.HabitsApplication import org.isoron.uhabits.R import org.isoron.uhabits.activities.common.views.RingView import org.isoron.uhabits.activities.habits.list.views.toShortString import org.isoron.uhabits.core.models.Entry.Companion.NO import org.isoron.uhabits.core.models.Entry.Companion.SKIP import org.isoron.uhabits.core.models.Entry.Companion.UNKNOWN import org.isoron.uhabits.core.models.Entry.Companion.YES_AUTO import org.isoron.uhabits.core.models.Entry.Companion.YES_MANUAL import org.isoron.uhabits.core.preferences.Preferences import org.isoron.uhabits.inject.HabitsApplicationComponent import org.isoron.uhabits.utils.InterfaceUtils.getDimension import org.isoron.uhabits.utils.PaletteUtils.getAndroidTestColor import org.isoron.uhabits.utils.StyledResources import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt class CheckmarkWidgetView : HabitWidgetView { var activeColor: Int = 0 var percentage = 0f var name: String? = null private lateinit var ring: RingView private lateinit var label: TextView var entryValue = 0 var entryState = 0 var isNumerical = false private var preferences: Preferences? = null constructor(context: Context?) : super(context) { init() } constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) { init() } fun refresh() { if (backgroundPaint == null || frame == null) return val res = StyledResources(context) val bgColor: Int val fgColor: Int when (entryState) { YES_MANUAL, SKIP -> { bgColor = activeColor fgColor = res.getColor(R.attr.contrast0) setShadowAlpha(0x4f) backgroundPaint!!.color = bgColor frame!!.setBackgroundDrawable(background) } YES_AUTO, NO, UNKNOWN -> { bgColor = res.getColor(R.attr.cardBgColor) fgColor = res.getColor(R.attr.contrast60) setShadowAlpha(0x00) } else -> { bgColor = res.getColor(R.attr.cardBgColor) fgColor = res.getColor(R.attr.contrast60) setShadowAlpha(0x00) } } ring.setPercentage(percentage) ring.setColor(fgColor) ring.setBackgroundColor(bgColor) ring.setText(text) label.text = name label.setTextColor(fgColor) requestLayout() postInvalidate() } private val text: String get() = if (isNumerical) { (max(0, entryValue) / 1000.0).toShortString() } else when (entryState) { YES_MANUAL, YES_AUTO -> resources.getString(R.string.fa_check) SKIP -> resources.getString(R.string.fa_skipped) UNKNOWN -> { run { if (preferences!!.areQuestionMarksEnabled) { return resources.getString(R.string.fa_question) } else { resources.getString(R.string.fa_times) } } resources.getString(R.string.fa_times) } NO -> resources.getString(R.string.fa_times) else -> resources.getString(R.string.fa_times) } override val innerLayoutId: Int get() = R.layout.widget_checkmark override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var width = MeasureSpec.getSize(widthMeasureSpec) var height = MeasureSpec.getSize(heightMeasureSpec) if (height >= width) { height = min(height, (width * 1.5).roundToInt()) } else { width = min(width, height) } val textSize = min(0.2f * width, getDimension(context, R.dimen.smallerTextSize)) label.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize) if (isNumerical) { ring.setTextSize(textSize * 0.9f) } else { ring.setTextSize(textSize) } ring.setThickness(0.03f * width) super.onMeasure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) ) } private fun init() { val appComponent: HabitsApplicationComponent = (context.applicationContext as HabitsApplication).component preferences = appComponent.preferences ring = findViewById<View>(R.id.scoreRing) as RingView label = findViewById<View>(R.id.label) as TextView ring.setIsTransparencyEnabled(true) if (isInEditMode) { percentage = 0.75f name = "Wake up early" activeColor = getAndroidTestColor(6) entryValue = YES_MANUAL refresh() } } }
gpl-3.0
218c2a7e7483fa69c46708a13fa8fe9e
36.152866
114
0.645294
4.398944
false
false
false
false
CrystalLord/plounge-quoter
src/main/kotlin/org/crystal/ploungequoter/Renderer.kt
1
3438
package org.crystal.ploungequoter import java.io.File import javax.imageio.ImageIO import java.awt.Graphics2D import java.awt.geom.AffineTransform import java.awt.image.AffineTransformOp import java.awt.image.BufferedImage import javax.imageio.IIOException /** * The Renderer stores all visual objects, then when finally processing, it * can generate an output file. * * To use this class, add layers to the renderer, then call render. * * @param[backgroundFile] File that details where the background image is. */ class Renderer(val backgroundFile: File) { /** * List of layers in the program. */ private var layers: MutableList<RenderLayer> = mutableListOf<RenderLayer>() /** * The stored overarching image. */ private var img: BufferedImage init { // Assign the render object list to an empty list. try { this.img = ImageIO.read(this.backgroundFile) println("Renderer Loaded Background") } catch (e: IIOException) { throw IllegalStateException("Background file could not be read.") } } /** * Render all render objects into a file. * @param[outputType] The file type for the output, as a string. * @param[outputFile] The File to actually output to. */ fun render(outputType: String, outputFile: File) { // Read the background image file in. // Note, the background is the base layer for the rendering system. // Sensibly, this would be changed for a more general // implementation. val overarchingGraphics: Graphics2D = img.createGraphics() // Render all the objects in the queue. for (layer in this.layers) { // Pass each of the layers into the overarching graphics. overarchingGraphics.drawImage( layer.getImage(), // The image to draw AffineTransformOp( AffineTransform(), AffineTransformOp.TYPE_BICUBIC ), // Identity transformation 0, // x pos 0 // y pos ) } // TODO: // Consider closing the graphics object here? // Actually write the file ImageIO.write(img,outputType,outputFile) } /** * Retrieve a layer from the renderer. * @param index Index of the layer to retrieve. */ fun getLayer(index: Int): RenderLayer = this.layers[index] /** * Place a layer to the back of the queue. * @param layer Layer to stick ontop of the Renderer. */ fun addLayer(layer: RenderLayer) { this.layers.add(layer) } /** * Place a transparent RasterLayer on the render queue * * @return The newly added RasterLayer */ fun addRasterLayer(): RasterLayer { val newLayer: RasterLayer = RasterLayer( this.img.getWidth(), this.img.getHeight() ) this.layers.add(newLayer) return newLayer } /** * Place a transparent GraphicsLayer on the render queue * @return The newly added layer. */ fun addGraphicsLayer(): GraphicsLayer { val newLayer: GraphicsLayer = GraphicsLayer( this.img.getWidth(), this.img.getHeight() ) this.layers.add(newLayer) return newLayer } }
apache-2.0
13107a9ac18ba5e3a7b09750b6f1297b
29.157895
79
0.603839
4.614765
false
false
false
false
dahlstrom-g/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/ChangesViewCommitWorkflowHandler.kt
1
10888
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.commit import com.intellij.application.subscribe import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsDataKeys.COMMIT_WORKFLOW_HANDLER import com.intellij.openapi.vcs.changes.* import com.intellij.util.EventDispatcher import com.intellij.util.containers.CollectionFactory import java.util.* import kotlin.properties.Delegates.observable private fun Collection<Change>.toPartialAwareSet() = CollectionFactory.createCustomHashingStrategySet(ChangeListChange.HASHING_STRATEGY) .also { it.addAll(this) } internal class ChangesViewCommitWorkflowHandler( override val workflow: ChangesViewCommitWorkflow, override val ui: ChangesViewCommitWorkflowUi ) : NonModalCommitWorkflowHandler<ChangesViewCommitWorkflow, ChangesViewCommitWorkflowUi>(), CommitAuthorTracker by ui, CommitAuthorListener, ProjectManagerListener { override val commitPanel: CheckinProjectPanel = CommitProjectPanelAdapter(this) override val amendCommitHandler: NonModalAmendCommitHandler = NonModalAmendCommitHandler(this) private fun getCommitState(): ChangeListCommitState { val changes = getIncludedChanges() val changeList = workflow.getAffectedChangeList(changes) return ChangeListCommitState(changeList, changes, getCommitMessage()) } private val activityEventDispatcher = EventDispatcher.create(ActivityListener::class.java) private val changeListManager = ChangeListManagerEx.getInstanceEx(project) private var knownActiveChanges: Collection<Change> = emptyList() private val inclusionModel = PartialCommitInclusionModel(project) private val commitMessagePolicy = ChangesViewCommitMessagePolicy(project) private var currentChangeList by observable<LocalChangeList?>(null) { _, oldValue, newValue -> if (oldValue?.id != newValue?.id) { changeListChanged(oldValue, newValue) changeListDataChanged() } else if (oldValue?.data != newValue?.data) { changeListDataChanged() } } init { Disposer.register(this, inclusionModel) Disposer.register(ui, this) workflow.addListener(this, this) workflow.addCommitListener(GitCommitStateCleaner(), this) addCommitAuthorListener(this, this) ui.addExecutorListener(this, this) ui.addDataProvider(createDataProvider()) ui.addInclusionListener(this, this) ui.inclusionModel = inclusionModel Disposer.register(inclusionModel, Disposable { ui.inclusionModel = null }) ui.setCompletionContext(changeListManager.changeLists) setupDumbModeTracking() ProjectManager.TOPIC.subscribe(this, this) setupCommitHandlersTracking() setupCommitChecksResultTracking() vcsesChanged() // as currently vcses are set before handler subscribes to corresponding event currentChangeList = workflow.getAffectedChangeList(emptySet()) if (isToggleMode()) deactivate(false) val busConnection = project.messageBus.connect(this) CommitModeManager.subscribeOnCommitModeChange(busConnection, object : CommitModeManager.CommitModeListener { override fun commitModeChanged() { if (isToggleMode()) { deactivate(false) } else { activate() } } }) DelayedCommitMessageProvider.init(project, ui, ::getCommitMessageFromPolicy) } override fun createDataProvider(): DataProvider = object : DataProvider { private val superProvider = [email protected]() override fun getData(dataId: String): Any? = if (COMMIT_WORKFLOW_HANDLER.`is`(dataId)) [email protected] { it.isActive } else superProvider.getData(dataId) } override fun commitOptionsCreated() { currentChangeList?.let { commitOptions.changeListChanged(it) } } override fun executionEnded() { super.executionEnded() ui.endExecution() } fun synchronizeInclusion(changeLists: List<LocalChangeList>, unversionedFiles: List<FilePath>) { if (!inclusionModel.isInclusionEmpty()) { val possibleInclusion = CollectionFactory.createCustomHashingStrategySet(ChangeListChange.HASHING_STRATEGY) possibleInclusion.addAll(changeLists.asSequence().flatMap { it.changes }) possibleInclusion.addAll(unversionedFiles) inclusionModel.retainInclusion(possibleInclusion) } if (knownActiveChanges.isNotEmpty()) { val activeChanges = changeListManager.defaultChangeList.changes knownActiveChanges = knownActiveChanges.intersect(activeChanges) } inclusionModel.changeLists = changeLists ui.setCompletionContext(changeLists) } fun setCommitState(changeList: LocalChangeList, items: Collection<Any>, force: Boolean) { setInclusion(items, force) setSelection(changeList) } private fun setInclusion(items: Collection<Any>, force: Boolean) { val activeChanges = changeListManager.defaultChangeList.changes if (!isActive || force) { inclusionModel.clearInclusion() ui.includeIntoCommit(items) knownActiveChanges = if (!isActive) activeChanges else emptyList() } else { // skip if we have inclusion from not active change lists if ((inclusionModel.getInclusion() - activeChanges.toPartialAwareSet()).filterIsInstance<Change>().isNotEmpty()) return // we have inclusion in active change list and/or unversioned files => include new active changes if any val newChanges = activeChanges - knownActiveChanges ui.includeIntoCommit(newChanges) // include all active changes if nothing is included if (inclusionModel.isInclusionEmpty()) ui.includeIntoCommit(activeChanges) } } private fun setSelection(changeList: LocalChangeList) { val inclusion = inclusionModel.getInclusion() val isChangeListFullyIncluded = changeList.changes.run { isNotEmpty() && all { it in inclusion } } if (isChangeListFullyIncluded) { ui.select(changeList) ui.expand(changeList) } else { ui.selectFirst(inclusion) } } val isActive: Boolean get() = ui.isActive fun activate(): Boolean = fireActivityStateChanged { ui.activate() } fun deactivate(isRestoreState: Boolean) = fireActivityStateChanged { ui.deactivate(isRestoreState) } fun addActivityListener(listener: ActivityListener, parent: Disposable) = activityEventDispatcher.addListener(listener, parent) private fun <T> fireActivityStateChanged(block: () -> T): T { val oldValue = isActive return block().also { if (oldValue != isActive) activityEventDispatcher.multicaster.activityStateChanged() } } private fun changeListChanged(oldChangeList: LocalChangeList?, newChangeList: LocalChangeList?) { oldChangeList?.let { commitMessagePolicy.save(it, getCommitMessage(), false) } val newCommitMessage = newChangeList?.let(::getCommitMessageFromPolicy) setCommitMessage(newCommitMessage) newChangeList?.let { commitOptions.changeListChanged(it) } } private fun getCommitMessageFromPolicy(changeList: LocalChangeList? = currentChangeList): String? { if (changeList == null) return null return commitMessagePolicy.getCommitMessage(changeList) { getIncludedChanges() } } private fun changeListDataChanged() { commitAuthor = currentChangeList?.author commitAuthorDate = currentChangeList?.authorDate } override fun commitAuthorChanged() { val changeList = changeListManager.getChangeList(currentChangeList?.id) ?: return if (commitAuthor == changeList.author) return changeListManager.editChangeListData(changeList.name, ChangeListData.of(commitAuthor, commitAuthorDate)) } override fun commitAuthorDateChanged() { val changeList = changeListManager.getChangeList(currentChangeList?.id) ?: return if (commitAuthorDate == changeList.authorDate) return changeListManager.editChangeListData(changeList.name, ChangeListData.of(commitAuthor, commitAuthorDate)) } override fun inclusionChanged() { val inclusion = inclusionModel.getInclusion() val activeChanges = changeListManager.defaultChangeList.changes val includedActiveChanges = activeChanges.filter { it in inclusion } // ensure all included active changes are known => if user explicitly checks and unchecks some change, we know it is unchecked knownActiveChanges = knownActiveChanges.union(includedActiveChanges) currentChangeList = workflow.getAffectedChangeList(inclusion.filterIsInstance<Change>()) super.inclusionChanged() } override fun beforeCommitChecksEnded(isDefaultCommit: Boolean, result: CommitChecksResult) { super.beforeCommitChecksEnded(isDefaultCommit, result) if (result.shouldCommit) { // commit message could be changed during before-commit checks - ensure updated commit message is used for commit workflow.commitState = workflow.commitState.copy(getCommitMessage()) if (isToggleMode()) deactivate(true) } } private fun isToggleMode(): Boolean { val commitMode = CommitModeManager.getInstance(project).getCurrentCommitMode() return commitMode is CommitMode.NonModalCommitMode && commitMode.isToggleMode } override fun updateWorkflow() { workflow.commitState = getCommitState() } override fun addUnversionedFiles(): Boolean = addUnversionedFiles(workflow.getAffectedChangeList(getIncludedChanges())) override fun saveCommitMessage(success: Boolean) = commitMessagePolicy.save(currentChangeList, getCommitMessage(), success) // save state on project close // using this method ensures change list comment and commit options are updated before project state persisting override fun projectClosingBeforeSave(project: Project) { saveStateBeforeDispose() disposeCommitOptions() currentChangeList = null } // save state on other events - like "settings changed to use commit dialog" override fun dispose() { saveStateBeforeDispose() disposeCommitOptions() super.dispose() } private fun saveStateBeforeDispose() { commitOptions.saveState() saveCommitMessage(false) } interface ActivityListener : EventListener { fun activityStateChanged() } private inner class GitCommitStateCleaner : CommitStateCleaner() { private fun initCommitMessage() = setCommitMessage(getCommitMessageFromPolicy()) override fun onSuccess(commitMessage: String) { initCommitMessage() super.onSuccess(commitMessage) } } }
apache-2.0
f0386a777fd8a2598efb03828aa6d24e
36.544828
140
0.764511
5.036078
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/dto/JsonFileSize.kt
10
1473
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing.diagnostic.dto import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.JsonSerializer import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.intellij.openapi.util.text.StringUtil import com.intellij.util.indexing.diagnostic.BytesNumber @JsonSerialize(using = JsonFileSize.Serializer::class) @JsonDeserialize(using = JsonFileSize.Deserializer::class) @JsonIgnoreProperties(ignoreUnknown = true) data class JsonFileSize(val bytes: BytesNumber = 0) { object Serializer : JsonSerializer<JsonFileSize>() { override fun serialize(value: JsonFileSize, gen: JsonGenerator, serializers: SerializerProvider?) { gen.writeNumber(value.bytes) } } object Deserializer : JsonDeserializer<JsonFileSize>() { override fun deserialize(p: JsonParser, ctxt: DeserializationContext?): JsonFileSize = JsonFileSize(p.longValue) } fun presentableSize(): String = StringUtil.formatFileSize(bytes) }
apache-2.0
dd7852b1bb3b785573a8b52e7135e600
46.548387
140
0.819416
4.67619
false
false
false
false
ediTLJ/novelty
app/src/main/java/ro/edi/novelty/data/db/entity/DbNewsState.kt
1
1168
/* * Copyright 2019 Eduard Scarlat * * 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 ro.edi.novelty.data.db.entity import androidx.room.* @Entity( tableName = "news_state", indices = [Index(value = ["feed_id", "is_starred"])], foreignKeys = [ForeignKey( entity = DbFeed::class, parentColumns = arrayOf("id"), childColumns = arrayOf("feed_id"), onDelete = ForeignKey.CASCADE )] ) data class DbNewsState( @PrimaryKey val id: Int, @ColumnInfo(name = "feed_id") val feedId: Int, @ColumnInfo(name = "is_read") val isRead: Boolean = false, @ColumnInfo(name = "is_starred") val isStarred: Boolean = false )
apache-2.0
9f84f5c7a3aa74f3c39780fbf2ab500a
32.4
74
0.697774
3.86755
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/web/util/ImageUtils.kt
1
23496
package top.zbeboy.isy.web.util import org.apache.commons.io.FilenameUtils import org.apache.commons.io.IOUtils import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory import java.awt.* import java.awt.geom.RoundRectangle2D import java.awt.image.BufferedImage import java.io.* import java.net.URL import javax.imageio.IIOImage import javax.imageio.ImageIO import javax.imageio.ImageWriteParam import javax.imageio.ImageWriter import javax.imageio.stream.ImageOutputStream /** * Created by zbeboy 2017-11-26 . **/ open class ImageUtils { companion object { private val log = LoggerFactory.getLogger(ImageUtils::class.java) /** * 获取图片尺寸信息 * * @param filePath a [java.lang.String] object. * @return [width, height] */ @JvmStatic @Throws(Exception::class) fun getSizeInfo(filePath: String): IntArray { val file = File(filePath) return getSizeInfo(file) } /** * 获取图片尺寸信息 * * @param url a [java.net.URL] object. * @return [width, height] */ @JvmStatic @Throws(Exception::class) fun getSizeInfo(url: URL): IntArray { val input: InputStream try { input = url.openStream() return getSizeInfo(input) } catch (e: IOException) { log.error("Get file size error : {}", e) throw Exception(e) } } /** * 获取图片尺寸信息 * * @param file a [java.io.File] object. * @return [width, height] */ @JvmStatic @Throws(Exception::class) fun getSizeInfo(file: File): IntArray { if (!file.exists()) { throw Exception("file " + file.absolutePath + " doesn't exist.") } val input: BufferedInputStream try { input = BufferedInputStream(FileInputStream(file)) return getSizeInfo(input) } catch (e: FileNotFoundException) { log.error("Get file size error : {}", e) throw Exception(e) } } /** * 获取图片尺寸 * * @param input a [java.io.InputStream] object. * @return [width, height] */ @JvmStatic @Throws(Exception::class) fun getSizeInfo(input: InputStream?): IntArray { try { val img = ImageIO.read(input!!) val w = img.getWidth(null) val h = img.getHeight(null) return intArrayOf(w, h) } catch (e: IOException) { log.error("Get file size error : {}", e) throw Exception(e) } } /** * 重调图片尺寸 * * @param srcFilePath 原图路径 * @param destFile 目标文件 * @param width 新的宽度,小于1则忽略,按原图比例缩放 * @param height 新的高度,小于1则忽略,按原图比例缩放 */ @JvmStatic @Throws(Exception::class) fun resize(srcFilePath: String, destFile: String, width: Int, height: Int) { resize(srcFilePath, destFile, width, height, -1, -1) } /** * 重调图片尺寸 * * @param input a [java.io.InputStream] object. * @param output a [java.io.OutputStream] object. * @param width a int. * @param height a int. */ @JvmStatic @Throws(Exception::class) fun resize(input: InputStream, output: OutputStream, width: Int, height: Int) { resize(input, output, width, height, -1, -1) } /** * 重调图片尺寸 * * @param input a [java.io.InputStream] object. * @param output a [java.io.OutputStream] object. * @param width a int. * @param height a int. * @param maxWidth a int. * @param maxHeight a int. */ @JvmStatic @Throws(Exception::class) fun resize(input: InputStream, output: OutputStream, width: Int, height: Int, maxWidth: Int, maxHeight: Int) { if (width < 1 && height < 1 && maxWidth < 1 && maxHeight < 1) { try { IOUtils.copy(input, output) } catch (e: IOException) { throw Exception("resize error: ", e) } } try { val img = ImageIO.read(input) val hasNotAlpha = !img.colorModel.hasAlpha() val w = img.getWidth(null).toDouble() val h = img.getHeight(null).toDouble() var toWidth: Int var toHeight: Int var rate = w / h if (width > 0 && height > 0) { rate = width.toDouble() / height.toDouble() toWidth = width toHeight = height } else if (width > 0) { toWidth = width toHeight = (toWidth / rate).toInt() } else if (height > 0) { toHeight = height toWidth = (toHeight * rate).toInt() } else { toWidth = (w as Number).toInt() toHeight = (h as Number).toInt() } if (maxWidth in 1..(toWidth - 1)) { toWidth = maxWidth toHeight = (toWidth / rate).toInt() } if (maxHeight in 1..(toHeight - 1)) { toHeight = maxHeight toWidth = (toHeight * rate).toInt() } val tag = BufferedImage(toWidth, toHeight, if (hasNotAlpha) BufferedImage.TYPE_INT_RGB else BufferedImage.TYPE_INT_ARGB) // Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢 tag.graphics.drawImage(img.getScaledInstance(toWidth, toHeight, Image.SCALE_SMOOTH), 0, 0, null) ImageIO.write(tag, if (hasNotAlpha) "jpg" else "png", output) } catch (e: Exception) { log.error("Resize error : {}", e) throw Exception(e) } finally { input.close() output.close() } } /** * 重调图片尺寸 * * @param srcFile 原图路径 * @param destFile 目标文件 * @param width 新的宽度,小于1则忽略,按原图比例缩放 * @param height 新的高度,小于1则忽略,按原图比例缩放 * @param maxWidth 最大宽度,限制目标图片宽度,小于1则忽略此设置 * @param maxHeight 最大高度,限制目标图片高度,小于1则忽略此设置 */ @JvmStatic @Throws(Exception::class) fun resize(srcFile: String, destFile: String, width: Int, height: Int, maxWidth: Int, maxHeight: Int) { resize(File(srcFile), File(destFile), width, height, maxWidth, maxHeight) } /** * 重调图片尺寸 * * @param srcFile 原图路径 * @param destFile 目标文件 * @param width 新的宽度,小于1则忽略,按原图比例缩放 * @param height 新的高度,小于1则忽略,按原图比例缩放 */ @JvmStatic @Throws(Exception::class) fun resize(srcFile: File, destFile: File, width: Int, height: Int) { resize(srcFile, destFile, width, height, -1, -1) } /** * 重调图片尺寸 * * @param srcFile 原图路径 * @param destFile 目标文件 * @param width 新的宽度,小于1则忽略,按原图比例缩放 * @param height 新的高度,小于1则忽略,按原图比例缩放 * @param maxWidth 最大宽度,限制目标图片宽度,小于1则忽略此设置 * @param maxHeight 最大高度,限制目标图片高度,小于1则忽略此设置 */ @JvmStatic @Throws(Exception::class) fun resize(srcFile: File, destFile: File, width: Int, height: Int, maxWidth: Int, maxHeight: Int) { if (destFile.exists()) { destFile.delete() } else { destFile.parentFile.mkdirs() } val input: InputStream val output: OutputStream try { input = BufferedInputStream(FileInputStream(srcFile)) output = FileOutputStream(destFile) resize(input, output, width, height, maxWidth, maxHeight) } catch (e: FileNotFoundException) { log.error("Resize error : {}", e) throw Exception(e) } } /** * 裁剪图片 * * @param source a [java.lang.String] object. * @param target a [java.lang.String] object. * @param x a int. * @param y a int. * @param w a int. * @param h a int. */ @JvmStatic @Throws(Exception::class) fun crop(source: String, target: String, x: Int, y: Int, w: Int, h: Int) { crop(File(source), File(target), x, y, w, h) } /** * 裁剪图片 * * @param source a [java.io.File] object. * @param target a [java.io.File] object. * @param x a int. * @param y a int. * @param w a int. * @param h a int. */ @JvmStatic @Throws(Exception::class) fun crop(source: File, target: File, x: Int, y: Int, w: Int, h: Int) { val output: OutputStream val input: InputStream val ext = FilenameUtils.getExtension(target.name) try { input = BufferedInputStream(FileInputStream(source)) if (target.exists()) { target.delete() } else { target.parentFile.mkdirs() } output = BufferedOutputStream(FileOutputStream(target)) } catch (e: IOException) { log.error("Crop error : {}", e) throw Exception(e) } crop(input, output, x, y, w, h, StringUtils.equalsIgnoreCase("png", ext)) } /** * 裁剪图片 * * @param x a int. * @param y a int. * @param w a int. * @param h a int. * @param input a [java.io.InputStream] object. * @param output a [java.io.OutputStream] object. * @param isPNG a boolean. */ @JvmStatic @Throws(Exception::class) fun crop(input: InputStream, output: OutputStream, x: Int, y: Int, w: Int, h: Int, isPNG: Boolean) { try { val srcImg = ImageIO.read(input) val tmpWidth = srcImg.width val tmpHeight = srcImg.height val xx = Math.min(tmpWidth - 1, x) val yy = Math.min(tmpHeight - 1, y) var ww = w if (xx + w > tmpWidth) { ww = Math.max(1, tmpWidth - xx) } var hh = h if (yy + h > tmpHeight) { hh = Math.max(1, tmpHeight - yy) } val dest = srcImg.getSubimage(xx, yy, ww, hh) val tag = BufferedImage(w, h, if (isPNG) BufferedImage.TYPE_INT_ARGB else BufferedImage.TYPE_INT_RGB) tag.graphics.drawImage(dest, 0, 0, null) ImageIO.write(tag, if (isPNG) "png" else "jpg", output) } catch (e: Exception) { log.error("Crop error : {}", e) throw Exception(e) } finally { input.close() output.close() } } /** * 压缩图片,PNG图片按JPG处理 * * @param input a [java.io.InputStream] object. * @param output a [java.io.OutputStream] object. * @param quality 图片质量0-1之间 */ @JvmStatic @Throws(Exception::class) fun optimize(input: InputStream, output: OutputStream, quality: Float) { // create a BufferedImage as the result of decoding the supplied // InputStream val image: BufferedImage var ios: ImageOutputStream? = null var writer: ImageWriter? = null try { image = ImageIO.read(input) // get all image writers for JPG format val writers = ImageIO.getImageWritersByFormatName("jpeg") if (!writers.hasNext()) throw IllegalStateException("No writers found") writer = writers.next() as ImageWriter ios = ImageIO.createImageOutputStream(output) writer.output = ios val param = writer.defaultWriteParam // optimize to a given quality param.compressionMode = ImageWriteParam.MODE_EXPLICIT param.compressionQuality = quality // appends a complete image stream containing a single image and // associated stream and image metadata and thumbnails to the output writer.write(null, IIOImage(image, null, null), param) } catch (e: IOException) { log.error("Optimize error : {}", e) } finally { if (ios != null) { try { input.close() output.close() ios.close() } catch (e: IOException) { log.error("ImageOutputStream closed error : {}", e) } } if (writer != null) { writer.dispose() } } } /** * 压缩图片 * * @param source a [java.lang.String] object. * @param target a [java.lang.String] object. * @param quality a float. */ @JvmStatic @Throws(Exception::class) fun optimize(source: String, target: String, quality: Float) { val fromFile = File(source) val toFile = File(target) optimize(fromFile, toFile, quality) } /** * 压缩图片 * * @param source a [java.io.File] object. * @param target a [java.io.File] object. * @param quality 图片质量0-1之间 */ @JvmStatic @Throws(Exception::class) fun optimize(source: File, target: File, quality: Float) { if (target.exists()) { target.delete() } else { target.parentFile.mkdirs() } val `is`: InputStream val os: OutputStream try { `is` = BufferedInputStream(FileInputStream(source)) os = BufferedOutputStream(FileOutputStream(target)) optimize(`is`, os, quality) } catch (e: FileNotFoundException) { log.error("Optimize error : {}", e) throw Exception(e) } } /** * 制作圆角 * * @param srcFile 原文件 * @param destFile 目标文件 * @param cornerRadius 角度 */ @JvmStatic @Throws(Exception::class) fun makeRoundedCorner(srcFile: File, destFile: File, cornerRadius: Int) { val `in`: InputStream val out: OutputStream try { `in` = BufferedInputStream(FileInputStream(srcFile)) destFile.parentFile.mkdirs() out = BufferedOutputStream(FileOutputStream(destFile)) makeRoundedCorner(`in`, out, cornerRadius) } catch (e: IOException) { log.error("MakeRoundedCorner error : {}", e) throw Exception(e) } } /** * 制作圆角 * * @param srcFile 原文件 * @param destFile 目标文件 * @param cornerRadius 角度 */ @JvmStatic @Throws(Exception::class) fun makeRoundedCorner(srcFile: String, destFile: String, cornerRadius: Int) { makeRoundedCorner(File(srcFile), File(destFile), cornerRadius) } /** * 制作圆角 * * @param inputStream 原图输入流 * @param outputStream 目标输出流 * @param radius 角度 */ @JvmStatic @Throws(Exception::class) fun makeRoundedCorner(inputStream: InputStream, outputStream: OutputStream, radius: Int) { val sourceImage: BufferedImage val targetImage: BufferedImage try { sourceImage = ImageIO.read(inputStream) val w = sourceImage.width val h = sourceImage.height println(w) val cornerRadius = if (radius < 1) w / 4 else radius targetImage = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB) val g2 = targetImage.createGraphics() // This is what we want, but it only does hard-clipping, i.e. // aliasing // g2.setClip(new RoundRectangle2D ...) // so instead fake soft-clipping by first drawing the desired clip // shape // in fully opaque white with antialiasing enabled... g2.composite = AlphaComposite.Src g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g2.color = Color.WHITE g2.fill(RoundRectangle2D.Float(0f, 0f, w.toFloat(), h.toFloat(), cornerRadius.toFloat(), cornerRadius.toFloat())) // ... then compositing the image on top, // using the white shape from above as alpha source g2.composite = AlphaComposite.SrcAtop g2.drawImage(sourceImage, 0, 0, null) g2.dispose() ImageIO.write(targetImage, "png", outputStream) } catch (e: IOException) { log.error("MakeRoundedCorner error : {}", e) throw Exception(e) } finally { inputStream.close() outputStream.close() } } /** * 图片旋转 * * @param srcFile 源文文件 * @param destFile 输出文件 * @param angle rotate * @throws Exception 异常 */ @JvmStatic @Throws(Exception::class) fun makeRotate(srcFile: File, destFile: File, angle: Int) { val `in`: InputStream val out: OutputStream try { `in` = BufferedInputStream(FileInputStream(srcFile)) destFile.parentFile.mkdirs() out = BufferedOutputStream(FileOutputStream(destFile)) makeRotate(`in`, out, angle) } catch (e: IOException) { log.error("makeRotate error : {}", e) throw Exception(e) } } /** * 图片旋转 * * @param srcFile 源文文件 * @param destFile 输出文件 * @param angle rotate * @throws Exception 异常 */ @JvmStatic @Throws(Exception::class) fun makeRotate(srcFile: String, destFile: String, angle: Int) { makeRotate(File(srcFile), File(destFile), angle) } /** * 图片旋转 * * @param inputStream 输入流 * @param outputStream 输出流 * @param angle rotate * @throws Exception 异常 */ @JvmStatic @Throws(Exception::class) fun makeRotate(inputStream: InputStream, outputStream: OutputStream, angle: Int) { val dealedImage: BufferedImage val res: BufferedImage try { dealedImage = ImageIO.read(inputStream) val width = dealedImage.width val height = dealedImage.height // calculate the new image size val rect_des = CalcRotatedSize(Rectangle(Dimension( width, height)), angle) res = BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB) val g2 = res.createGraphics() // transform g2.translate((rect_des.width - width) / 2, (rect_des.height - height) / 2) g2.rotate(Math.toRadians(angle.toDouble()), width / 2.0, height / 2.0) g2.drawImage(dealedImage, null, null) g2.dispose() ImageIO.write(res, "png", outputStream) } catch (e: IOException) { log.error("makeRotate error : {}", e) throw Exception(e) } finally { inputStream.close() outputStream.close() } } /** * 旋转处理 */ @JvmStatic fun CalcRotatedSize(src: Rectangle, angel: Int): Rectangle { var tempAngel = angel // if angel is greater than 90 degree, we need to do some conversion tempAngel = Math.abs(tempAngel) if (tempAngel >= 90) { if (tempAngel / 90 % 2 == 1) { val temp = src.height src.height = src.width src.width = temp } tempAngel %= 90 } val r = Math.sqrt(src.height.toDouble() * src.height + src.width.toDouble() * src.width) / 2 val len = 2.0 * Math.sin(Math.toRadians(tempAngel.toDouble()) / 2) * r val angel_alpha = (Math.PI - Math.toRadians(tempAngel.toDouble())) / 2 val angel_dalta_width = Math.atan(src.height.toDouble() / src.width) val angel_dalta_height = Math.atan(src.width.toDouble() / src.height) val len_dalta_width = (len * Math.cos(Math.PI - angel_alpha - angel_dalta_width)).toInt() val len_dalta_height = (len * Math.cos(Math.PI - angel_alpha - angel_dalta_height)).toInt() val des_width = src.width + len_dalta_width * 2 val des_height = src.height + len_dalta_height * 2 return java.awt.Rectangle(Dimension(des_width, des_height)) } } }
mit
ee36eb03ab5d9037d30270b9218af3cf
32.696108
136
0.488715
4.454384
false
false
false
false
gmariotti/kotlin-koans
lesson5/task4/src/data.kt
4
941
data class Product(val description: String, val price: Double, val popularity: Int) val cactus = Product("cactus", 11.2, 13) val cake = Product("cake", 3.2, 111) val camera = Product("camera", 134.5, 2) val car = Product("car", 30000.0, 0) val carrot = Product("carrot", 1.34, 5) val cellPhone = Product("cell phone", 129.9, 99) val chimney = Product("chimney", 190.0, 2) val certificate = Product("certificate", 99.9, 1) val cigar = Product("cigar", 8.0, 51) val coffee = Product("coffee", 8.0, 67) val coffeeMaker = Product("coffee maker", 201.2, 1) val cola = Product("cola", 4.0, 67) val cranberry = Product("cranberry", 4.1, 39) val crocs = Product("crocs", 18.7, 10) val crocodile = Product("crocodile", 20000.2, 1) val cushion = Product("cushion", 131.0, 0) fun getProducts() = listOf(cactus, cake, camera, car, carrot, cellPhone, chimney, certificate, cigar, coffee, coffeeMaker, cola, cranberry, crocs, crocodile, cushion)
mit
cbf5199197acb26605e894167f58a8ed
43.857143
122
0.689692
2.8429
false
false
false
false
seratch/jslack
bolt-kotlin-examples/src/main/kotlin/examples/say_something/app.kt
1
2746
package examples.say_something import com.slack.api.bolt.App import com.slack.api.bolt.context.Context import com.slack.api.bolt.context.builtin.SlashCommandContext import com.slack.api.bolt.jetty.SlackAppServer import com.slack.api.methods.request.conversations.ConversationsListRequest import com.slack.api.model.ConversationType fun main() { // export SLACK_BOT_TOKEN=xoxb-*** // export SLACK_SIGNING_SECRET=123abc*** val app = App() // requires channels:read scope fun toConversationId(ctx: Context, where: String): String? { val name = where.replaceFirst("#", "").trim() var cursor: String? = null var conversationId: String? = null while (conversationId == null && cursor != "") { val rb = ConversationsListRequest.builder().limit(1000).types(listOf(ConversationType.PUBLIC_CHANNEL)) val req = if (cursor != null) rb.cursor(cursor).build() else rb.build() val list = ctx.client().conversationsList(req) for (c in list.channels) { if (c.name == name) { conversationId = c.id break } } } return conversationId } // requires channels:join scope fun joinConversation(ctx: Context, conversationId: String) { val res = ctx.client().conversationsJoin { it.channel(conversationId) } ctx.logger.info("conversions.join result - {}", res) } fun saySomething(ctx: SlashCommandContext, where: String, text: String) { val conversationId = toConversationId(ctx, where) if (conversationId == null) { ctx.ack("[Error] $where was not found") } else { joinConversation(ctx, conversationId) val res = ctx.say { it.channel(where).text(text) } ctx.logger.info("say result - {}", res) } } app.command("/say-something") { req, ctx -> val elements = req.payload.text?.split(" at ") if (elements == null || elements.size < 2) { ctx.ack("[Usage] /say-something Hey folks, how have you been doing? at #general") } else { if (elements.size == 2) { val where = elements[1].trim() val text = elements[0].trim() saySomething(ctx, where, "$text by <@${req.payload.userId}>") } else { val where = elements[elements.size - 1].trim() val text = elements.dropLast(1).joinToString { " at " }.trim() saySomething(ctx, where, "$text by <@${req.payload.userId}>") } ctx.ack() } } val server = SlackAppServer(app) server.start() }
mit
5223040a18ab24f3d27d8226bbe70f22
37.138889
113
0.57866
4.231125
false
false
false
false
paplorinc/intellij-community
platform/platform-api/src/com/intellij/ui/tabs/newImpl/JBEditorTabsBackgroundAndBorder.kt
1
1568
// 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.ui.tabs.newImpl import com.intellij.ui.tabs.JBTabsBackgroundAndBorder import com.intellij.ui.tabs.JBTabsPosition import java.awt.* class JBEditorTabsBackgroundAndBorder(tabs: JBTabsImpl) : JBTabsBackgroundAndBorder(tabs) { override val effectiveBorder: Insets get() = Insets(thickness, 0, 0, 0) override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) { if(tabs.isEmptyVisible) return g as Graphics2D val firstLabel = tabs.myInfo2Label.get(tabs.lastLayoutPass.getTabAt(0, 0)) ?: return paintBackground(g, Rectangle(x, y, width, height)) val startY = firstLabel.y - if (tabs.position == JBTabsPosition.bottom) 0 else thickness tabs.getTabPainter().paintBorderLine(g, thickness, Point(x, startY), Point(x + width, startY)) when(tabs.position) { JBTabsPosition.top -> { for (eachRow in 1..tabs.lastLayoutPass.rowCount) { val yl = (eachRow * tabs.myHeaderFitSize.height) + startY tabs.getTabPainter().paintBorderLine(g, thickness, Point(x, yl), Point(x + width, yl)) } } JBTabsPosition.bottom -> { tabs.getTabPainter().paintBorderLine(g, thickness, Point(x, y), Point(x + width, y)) } JBTabsPosition.right -> { val lx = firstLabel.x tabs.getTabPainter().paintBorderLine(g, thickness, Point(lx, y), Point(lx, y + height)) } } } }
apache-2.0
0159dd844e27dfd2fdec392c8bdcaa68
38.225
140
0.685587
3.742243
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/util/Urls.kt
6
8011
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.io.URLUtil import gnu.trove.TObjectHashingStrategy import java.net.URI import java.net.URISyntaxException import java.util.regex.Pattern private val LOG = Logger.getInstance(Urls::class.java) // about ";" see WEB-100359 private val URI_PATTERN = Pattern.compile("^([^:/?#]+):(//)?([^/?#]*)([^?#;]*)(.*)") object Urls { val caseInsensitiveUrlHashingStrategy: TObjectHashingStrategy<Url> by lazy { CaseInsensitiveUrlHashingStrategy() } @JvmStatic fun newUri(scheme: String?, path: String): UrlImpl = UrlImpl(scheme, null, path) @JvmStatic fun newUrl(scheme: String, authority: String, path: String, rawParameters: String?): UrlImpl { return UrlImpl(scheme, authority, path, rawParameters) } @JvmStatic fun newUrl(scheme: String, authority: String, path: String, parameters: Map<String, String?>): UrlImpl { var parametersString: String? = null if (parameters.isNotEmpty()) { val result = StringBuilder() result.append("?") encodeParameters(parameters, result) parametersString = result.toString() } return UrlImpl(scheme, authority, path, parametersString) } @JvmStatic fun encodeParameters(parameters: Map<String, String?>, result: StringBuilder) { val initialSize = result.length for ((name, value) in parameters) { if (result.length != initialSize) { result.append('&') } // https://stackoverflow.com/questions/5330104/encoding-url-query-parameters-in-java result.append(URLUtil.encodeURIComponent(name)) if (value != null && value.isNotEmpty()) { result.append('=') result.append(URLUtil.encodeURIComponent(value)) } } } @JvmStatic fun newLocalFileUrl(path: String): Url = LocalFileUrl(FileUtilRt.toSystemIndependentName(path)) @JvmStatic fun newLocalFileUrl(file: VirtualFile): Url = LocalFileUrl(file.path) @JvmStatic fun newFromEncoded(url: String): Url { val result = parseEncoded(url) LOG.assertTrue(result != null, url) return result!! } @JvmStatic fun parseEncoded(url: String): Url? = parse(url, false) @JvmStatic fun newHttpUrl(authority: String, path: String?): Url { return newUrl("http", authority, path) } @JvmStatic fun newHttpUrl(authority: String, path: String?, parameters: String?): Url { return UrlImpl("http", authority, path, parameters) } @JvmStatic fun newUrl(scheme: String, authority: String, path: String?): Url { return UrlImpl(scheme, authority, path) } /** * Url will not be normalized (see [VfsUtilCore.toIdeaUrl]), parsed as is */ @JvmStatic fun newFromIdea(url: CharSequence): Url { val result = parseFromIdea(url) LOG.assertTrue(result != null, url) return result!! } // java.net.URI.create cannot parse "file:///Test Stuff" - but you don't need to worry about it - this method is aware @JvmStatic fun parseFromIdea(url: CharSequence): Url? { var i = 0 val n = url.length while (i < n) { val c = url[i] if (c == ':') { // file:// or dart:core/foo return parseUrl(url) } else if (c == '/' || c == '\\') { return newLocalFileUrl(url.toString()) } i++ } return newLocalFileUrl(url.toString()) } @JvmStatic fun parse(url: String, asLocalIfNoScheme: Boolean): Url? { if (url.isEmpty()) { return null } if (asLocalIfNoScheme && !URLUtil.containsScheme(url)) { // nodejs debug - files only in local filesystem return newLocalFileUrl(url) } else { return parseUrl(VfsUtilCore.toIdeaUrl(url)) } } @JvmStatic fun parseAsJavaUriWithoutParameters(url: String): URI? { val asUrl = parseUrl(url) ?: return null try { return toUriWithoutParameters(asUrl) } catch (e: Exception) { LOG.info("Cannot parse url $url", e) return null } } private fun parseUrl(url: CharSequence): Url? { val urlToParse: CharSequence if (StringUtil.startsWith(url, "jar:file://")) { urlToParse = url.subSequence("jar:".length, url.length) } else { urlToParse = url } val matcher = URI_PATTERN.matcher(urlToParse) if (!matcher.matches()) { return null } var scheme = matcher.group(1) if (urlToParse !== url) { scheme = "jar:$scheme" } var authority = StringUtil.nullize(matcher.group(3)) var path = StringUtil.nullize(matcher.group(4)) val hasUrlSeparator = !StringUtil.isEmpty(matcher.group(2)) if (authority == null) { if (hasUrlSeparator) { authority = "" } } else if (StandardFileSystems.FILE_PROTOCOL == scheme || !hasUrlSeparator) { path = if (path == null) authority else authority + path authority = if (hasUrlSeparator) "" else null } // canonicalize only if authority is not empty or file url - we should not canonicalize URL with unknown scheme (webpack:///./modules/flux-orion-plugin/fluxPlugin.ts) if (path != null && (!StringUtil.isEmpty(authority) || StandardFileSystems.FILE_PROTOCOL == scheme)) { path = FileUtil.toCanonicalUriPath(path) } return UrlImpl(scheme, authority, path, matcher.group(5)) } @JvmStatic fun newFromVirtualFile(file: VirtualFile): Url { if (file.isInLocalFileSystem) { return newUri(file.fileSystem.protocol, file.path) } else { val url = parseUrl(file.url) return url ?: Urls.newUnparsable(file.path) } } @JvmStatic fun newUnparsable(string: String): UrlImpl = UrlImpl(null, null, string, null) @JvmOverloads @JvmStatic fun equalsIgnoreParameters(url: Url, urls: Collection<Url>, caseSensitive: Boolean = true): Boolean { for (otherUrl in urls) { if (equals(url, otherUrl, caseSensitive, true)) { return true } } return false } fun equalsIgnoreParameters(url: Url, file: VirtualFile): Boolean { if (file.isInLocalFileSystem) { return url.isInLocalFileSystem && if (SystemInfoRt.isFileSystemCaseSensitive) url.path == file.path else url.path.equals(file.path, ignoreCase = true) } else if (url.isInLocalFileSystem) { return false } val fileUrl = parseUrl(file.url) return fileUrl != null && fileUrl.equalsIgnoreParameters(url) } fun equals(url1: Url?, url2: Url?, caseSensitive: Boolean, ignoreParameters: Boolean): Boolean { if (url1 == null || url2 == null) { return url1 === url2 } val o1 = if (ignoreParameters) url1.trimParameters() else url1 val o2 = if (ignoreParameters) url2.trimParameters() else url2 return if (caseSensitive) o1 == o2 else o1.equalsIgnoreCase(o2) } @JvmStatic fun toUriWithoutParameters(url: Url): URI { try { var externalPath = url.path val inLocalFileSystem = url.isInLocalFileSystem if (inLocalFileSystem && SystemInfoRt.isWindows && externalPath[0] != '/') { externalPath = "/$externalPath" } return URI(if (inLocalFileSystem) "file" else url.scheme, if (inLocalFileSystem) "" else url.authority, externalPath, null, null) } catch (e: URISyntaxException) { throw RuntimeException(e) } } } private class CaseInsensitiveUrlHashingStrategy : TObjectHashingStrategy<Url> { override fun computeHashCode(url: Url?) = url?.hashCodeCaseInsensitive() ?: 0 override fun equals(url1: Url, url2: Url) = Urls.equals(url1, url2, false, false) }
apache-2.0
f9e162dbc10a33acb0cb0c3141b155bf
29.815385
170
0.670203
3.954097
false
false
false
false
chrislo27/Tickompiler
src/main/kotlin/rhmodding/tickompiler/cli/DecompileCommand.kt
2
4410
package rhmodding.tickompiler.cli import kotlinx.coroutines.Deferred import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking import picocli.CommandLine import rhmodding.tickompiler.DSFunctions import rhmodding.tickompiler.MegamixFunctions import rhmodding.tickompiler.decompiler.CommentType import rhmodding.tickompiler.decompiler.Decompiler import rhmodding.tickompiler.util.getDirectories import java.io.File import java.io.FileOutputStream import java.nio.ByteOrder import java.nio.charset.Charset import java.nio.file.Files @CommandLine.Command(name = "decompile", aliases = ["d"], description = ["Decompile file(s) and output them to the file/directory specified.", "Files must be with the file extension .bin (little-endian)", "Files will be overwritten without warning.", "If the output is not specified, the file will be a .tickflow file with the same name."], mixinStandardHelpOptions = true) class DecompileCommand : Runnable { @CommandLine.Option(names = ["-c"], description = ["Continue even with errors."]) var continueWithErrors: Boolean = false @CommandLine.Option(names = ["-nc", "--no-comments"], description = ["Don't include comments."]) var noComments: Boolean = false @CommandLine.Option(names = ["--bytecode"], description = ["Have a comment with the bytecode (overridden by --no-comments)."]) var showBytecode: Boolean = false @CommandLine.Option(names = ["-nm", "--no-metadata"], description = ["No metadata (use when decompiling snippets instead of full files)."]) var noMetadata: Boolean = false @CommandLine.Option(names = ["-m", "--megamix"], description = ["Decompile with Megamix functions. (default true)"]) var megamixFunctions: Boolean = true @CommandLine.Option(names = ["--ds"], description = ["Decompile with RHDS functions (also disables Megamix-specific metadata)"]) var dsFunctions: Boolean = false @CommandLine.Parameters(index = "0", arity = "1", description = ["Input file or directory."]) lateinit var inputFile: File @CommandLine.Parameters(index = "1", arity = "0..1", description = ["Output file or directory."]) var outputFile: File? = null override fun run() { val nanoStart = System.nanoTime() val dirs = getDirectories(inputFile, outputFile, { s -> s.endsWith(".bin") }, "tickflow") val functions = when { dsFunctions -> DSFunctions megamixFunctions -> MegamixFunctions else -> MegamixFunctions } val coroutines: MutableList<Deferred<Boolean>> = mutableListOf() println("Decompiling ${dirs.input.size} file(s)") dirs.input.forEachIndexed { index, file -> coroutines += GlobalScope.async { val decompiler = Decompiler(Files.readAllBytes(file.toPath()), ByteOrder.LITTLE_ENDIAN, functions) try { println("Decompiling ${file.path}") val result = decompiler.decompile(when { noComments -> CommentType.NONE showBytecode -> CommentType.BYTECODE else -> CommentType.NORMAL }, !noMetadata && functions == MegamixFunctions) dirs.output[index].createNewFile() val fos = FileOutputStream(dirs.output[index]) fos.write(result.second.toByteArray(Charset.forName("UTF-8"))) fos.close() println("Decompiled ${file.path} -> ${result.first} ms") return@async true } catch (e: RuntimeException) { if (continueWithErrors) { println("FAILED to decompile ${file.path}") e.printStackTrace() } else { throw e } } return@async true } } runBlocking { val successful = coroutines .map { it.await() } .count { it } println(""" +========================+ | DECOMPILATION COMPLETE | +========================+ $successful / ${dirs.input.size} decompiled successfully in ${(System.nanoTime() - nanoStart) / 1_000_000.0} ms """) } } }
mit
e7640d3f23bc110ac4cbb810aab3dcbd
39.1
143
0.609297
4.80916
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/model/messaging/GroupMessageServiceImpl.kt
1
2550
package backend.model.messaging import backend.model.misc.Email import backend.model.misc.EmailAddress import backend.model.user.UserAccount import backend.model.user.UserRepository import backend.services.NotificationService import backend.services.mail.MailService import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class GroupMessageServiceImpl(val repository: GroupMessageRepository, val userRepository: UserRepository, val mailService: MailService, val notificationServer: NotificationService) : GroupMessageService { @Transactional override fun createGroupMessage(creator: UserAccount): GroupMessage { val groupMessage = GroupMessage(creator) return repository.save(groupMessage) } override fun getByID(id: Long): GroupMessage? = repository.findById(id) override fun save(groupMessage: GroupMessage): GroupMessage = repository.save(groupMessage) @Transactional override fun addUser(user: UserAccount, groupMessage: GroupMessage): GroupMessage { groupMessage.addUser(user) val email = Email( to = listOf(EmailAddress(user.email)), subject = "BreakOut - Du wurdest einer Gruppennachricht hinzugefügt!", body = "Hallo ${user.firstname ?: ""},<br><br>" + "Du wurdest einer neuen Gruppennachricht hinzugefügt. Sieh nach was man Dir mitteilen mag!<br><br>" + "Liebe Grüße<br>" + "Euer BreakOut-Team", buttonText = "NACHRICHT ÖFFNEN", buttonUrl = "https://anmeldung.break-out.org/messages/${groupMessage.id}?utm_source=backend&utm_medium=email&utm_content=intial&utm_campaign=add_groupmessage", campaignCode = "add_groupmessage" ) mailService.send(email) notificationServer.notifyAddedToMessage(groupMessage.id, user) return repository.save(groupMessage) } @Transactional override fun addMessage(message: Message, groupMessage: GroupMessage): GroupMessage { userRepository.save(message.creator) groupMessage.addMessage(message) val notifiedUsers = groupMessage.users.filter { it.id != message.creator?.id && !groupMessage.isBlockedBy(it.id) } notificationServer.notifyNewMessage(message, groupMessage.id, notifiedUsers) return repository.save(groupMessage) } }
agpl-3.0
ae79fd5cc74b79d563842a59f8af0445
42.135593
175
0.685265
4.585586
false
false
false
false
encircled/Joiner
joiner-reactive/src/main/java/cz/encircled/joiner/reactive/composer/JoinerComposerWithReceiver.kt
1
1398
package cz.encircled.joiner.reactive.composer import cz.encircled.joiner.query.JoinerQuery import cz.encircled.joiner.reactive.ExecutionStep open class JoinerComposerWithReceiver<ENTITY, ENTITY_CONTAINER, PUBLISHER>( steps: MutableList<ExecutionStep<*>> ) : JoinerComposer<ENTITY, ENTITY_CONTAINER, PUBLISHER>(steps) { /** * Execute a select query and expect exactly one result */ open fun <F, R> findOne(query: (ENTITY_CONTAINER) -> JoinerQuery<F, R>): MonoJoinerComposer<R> = singular { query(it) } /** * Execute a select query and expect at most one result */ fun <F, R> findOneOptional(query: (ENTITY_CONTAINER) -> JoinerQuery<F, R>): OptionalMonoJoinerComposer<R> = optional { query(it) } /** * Execute a select query */ open fun <F, R> find(query: (ENTITY_CONTAINER) -> JoinerQuery<F, R>): FluxJoinerComposer<R> = plural { query(it) } /** * Persist a single entity, return a reference to persisted entity */ fun <E : Any> persist(entity: (ENTITY_CONTAINER) -> E): MonoJoinerComposer<E> = singular { entity(it) } /** * Persist multiple entities at once, return references to persisted entities */ fun <E : Any> persistMultiple(entity: (ENTITY_CONTAINER) -> List<E>): FluxJoinerComposer<E> = plural { entity(it) } }
apache-2.0
50651c9c9997ad3eb662c83e4c892f31
29.391304
111
0.641631
3.840659
false
false
false
false
google/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/vfs/local/FileWatcherPerformanceTest.kt
6
3914
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vfs.local import com.intellij.openapi.diagnostic.LogLevel import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.impl.local.FileWatcher import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl import com.intellij.openapi.vfs.impl.local.NativeFileWatcherImpl import com.intellij.openapi.vfs.local.FileWatcherTestUtil.INTER_RESPONSE_DELAY import com.intellij.openapi.vfs.local.FileWatcherTestUtil.shutdown import com.intellij.openapi.vfs.local.FileWatcherTestUtil.startup import com.intellij.openapi.vfs.local.FileWatcherTestUtil.unwatch import com.intellij.openapi.vfs.local.FileWatcherTestUtil.watch import com.intellij.testFramework.fixtures.BareTestFixtureTestCase import com.intellij.testFramework.rules.TempDirectory import com.intellij.util.TimeoutUtil import org.assertj.core.api.Assertions.assertThat import org.junit.* import java.io.File import java.util.concurrent.atomic.AtomicInteger private const val WARM_UPS = 5 private const val REPEATS = 50 private const val NUM_FILES = 1000 @Ignore class FileWatcherPerformanceTest : BareTestFixtureTestCase() { @Rule @JvmField val tempDir: TempDirectory = TempDirectory() private var tracing: Boolean = false private lateinit var watcher: FileWatcher private val events = AtomicInteger(0) private val resets = AtomicInteger(0) private val notifier: (String) -> Unit = { path -> if (path === FileWatcher.RESET || path !== FileWatcher.OTHER && path.startsWith(tempDir.root.path)) { events.incrementAndGet() if (path == FileWatcher.RESET) { resets.incrementAndGet() } } } @Before fun setUp() { val logger = Logger.getInstance(NativeFileWatcherImpl::class.java) tracing = logger.isTraceEnabled if (tracing) logger.setLevel(LogLevel.WARNING) watcher = (LocalFileSystem.getInstance() as LocalFileSystemImpl).fileWatcher } @After fun tearDown() { if (tracing) Logger.getInstance(NativeFileWatcherImpl::class.java).setLevel(LogLevel.TRACE) } @Test fun watcherOverhead() { var unwatchedTime = 0L var watchedTime = 0L for (i in 1..WARM_UPS) { createDeleteFiles(tempDir.newDirectory()) } for (i in 1..REPEATS) { TimeoutUtil.sleep(250) val unwatchedDir = tempDir.newDirectory() unwatchedTime += time { createDeleteFiles(unwatchedDir) } TimeoutUtil.sleep(250) val watchedDir = tempDir.newDirectory() val request = startWatcher(watchedDir) watchedTime += time { createDeleteFiles(watchedDir) } waitForEvents() stopWatcher(request) } val overhead = ((watchedTime - unwatchedTime) * 100) / unwatchedTime println("** FW overhead = ${overhead}%, events = ${events}, resets = ${resets}") assertThat(overhead).isLessThanOrEqualTo(25) assertThat(resets.get()).isLessThanOrEqualTo(REPEATS) } private fun createDeleteFiles(directory: File) { for (i in 1..NUM_FILES) File(directory, "test_file_${i}.txt").writeText("hi there.") for (i in 1..NUM_FILES) File(directory, "test_file_${i}.txt").delete() } private fun time(block: () -> Unit): Long { val t = System.nanoTime() block() return (System.nanoTime() - t) / 1000 } private fun startWatcher(directory: File): LocalFileSystem.WatchRequest { startup(watcher, notifier) return watch(watcher, directory) } private fun stopWatcher(request: LocalFileSystem.WatchRequest) { unwatch(watcher, request) shutdown(watcher) } private fun waitForEvents() { var lastCount = events.get() while (true) { TimeoutUtil.sleep(INTER_RESPONSE_DELAY) val newCount = events.get() if (lastCount == newCount) break lastCount = newCount } } }
apache-2.0
0f20d31a464bc85e8bdbb7385834a035
33.342105
120
0.730455
4.111345
false
true
false
false
Werb/MoreType
app/src/main/java/com/werb/moretype/multi/MessageInViewHolder.kt
1
2201
package com.werb.moretype.multi import android.view.LayoutInflater import android.view.View import android.widget.RelativeLayout import androidx.appcompat.widget.AppCompatTextView import com.facebook.drawee.view.SimpleDraweeView import com.werb.library.MoreViewHolder import com.werb.moretype.R import com.werb.moretype.Utils import kotlinx.android.synthetic.main.item_view_multi_message_in.* /** * Created by wanbo on 2017/7/14. */ class MessageInViewHolder(values: MutableMap<String, Any>, containerView: View) : MoreViewHolder<Message>(values, containerView) { override fun bindData(data: Message, payloads: List<Any>) { message_icon.setImageURI(data.icon) if (data.showTime) { message_time.visibility = View.VISIBLE message_time.text = Utils.sendTime(data.time.toLong() * 1000) } else { message_time.visibility = View.INVISIBLE } message_content_layout.removeAllViews() var currentLayout: RelativeLayout? = null when (data.messageType) { "text" -> { currentLayout = LayoutInflater.from(containerView.context).inflate(R.layout.widget_view_message_in_text, message_content_layout, false) as RelativeLayout val text = currentLayout.findViewById<AppCompatTextView>(R.id.message_in_text) text.text = data.text } "image" -> { currentLayout = LayoutInflater.from(containerView.context).inflate(R.layout.widget_view_message_in_image, message_content_layout, false) as RelativeLayout val image = currentLayout.findViewById<SimpleDraweeView>(R.id.message_in_image) image.setImageURI(data.url) setImgSize(data.width, data.height, image) } else -> { } } message_content_layout.addView(currentLayout) } private fun setImgSize(width: String, height: String, image: SimpleDraweeView) { val size = Utils.getIMImageSize(width.toDouble(), height.toDouble()) val lp = image.layoutParams lp.width = size.width lp.height = size.height image.layoutParams = lp } }
apache-2.0
f67fa94a8a5f0e13f55a1d68e43bad2c
39.036364
170
0.666515
4.298828
false
false
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/actions/ChooseBookmarkTypeAction.kt
3
2859
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.bookmark.actions import com.intellij.ide.bookmark.BookmarkBundle import com.intellij.ide.bookmark.BookmarkType import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.ui.popup.PopupState internal class ChooseBookmarkTypeAction : DumbAwareAction(BookmarkBundle.messagePointer("mnemonic.chooser.mnemonic.toggle.action.text")) { private val popupState = PopupState.forPopup() override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(event: AnActionEvent) { val manager = event.bookmarksManager val bookmark = event.contextBookmark val type = bookmark?.let { manager?.getType(it) } event.presentation.apply { isVisible = bookmark != null isEnabled = bookmark != null && popupState.isHidden text = when (type) { BookmarkType.DEFAULT -> BookmarkBundle.message("mnemonic.chooser.mnemonic.assign.action.text") null -> BookmarkBundle.message("mnemonic.chooser.bookmark.create.action.text") else -> BookmarkBundle.message("mnemonic.chooser.mnemonic.change.action.text") } } } override fun actionPerformed(event: AnActionEvent) { if (popupState.isRecentlyHidden) return val manager = event.bookmarksManager ?: return val bookmark = event.contextBookmark ?: return val type = manager.getType(bookmark) val chooser = BookmarkTypeChooser(type, manager.assignedTypes, bookmark.firstGroupWithDescription?.getDescription(bookmark)) { chosenType, description -> popupState.hidePopup() if (manager.getType(bookmark) == null) { manager.toggle(bookmark, chosenType) } else { manager.setType(bookmark, chosenType) } if (description != "") { manager.getGroups(bookmark).firstOrNull()?.setDescription(bookmark, description) } } val title = when (type) { BookmarkType.DEFAULT -> BookmarkBundle.message("mnemonic.chooser.mnemonic.assign.popup.title") null -> BookmarkBundle.message("mnemonic.chooser.bookmark.create.popup.title") else -> BookmarkBundle.message("mnemonic.chooser.mnemonic.change.popup.title") } JBPopupFactory.getInstance().createComponentPopupBuilder(chooser, chooser.firstButton) .setFocusable(true).setRequestFocus(true) .setMovable(false).setResizable(false) .setTitle(title).createPopup() .also { popupState.prepareToShow(it) } .showInBestPositionFor(event.dataContext) } init { isEnabledInModalContext = true } }
apache-2.0
cc21f0ca54e251d9b2173763d2919535
43.671875
158
0.742218
4.741294
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ReflectionCheck.kt
1
3854
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes.NEW import org.objectweb.asm.Opcodes.PUTFIELD import org.objectweb.asm.Type.BYTE_TYPE import org.objectweb.asm.Type.INT_TYPE import org.runestar.client.updater.mapper.AllUniqueMapper import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.withDimensions import org.runestar.client.updater.mapper.nextWithin import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 @DependsOn(Node::class) class ReflectionCheck : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Node>() } .and { it.instanceFields.any { it.type == Array<java.lang.reflect.Field>::class.type } } .and { it.instanceFields.any { it.type == Array<java.lang.reflect.Method>::class.type } } class fields : InstanceField() { override val predicate = predicateOf<Field2> { it.type == Array<java.lang.reflect.Field>::class.type } } class methods : InstanceField() { override val predicate = predicateOf<Field2> { it.type == Array<java.lang.reflect.Method>::class.type } } class arguments : InstanceField() { override val predicate = predicateOf<Field2> { it.type == BYTE_TYPE.withDimensions(3) } } class size : AllUniqueMapper.Field() { override val predicate = predicateOf<Instruction2> { it.opcode == NEW && it.typeType == type<ReflectionCheck>() } .nextWithin(15) { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class id : AllUniqueMapper.Field() { override val predicate = predicateOf<Instruction2> { it.opcode == NEW && it.typeType == type<ReflectionCheck>() } .nextWithin(15) { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } .nextWithin(10) { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class operations : AllUniqueMapper.Field() { override val predicate = predicateOf<Instruction2> { it.opcode == NEW && it.typeType == type<ReflectionCheck>() } .nextWithin(15) { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } .nextWithin(10) { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } .nextWithin(10) { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class creationErrors : AllUniqueMapper.Field() { override val predicate = predicateOf<Instruction2> { it.opcode == NEW && it.typeType == type<ReflectionCheck>() } .nextWithin(15) { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } .nextWithin(10) { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } .nextWithin(10) { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } .nextWithin(10) { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } class intReplaceValues : AllUniqueMapper.Field() { override val predicate = predicateOf<Instruction2> { it.opcode == NEW && it.typeType == type<ReflectionCheck>() } .nextWithin(15) { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } .nextWithin(10) { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } .nextWithin(10) { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } .nextWithin(10) { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } .nextWithin(20) { it.opcode == PUTFIELD && it.fieldType == IntArray::class.type } } }
mit
c22d893fbc52aeeea06ae52afb7d693c
53.295775
121
0.66165
3.973196
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/codeInsight/KotlinHighLevelExpressionTypeProvider.kt
1
1327
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.codeInsight import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.types.Variance class KotlinHighLevelExpressionTypeProvider : KotlinExpressionTypeProvider() { override fun KtExpression.shouldShowStatementType(): Boolean { return true /* TODO */ } // this method gets called from the non-blocking read action override fun getInformationHint(element: KtExpression): String = analyze(element) { val ktType = if (element is KtDeclaration) { element.getReturnKtType() } else { element.getKtType() ?: return KotlinBundle.message("type.provider.unknown.type") } @NlsSafe val rendered = ktType.render(position = Variance.INVARIANT) StringUtil.escapeXmlEntities(rendered) } override fun getErrorHint(): String = KotlinBundle.message("hint.text.no.expression.found") }
apache-2.0
366aa9d0455238ce7c7a2ddfa6e5c3db
41.806452
158
0.746044
4.560137
false
false
false
false
apollographql/apollo-android
apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo3/gradle/internal/RegisterOperations.kt
1
10181
package com.apollographql.apollo3.gradle.internal import com.apollographql.apollo3.annotations.ApolloExperimental import com.apollographql.apollo3.ast.GQLArgument import com.apollographql.apollo3.ast.GQLArguments import com.apollographql.apollo3.ast.GQLDefinition import com.apollographql.apollo3.ast.GQLDirective import com.apollographql.apollo3.ast.GQLDocument import com.apollographql.apollo3.ast.GQLField import com.apollographql.apollo3.ast.GQLFloatValue import com.apollographql.apollo3.ast.GQLFragmentDefinition import com.apollographql.apollo3.ast.GQLFragmentSpread import com.apollographql.apollo3.ast.GQLInlineFragment import com.apollographql.apollo3.ast.GQLIntValue import com.apollographql.apollo3.ast.GQLNode import com.apollographql.apollo3.ast.GQLOperationDefinition import com.apollographql.apollo3.ast.GQLSelection import com.apollographql.apollo3.ast.GQLSelectionSet import com.apollographql.apollo3.ast.GQLStringValue import com.apollographql.apollo3.ast.GQLVariableDefinition import com.apollographql.apollo3.ast.NodeContainer import com.apollographql.apollo3.ast.SDLWriter import com.apollographql.apollo3.ast.TransformResult import com.apollographql.apollo3.ast.parseAsGQLDocument import com.apollographql.apollo3.ast.toUtf8 import com.apollographql.apollo3.ast.transform import com.apollographql.apollo3.compiler.APOLLO_VERSION import com.apollographql.apollo3.compiler.OperationIdGenerator import com.apollographql.apollo3.compiler.fromJson import com.apollographql.apollo3.compiler.operationoutput.OperationOutput import com.apollographql.apollo3.gradle.internal.SchemaDownloader.cast import okio.Buffer private fun GQLDefinition.score(): String { // Fragments always go first return when (this) { is GQLFragmentDefinition -> "a$name" is GQLOperationDefinition -> "b$name" else -> error("Cannot sort Definition '$this'") } } private fun GQLVariableDefinition.score(): String { return this.name } private fun GQLSelection.score(): String { return when (this) { is GQLField -> "a$name" is GQLFragmentSpread -> "b$name" is GQLInlineFragment -> "c" // apollo-tooling doesn't sort inline fragments else -> error("Cannot sort Selection '$this'") } } private fun GQLDirective.score() = name private fun GQLArgument.score() = name private fun isEmpty(s: String?): Boolean { return s == null || s.trim { it <= ' ' }.length == 0 } @OptIn(ApolloExperimental::class) private fun <T : GQLNode> List<T>.join( writer: SDLWriter, separator: String = " ", prefix: String = "", postfix: String = "", block: (T) -> Unit = { writer.write(it) }, ) { writer.write(prefix) forEachIndexed { index, t -> block(t) if (index < size - 1) { writer.write(separator) } } writer.write(postfix) } /** * A document printer that can use " " as a separator for field arguments when the line becomes bigger than 80 chars * as in graphql-js: https://github.com/graphql/graphql-js/blob/6453612a6c40a1f8ad06845f1516c5f0dafa666c/src/language/printer.ts#L62 */ @OptIn(ApolloExperimental::class) private fun printDocument(gqlNode: GQLNode): String { val buffer = Buffer() val writer = object : SDLWriter(buffer, " ") { override fun write(gqlNode: GQLNode) { when (gqlNode) { is GQLField -> { /** * Compute the size of "$alias: $name(arg1: value1, arg2: value2, etc...)" * * If it's bigger than 80, replace ', ' with ' ' */ val lineString = gqlNode.copy(directives = emptyList(), selectionSet = null).toUtf8() if (lineString.length > 80) { write(lineString.replace(", ", " ")) } else { write(lineString) } if (gqlNode.directives.isNotEmpty()) { write(" ") gqlNode.directives.join(this) } if (gqlNode.selectionSet != null) { write(" ") write(gqlNode.selectionSet!!) } else { write("\n") } } else -> super.write(gqlNode) } } } writer.write(gqlNode) return buffer.readUtf8() } @OptIn(ApolloExperimental::class) fun GQLNode.copyWithSortedChildren(): GQLNode { return when (this) { is GQLDocument -> { copy(definitions = definitions.sortedBy { it.score() }) } is GQLOperationDefinition -> { copy(variableDefinitions = variableDefinitions.sortedBy { it.score() }) } is GQLSelectionSet -> { copy(selections = selections.sortedBy { it.score() }) } is GQLField -> { copy(arguments = arguments) } is GQLFragmentSpread -> { copy(directives = directives.sortedBy { it.score() }) } is GQLInlineFragment -> { copy(directives = directives.sortedBy { it.score() }) } is GQLFragmentDefinition -> { copy(directives = directives.sortedBy { it.score() }) } is GQLDirective -> { copy(arguments = arguments) } is GQLArguments -> { copy(arguments = arguments.sortedBy { it.score() }) } else -> this } } @OptIn(ApolloExperimental::class) fun GQLNode.sort(): GQLNode { val newChildren = children.mapNotNull { it.sort() } val nodeContainer = NodeContainer(newChildren) return copyWithNewChildrenInternal(nodeContainer).also { nodeContainer.assert() }.copyWithSortedChildren() } @OptIn(ApolloExperimental::class) object RegisterOperations { private val mutation = """ mutation RegisterOperations( ${'$'}id : ID! ${'$'}clientIdentity : RegisteredClientIdentityInput! ${'$'}operations : [RegisteredOperationInput!]! ${'$'}manifestVersion : Int! ${'$'}graphVariant : String ) { service(id: ${'$'}id ) { registerOperationsWithResponse( clientIdentity: ${'$'}clientIdentity operations: ${'$'}operations manifestVersion: ${'$'}manifestVersion graphVariant: ${'$'}graphVariant ) { invalidOperations { errors { message } signature } newOperations { signature } registrationSuccess } } } """.trimIndent() private fun String.normalize(): String { val gqlDocument = Buffer().writeUtf8(this).parseAsGQLDocument().valueAssertNoErrors() // From https://github.com/apollographql/apollo-tooling/blob/6d69f226c2e2c54b4fc0de6394d813bddfb54694/packages/apollo-graphql/src/operationId.ts#L84 // No need to "Drop unused definition" as we include only one operation // hideLiterals val hiddenLiterals = gqlDocument.transform { when (it) { is GQLIntValue -> { TransformResult.Replace(it.copy(value = 0)) } is GQLFloatValue -> { /** * Because in JS (0.0).toString == "0" (vs "0.0" on the JVM), we replace the FloatValue by an IntValue * Since we always hide literals, this should be correct * See https://youtrack.jetbrains.com/issue/KT-33358 */ TransformResult.Replace( GQLIntValue( sourceLocation = it.sourceLocation, value = 0 ) ) } is GQLStringValue -> { TransformResult.Replace(it.copy(value = "")) } else -> TransformResult.Continue } } /** * Algorithm taken from https://github.com/apollographql/apollo-tooling/blob/6d69f226c2e2c54b4fc0de6394d813bddfb54694/packages/apollo-graphql/src/transforms.ts#L102 * It's not 100% exact but it's important that it matches what apollo-tooling is doing for safelisting * * Especially: * - it doesn't sort inline fragment * - it doesn't sort field directives */ val sortedDocument = hiddenLiterals!!.sort() val minimized = printDocument(sortedDocument) .replace(Regex("\\s+"), " ") .replace(Regex("([^_a-zA-Z0-9]) ")) { it.groupValues[1] } .replace(Regex(" ([^_a-zA-Z0-9])")) { it.groupValues[1] } return minimized } internal fun String.safelistingHash(): String { return OperationIdGenerator.Sha256.apply(normalize(), "") } fun registerOperations( key: String, graphID: String, graphVariant: String, operationOutput: OperationOutput, ) { val variables = mapOf( "id" to graphID, "clientIdentity" to mapOf( "name" to "apollo-android", "identifier" to "apollo-android", "version" to APOLLO_VERSION, ), "operations" to operationOutput.entries.map { val document = it.value.source mapOf( "signature" to document.safelistingHash(), "document" to document ) }, "manifestVersion" to 2, "graphVariant" to graphVariant ) val response = SchemaHelper.executeQuery(mutation, variables, "https://graphql.api.apollographql.com/api/graphql", mapOf("x-api-key" to key)) check(response.isSuccessful) val responseString = response.body.use { it?.string() } val errors = responseString ?.fromJson<Map<String, *>>() ?.get("data").cast<Map<String, *>>() ?.get("service").cast<Map<String, *>>() ?.get("registerOperationsWithResponse").cast<Map<String, *>>() ?.get("invalidOperations").cast<List<Map<String, *>>>() ?.flatMap { it.get("errors").cast<List<String>>() ?: emptyList() } ?: emptyList() check(errors.isEmpty()) { "Cannot push operations: ${errors.joinToString("\n")}" } val success = responseString ?.fromJson<Map<String, *>>() ?.get("data").cast<Map<String, *>>() ?.get("service").cast<Map<String, *>>() ?.get("registerOperationsWithResponse").cast<Map<String, *>>() ?.get("registrationSuccess").cast<Boolean>() ?: false check(success) { "Cannot push operations: $responseString" } println("Operations pushed successfully") } }
mit
cb27bdb5b1e2c5aa1e77a592764f2b2b
31.218354
168
0.635301
4.105242
false
false
false
false
apollographql/apollo-android
apollo-normalized-cache-api/src/commonMain/kotlin/com/apollographql/apollo3/cache/normalized/api/CacheResolver.kt
1
4124
package com.apollographql.apollo3.cache.normalized.api import com.apollographql.apollo3.api.CompiledField import com.apollographql.apollo3.api.Executable import com.apollographql.apollo3.api.resolveVariables import com.apollographql.apollo3.exception.CacheMissException import kotlin.jvm.JvmSuppressWildcards /** * An interface for [CacheResolver] used to read the cache */ interface CacheResolver { /** * Resolves a field from the cache. Called when reading from the cache, usually before a network request. * - takes a GraphQL field and operation variables as input and generates data for this field * - this data can be a CacheKey for objects but it can also be any other data if needed. In that respect, * it's closer to a resolver as might be found in apollo-server * - is used before a network request * - is used when reading the cache * * It can be used to map field arguments to [CacheKey]: * * ``` * { * user(id: "1"}) { * id * firstName * lastName * } * } * ``` * * ``` * override fun resolveField(field: CompiledField, variables: Executable.Variables, parent: Map<String, Any?>, parentId: String): Any? { * val id = field.resolveArgument("id", variables)?.toString() * if (id != null) { * return CacheKey(id) * } * * return super.resolveField(field, variables, parent, parentId) * } * ``` * * The simple example above isn't very representative as most of the times `@fieldPolicy` can express simple argument mappings in a more * concise way but still demonstrates how [resolveField] works. * * [resolveField] can also be generalized to return any value: * * ``` * override fun resolveField(field: CompiledField, variables: Executable.Variables, parent: Map<String, Any?>, parentId: String): Any? { * if (field.name == "name") { * // Every "name" field will return "JohnDoe" now! * return "JohnDoe" * } * * return super.resolveField(field, variables, parent, parentId) * } * ``` * * See also @fieldPolicy * See also [CacheKeyGenerator] * * @param field the field to resolve * @param variables the variables of the current operation * @param parent the parent object as a map. It can contain the same values as [Record]. Especially, nested objects will be represented * by [CacheKey] * @param parentId the id of the parent. Mainly used for debugging * * @return a value that can go in a [Record]. No type checking is done. It is the responsibility of implementations to return the correct * type */ fun resolveField( field: CompiledField, variables: Executable.Variables, parent: Map<String, @JvmSuppressWildcards Any?>, parentId: String, ): Any? } /** * A cache resolver that uses the parent to resolve fields. */ object DefaultCacheResolver: CacheResolver { /** * @param parent a [Map] that represent the object containing this field. The map values can have the same types as the ones in [Record] */ override fun resolveField( field: CompiledField, variables: Executable.Variables, parent: Map<String, @JvmSuppressWildcards Any?>, parentId: String, ): Any? { val name = field.nameWithArguments(variables) if (!parent.containsKey(name)) { throw CacheMissException(parentId, name) } return parent[name] } } /** * A [CacheResolver] that uses @fieldPolicy annotations to resolve fields and delegates to [DefaultCacheResolver] else */ object FieldPolicyCacheResolver: CacheResolver { override fun resolveField( field: CompiledField, variables: Executable.Variables, parent: Map<String, @JvmSuppressWildcards Any?>, parentId: String, ): Any? { val keyArgsValues = field.arguments.filter { it.isKey }.map { resolveVariables(it.value, variables).toString() } if (keyArgsValues.isNotEmpty()) { return CacheKey(field.type.leafType().name, keyArgsValues) } return DefaultCacheResolver.resolveField(field, variables, parent, parentId) } }
mit
00b717f19c16bd2ce8df0623ce1ef595
32.258065
139
0.681862
4.216769
false
false
false
false
mrAyaz/GCS
Android/src/org/droidplanner/android/fragments/widget/video/FullWidgetSoloLinkVideo.kt
2
12695
package org.droidplanner.android.fragments.widget.video import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Matrix import android.graphics.SurfaceTexture import android.os.Bundle import android.view.* import android.widget.TextView import com.o3dr.android.client.apis.GimbalApi import com.o3dr.android.client.apis.solo.SoloCameraApi import com.o3dr.services.android.lib.drone.attribute.AttributeEvent import com.o3dr.services.android.lib.drone.attribute.AttributeType import com.o3dr.services.android.lib.drone.companion.solo.SoloAttributes import com.o3dr.services.android.lib.drone.companion.solo.SoloEvents import com.o3dr.services.android.lib.drone.companion.solo.tlv.SoloGoproConstants import com.o3dr.services.android.lib.drone.companion.solo.tlv.SoloGoproState import com.o3dr.services.android.lib.drone.property.Attitude import com.o3dr.services.android.lib.model.AbstractCommandListener import org.droidplanner.android.R import timber.log.Timber /** * Created by Fredia Huya-Kouadio on 7/19/15. */ public class FullWidgetSoloLinkVideo : BaseVideoWidget() { companion object { private val filter = initFilter() @JvmStatic protected val TAG = FullWidgetSoloLinkVideo::class.java.simpleName private fun initFilter(): IntentFilter { val temp = IntentFilter() temp.addAction(AttributeEvent.STATE_CONNECTED) temp.addAction(SoloEvents.SOLO_GOPRO_STATE_UPDATED) return temp } } private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { AttributeEvent.STATE_CONNECTED -> { tryStreamingVideo() onGoproStateUpdate() } SoloEvents.SOLO_GOPRO_STATE_UPDATED -> { onGoproStateUpdate() } } } } private var surfaceRef: Surface? = null private val textureView by lazy(LazyThreadSafetyMode.NONE) { view?.findViewById(R.id.sololink_video_view) as TextureView? } private val videoStatus by lazy(LazyThreadSafetyMode.NONE) { view?.findViewById(R.id.sololink_video_status) as TextView? } private val widgetButtonBar by lazy(LazyThreadSafetyMode.NONE) { view?.findViewById(R.id.widget_button_bar) } private val takePhotoButton by lazy(LazyThreadSafetyMode.NONE) { view?.findViewById(R.id.sololink_take_picture_button) } private val recordVideo by lazy(LazyThreadSafetyMode.NONE) { view?.findViewById(R.id.sololink_record_video_button) } private val touchCircleImage by lazy(LazyThreadSafetyMode.NONE) { view?.findViewById(R.id.sololink_gimbal_joystick) } private val orientationListener = object : GimbalApi.GimbalOrientationListener { override fun onGimbalOrientationUpdate(orientation: GimbalApi.GimbalOrientation) { } override fun onGimbalOrientationCommandError(code: Int) { Timber.e("command failed with error code: %d", code) } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_widget_sololink_video, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) textureView?.surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable(surface: SurfaceTexture?, width: Int, height: Int) { adjustAspectRatio(textureView as TextureView); surfaceRef = Surface(surface) tryStreamingVideo() } override fun onSurfaceTextureDestroyed(surface: SurfaceTexture?): Boolean { surfaceRef = null tryStoppingVideoStream() return true } override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture?, width: Int, height: Int) { } override fun onSurfaceTextureUpdated(surface: SurfaceTexture?) { } } takePhotoButton?.setOnClickListener { Timber.d("Taking photo.. cheeze!") val drone = drone if (drone != null) { //TODO: fix when camera control support is stable on sololink SoloCameraApi.getApi(drone).takePhoto(null) } } recordVideo?.setOnClickListener { Timber.d("Recording video!") val drone = drone if (drone != null) { //TODO: fix when camera control support is stable on sololink SoloCameraApi.getApi(drone).toggleVideoRecording(null) } } } override fun onApiConnected() { tryStreamingVideo() onGoproStateUpdate() broadcastManager.registerReceiver(receiver, filter) } override fun onResume() { super.onResume() tryStreamingVideo() } override fun onPause() { super.onPause() tryStoppingVideoStream() } override fun onApiDisconnected() { tryStoppingVideoStream() onGoproStateUpdate() broadcastManager.unregisterReceiver(receiver) } private fun tryStreamingVideo() { if (surfaceRef == null) return val drone = drone videoStatus?.visibility = View.GONE startVideoStream(surfaceRef, TAG, object : AbstractCommandListener() { override fun onError(error: Int) { Timber.d("Unable to start video stream: %d", error) GimbalApi.getApi(drone).stopGimbalControl(orientationListener) textureView?.setOnTouchListener(null) videoStatus?.visibility = View.VISIBLE } override fun onSuccess() { videoStatus?.visibility = View.GONE Timber.d("Video stream started successfully") GimbalApi.getApi(drone).startGimbalControl(orientationListener) val gimbalTracker = object : View.OnTouchListener { var startX: Float = 0f var startY: Float = 0f override fun onTouch(view: View, event: MotionEvent): Boolean { return moveCopter(view, event) } private fun yawRotateTo(view: View, event: MotionEvent): Double { val drone = drone ?: return -1.0 val attitude = drone.getAttribute<Attitude>(AttributeType.ATTITUDE) var currYaw = attitude.getYaw() //yaw value is between -180 and 180. Convert so the value is between 0 to 360 if (currYaw < 0) { currYaw += 360.0 } val degreeIntervals = (360f / view.width).toDouble() val rotateDeg = (degreeIntervals * (event.x - startX)).toFloat() var rotateTo = currYaw.toFloat() + rotateDeg //Ensure value stays in range between 0 and 360 rotateTo = (rotateTo + 360) % 360 return rotateTo.toDouble() } private fun moveCopter(view: View, event: MotionEvent): Boolean { val xTouch = event.x val yTouch = event.y val touchWidth = touchCircleImage?.width ?: 0 val touchHeight = touchCircleImage?.height ?: 0 val centerTouchX = (touchWidth / 2f).toFloat() val centerTouchY = (touchHeight / 2f).toFloat() when (event.action) { MotionEvent.ACTION_DOWN -> { touchCircleImage?.setVisibility(View.VISIBLE) touchCircleImage?.setX(xTouch - centerTouchX) touchCircleImage?.setY(yTouch - centerTouchY) startX = event.x startY = event.y return true } MotionEvent.ACTION_MOVE -> { val yawRotateTo = yawRotateTo(view, event).toFloat() sendYawAndPitch(view, event, yawRotateTo) touchCircleImage?.setVisibility(View.VISIBLE) touchCircleImage?.setX(xTouch - centerTouchX) touchCircleImage?.setY(yTouch - centerTouchY) return true } MotionEvent.ACTION_UP -> { touchCircleImage?.setVisibility(View.GONE) } } return false } private fun sendYawAndPitch(view: View, event: MotionEvent, rotateTo: Float) { val orientation = GimbalApi.getApi(drone).getGimbalOrientation() val degreeIntervals = 90f / view.height val pitchDegree = (degreeIntervals * (startY - event.y)).toFloat() val pitchTo = orientation.getPitch() + pitchDegree Timber.d("Pitch %f roll %f yaw %f", orientation.getPitch(), orientation.getRoll(), rotateTo) Timber.d("degreeIntervals: %f pitchDegree: %f, pitchTo: %f", degreeIntervals, pitchDegree, pitchTo) GimbalApi.getApi(drone).updateGimbalOrientation(pitchTo, orientation.getRoll(), rotateTo, orientationListener) } } textureView?.setOnTouchListener(gimbalTracker) } override fun onTimeout() { Timber.d("Timed out while trying to start the video stream") GimbalApi.getApi(drone).stopGimbalControl(orientationListener) textureView?.setOnTouchListener(null) videoStatus?.visibility = View.VISIBLE } }) } private fun tryStoppingVideoStream() { val drone = drone stopVideoStream(TAG, object : AbstractCommandListener() { override fun onError(error: Int) { Timber.d("Unable to stop video stream: %d", error) } override fun onSuccess() { Timber.d("Video streaming stopped successfully.") GimbalApi.getApi(drone).stopGimbalControl(orientationListener) } override fun onTimeout() { Timber.d("Timed out while stopping video stream.") } }) } private fun onGoproStateUpdate() { val goproState: SoloGoproState? = drone?.getAttribute(SoloAttributes.SOLO_GOPRO_STATE) if (goproState == null) { widgetButtonBar?.visibility = View.GONE } else { widgetButtonBar?.visibility = View.VISIBLE //Update the video recording button recordVideo?.isActivated = goproState.captureMode == SoloGoproConstants.CAPTURE_MODE_VIDEO && goproState.recording == SoloGoproConstants.RECORDING_ON } } private fun adjustAspectRatio(textureView: TextureView) { val viewWidth = textureView.width val viewHeight = textureView.height val aspectRatio: Float = 9f / 16f val newWidth: Int val newHeight: Int if (viewHeight > (viewWidth * aspectRatio)) { //limited by narrow width; restrict height newWidth = viewWidth newHeight = (viewWidth * aspectRatio).toInt() } else { //limited by short height; restrict width newWidth = (viewHeight / aspectRatio).toInt(); newHeight = viewHeight } val xoff = (viewWidth - newWidth) / 2f val yoff = (viewHeight - newHeight) / 2f val txform = Matrix(); textureView.getTransform(txform); txform.setScale((newWidth.toFloat() / viewWidth), newHeight.toFloat() / viewHeight); txform.postTranslate(xoff, yoff); textureView.setTransform(txform); } }
gpl-3.0
cdc0763082fd69b86966fc37531ac519
37.240964
134
0.583064
5.061802
false
false
false
false
exercism/xkotlin
exercises/practice/grains/src/test/kotlin/BoardTest.kt
1
1572
import org.junit.Ignore import org.junit.Test import java.math.BigInteger import kotlin.test.assertEquals class BoardTest { @Test fun `per square - 1`() = assertGrainsEqual(1, 1) @Ignore @Test fun `per square - 2`() = assertGrainsEqual(2, 2) @Ignore @Test fun `per square - 3`() = assertGrainsEqual(3, 4) @Ignore @Test fun `per square - 4`() = assertGrainsEqual(4, 8) @Ignore @Test fun `per square - 16`() = assertGrainsEqual(16, 32768) @Ignore @Test fun `per square - 32`() = assertGrainsEqual(32, 2147483648) @Ignore @Test fun `per square - 64`() = assertGrainsEqual(64, "9223372036854775808") @Ignore @Test(expected = IllegalArgumentException::class) fun `invalid input - square 0`() { grains(0) } @Ignore @Test(expected = IllegalArgumentException::class) fun `invalid input - negative square`() { grains(-1) } @Ignore @Test(expected = IllegalArgumentException::class) fun `invalid input - square after 64`() { grains(65) } @Ignore @Test fun `total - all grains on board`() { assertEquals(BigInteger("18446744073709551615"), Board.getTotalGrainCount()) } } private fun assertGrainsEqual(cell: Int, expectation: String) = assertEquals(BigInteger(expectation), grains(cell)) private fun assertGrainsEqual(cell: Int, expectation: Long) = assertEquals(BigInteger.valueOf(expectation), grains(cell)) private fun grains(cell: Int) = Board.getGrainCountForSquare(cell)
mit
4a76cf2759bca16870be87925abeb00c
22.818182
84
0.646947
3.716312
false
true
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/internal/TrustedModeAction.kt
3
1072
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal import com.intellij.ide.impl.TrustedProjectSettings import com.intellij.ide.impl.getTrustedState import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAwareAction import com.intellij.util.ThreeState sealed class TrustedModeAction(val state: ThreeState) : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { if (state == e.project?.getTrustedState()) return e.project?.service<TrustedProjectSettings>()?.trustedState = state } override fun update(e: AnActionEvent) { if (state == e.project?.getTrustedState()) { e.presentation.isEnabled = false } e.presentation.isVisible = true } } class UnsureTrustAction : TrustedModeAction(ThreeState.UNSURE) class YesTrustAction : TrustedModeAction(ThreeState.YES) class NoTrustAction : TrustedModeAction(ThreeState.NO)
apache-2.0
0adfb046b6d084662ea0324da57f79c8
37.285714
140
0.785448
4.237154
false
false
false
false
notsyncing/cowherd
cowherd-cluster/src/main/kotlin/io/github/notsyncing/cowherd/cluster/CowherdCluster.kt
1
653
package io.github.notsyncing.cowherd.cluster object CowherdCluster { private lateinit var master: CowherdClusterMaster private lateinit var slave: CowherdClusterSlave var isMaster = System.getProperty("cowherd.cluster.mode") != "slave" val currentNode = if (isMaster) master else slave fun init() { if (isMaster) { slave = CowherdClusterSlave() slave.init() } else { master = CowherdClusterMaster() master.init() } } fun destroy() { if (isMaster) { master.destroy() } else { slave.destroy() } } }
gpl-3.0
f8871257b61e7f62504ef647fd0867fc
22.357143
72
0.572741
4.38255
false
false
false
false
Raizlabs/DBFlow
tests/src/androidTest/java/com/dbflow5/User.kt
1
446
package com.dbflow5 import com.dbflow5.annotation.Column import com.dbflow5.annotation.PrimaryKey import com.dbflow5.annotation.Table import com.dbflow5.contentobserver.ContentObserverDatabase @Table(database = ContentObserverDatabase::class, name = "User2") class User(@PrimaryKey var id: Int = 0, @Column var firstName: String? = null, @Column var lastName: String? = null, @Column var email: String? = null)
mit
e05b3f13584a7eae358714054a98e440
36.166667
65
0.733184
3.946903
false
false
false
false
intellij-purescript/intellij-purescript
src/main/kotlin/org/purescript/ide/actions/CreateFileAction.kt
1
4791
package org.purescript.ide.actions import com.intellij.ide.actions.CreateFileFromTemplateAction import com.intellij.ide.actions.CreateFileFromTemplateDialog import com.intellij.ide.fileTemplates.FileTemplate import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.ide.fileTemplates.actions.AttributesDefaults import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog import com.intellij.openapi.project.Project import com.intellij.openapi.ui.InputValidatorEx import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import org.purescript.icons.PSIcons import java.nio.file.Paths import java.util.* class CreateFileAction : CreateFileFromTemplateAction(TITLE, "", PSIcons.FILE) { override fun buildDialog( project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder ) { /* * If we add more kinds here, IntelliJ will prompt for which kind * you want to create when invoking the action. * * All template names must correspond to a file in [/src/main/resources/fileTemplates/internal], * and to a <internalFileTemplate/> in [src/main/resources/META-INF/plugin.xml] */ builder.setTitle(TITLE) .addKind("Module", PSIcons.FILE, "Purescript Module") .setValidator(NAME_VALIDATOR) } override fun getActionName( directory: PsiDirectory?, newName: String, templateName: String? ): String = TITLE /** * We override this so that we can control the properties * that are sent into the template. In particular, we want * `MODULE_NAME` to be available for the template engine. * * It looks a little hacky using the [CreateFromTemplateDialog] to create the file, * since we don't want any additional dialogs, but I couldn't find an easier way to do it. * The Julia plugin project is passing custom properties this way: * [https://github.com/JuliaEditorSupport/julia-intellij/blob/master/src/org/ice1000/julia/lang/action/julia-file-actions.kt] */ override fun createFileFromTemplate( name: String, template: FileTemplate, dir: PsiDirectory ): PsiFile? { val lastModuleName = name.removeSuffix(".purs") .split(".") .last() val fileName = "$lastModuleName.purs" val properties = getProperties(lastModuleName, dir) // We need to set AttributesDefaults here, otherwise we will get prompted for the file name val dialog = CreateFromTemplateDialog( dir.project, dir, template, AttributesDefaults(fileName).withFixedName(true), properties ) return dialog.create()?.containingFile } private fun getProperties( lastModuleName: String, dir: PsiDirectory ): Properties { val filePath = Paths.get(dir.virtualFile.path) val relativePath = try { dir .project .basePath ?.let { Paths.get(it).toAbsolutePath() } ?.relativize(filePath.toAbsolutePath()) ?: filePath } catch (ignore: java.lang.IllegalArgumentException) { filePath } val moduleName = relativePath .reversed() .takeWhile { "$it" != "src" && "$it" != "test" } .filter { "$it".first().isUpperCase()} .reversed() .joinToString(".") .let { "$it.$lastModuleName" } .removePrefix(".") val properties = FileTemplateManager.getInstance(dir.project).defaultProperties properties += "MODULE_NAME" to moduleName return properties } companion object { const val TITLE = "Purescript File" internal val NAME_VALIDATOR = object : InputValidatorEx { override fun checkInput(inputString: String?): Boolean = true override fun canClose(inputString: String?): Boolean = getErrorText(inputString) == null override fun getErrorText(inputString: String?): String? { if (inputString.isNullOrBlank()) { return "File name cannot be empty" } if (!inputString.first().isUpperCase()) { return "File name must start with a capital letter" } return null } } } /** * Exposed only for testing purposes. */ internal fun internalCreateFile( name: String, templateName: String, dir: PsiDirectory ) = createFile(name, templateName, dir) }
bsd-3-clause
5fc7acc4479bd6aeaacf69dad8cbfce8
34.227941
134
0.620539
4.908811
false
false
false
false
byoutline/kickmaterial
app/src/main/java/com/byoutline/kickmaterial/model/DiscoverQuery.kt
1
2924
package com.byoutline.kickmaterial.model import android.databinding.BaseObservable import java.util.* /** * @author Sebastian Kacprzak <sebastian.kacprzak at byoutline.com> */ class DiscoverQuery(val queryMap: Map<String, String>, val discoverType: DiscoverType) : BaseObservable() { val pageFromQuery: Int? get() { if (queryMap.containsKey("page")) { return Integer.valueOf(queryMap["page"]) } return null } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val that = other as DiscoverQuery? if (queryMap != that!!.queryMap) return false return discoverType == that.discoverType } override fun hashCode(): Int { var result = queryMap.hashCode() result = 31 * result + discoverType.hashCode() return result } companion object { private const val PER_PAGE = 12 private fun getDiscover(page: Int?): DiscoverQuery { val firstPage = page == null || page == 1 val params = if (firstPage) emptyMap<String, String>() else getDiscoverCategoryMap(null, page, PER_PAGE, null) return DiscoverQuery(params, DiscoverType.DISCOVER) } private fun getDiscoverCategory(categoryId: Int, page: Int, sort: SortTypes): DiscoverQuery { val params = getDiscoverCategoryMap(categoryId, page, PER_PAGE, sort) return DiscoverQuery(params, DiscoverType.DISCOVER_CATEGORY) } fun getDiscoverSearch(searchTerm: String, categoryId: Int?, page: Int?, sort: SortTypes): DiscoverQuery { val params = getDiscoverCategoryMap(categoryId, page, PER_PAGE, sort) params.put("term", searchTerm) return DiscoverQuery(params, DiscoverType.SEARCH) } private fun getDiscoverCategoryMap(categoryId: Int?, page: Int?, perPage: Int?, sort: SortTypes?): MutableMap<String, String> { val params = HashMap<String, String>() if (categoryId != null) { params.put("category_id", Integer.toString(categoryId)) } if (page != null) { params.put("page", Integer.toString(page)) } if (perPage != null) { params.put("per_page", Integer.toString(perPage)) } if (sort != null) { params.put("sort", sort.apiName) } return params } fun getDiscoverQuery(category: Category?, page: Int): DiscoverQuery { return if (category == null || category.categoryId == Category.ALL_CATEGORIES_ID) { getDiscover(page) } else { getDiscoverCategory(category.categoryId, page, SortTypes.MAGIC) } } } }
apache-2.0
8f9d6e89d0cf5ede4bfa7ca119047efb
35.098765
135
0.594391
4.64127
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/keepawake/KeepAwakeModule.kt
2
1832
// Copyright 2015-present 650 Industries. All rights reserved. package abi44_0_0.expo.modules.keepawake import android.content.Context import abi44_0_0.expo.modules.core.ExportedModule import abi44_0_0.expo.modules.core.ModuleRegistry import abi44_0_0.expo.modules.core.interfaces.services.KeepAwakeManager import abi44_0_0.expo.modules.core.ModuleRegistryDelegate import abi44_0_0.expo.modules.core.Promise import abi44_0_0.expo.modules.core.interfaces.ExpoMethod import abi44_0_0.expo.modules.core.errors.CurrentActivityNotFoundException private const val NAME = "ExpoKeepAwake" private const val NO_ACTIVITY_ERROR_CODE = "NO_CURRENT_ACTIVITY" class KeepAwakeModule( context: Context, private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate() ) : ExportedModule(context) { private val keepAwakeManager: KeepAwakeManager by moduleRegistry() private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() override fun onCreate(moduleRegistry: ModuleRegistry) { moduleRegistryDelegate.onCreate(moduleRegistry) } override fun getName(): String { return NAME } @ExpoMethod fun activate(tag: String, promise: Promise) { try { keepAwakeManager.activate(tag) { promise.resolve(true) } } catch (ex: CurrentActivityNotFoundException) { promise.reject(NO_ACTIVITY_ERROR_CODE, "Unable to activate keep awake") } } @ExpoMethod fun deactivate(tag: String, promise: Promise) { try { keepAwakeManager.deactivate(tag) { promise.resolve(true) } } catch (ex: CurrentActivityNotFoundException) { promise.reject(NO_ACTIVITY_ERROR_CODE, "Unable to deactivate keep awake. However, it probably is deactivated already.") } } val isActivated: Boolean get() = keepAwakeManager.isActivated }
bsd-3-clause
2092601d5bbcfbe0f29cebbc8425cfc7
32.925926
125
0.766921
4.080178
false
false
false
false
exponent/exponent
packages/expo-dev-menu/android/src/main/java/expo/modules/devmenu/devtools/DevMenuDevToolsDelegate.kt
2
3724
package expo.modules.devmenu.devtools import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.provider.Settings import android.util.Log import com.facebook.react.ReactInstanceManager import com.facebook.react.bridge.UiThreadUtil import com.facebook.react.devsupport.DevInternalSettings import expo.interfaces.devmenu.DevMenuManagerInterface import expo.modules.devmenu.DEV_MENU_TAG import expo.modules.devmenu.DevMenuManager import kotlinx.coroutines.launch import java.lang.ref.WeakReference class DevMenuDevToolsDelegate( private val manager: DevMenuManagerInterface, reactInstanceManager: ReactInstanceManager ) { private val _reactDevManager = WeakReference( reactInstanceManager.devSupportManager ) private val _reactContext = WeakReference( reactInstanceManager.currentReactContext ) val reactDevManager get() = _reactDevManager.get() val devSettings get() = reactDevManager?.devSettings val reactContext get() = _reactContext.get() fun reload() { val reactDevManager = reactDevManager ?: return manager.closeMenu() UiThreadUtil.runOnUiThread { reactDevManager.handleReloadJS() } } fun toggleElementInspector() = runWithDevSupportEnabled { reactDevManager?.toggleElementInspector() } fun toggleRemoteDebugging() = runWithDevSupportEnabled { val reactDevManager = reactDevManager ?: return val devSettings = devSettings ?: return manager.closeMenu() UiThreadUtil.runOnUiThread { devSettings.isRemoteJSDebugEnabled = !devSettings.isRemoteJSDebugEnabled reactDevManager.handleReloadJS() } } fun togglePerformanceMonitor(context: Context) { val reactDevManager = reactDevManager ?: return val devSettings = devSettings ?: return requestOverlaysPermission(context) runWithDevSupportEnabled { reactDevManager.setFpsDebugEnabled(!devSettings.isFpsDebugEnabled) } } fun openJsInspector() = runWithDevSupportEnabled { val devSettings = (devSettings as? DevInternalSettings) ?: return val reactContext = reactContext ?: return val metroHost = "http://${devSettings.packagerConnectionSettings.debugServerHost}" manager.coroutineScope.launch { try { DevMenuManager.metroClient.openJSInspector(metroHost, reactContext.packageName) } catch (e: Exception) { Log.w(DEV_MENU_TAG, "Unable to open js inspector: ${e.message}", e) } } } /** * RN will temporary disable `devSupport` if the current activity isn't active. * Because of that we can't call some functions like `toggleElementInspector`. * However, we can temporary set the `devSupport` flag to true and run needed methods. */ private inline fun runWithDevSupportEnabled(action: () -> Unit) { val reactDevManager = reactDevManager ?: return val currentSetting = reactDevManager.devSupportEnabled reactDevManager.devSupportEnabled = true action() reactDevManager.devSupportEnabled = currentSetting } /** * Requests for the permission that allows the app to draw overlays on other apps. * Such permission is required to enable performance monitor. */ private fun requestOverlaysPermission(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(context)) { val uri = Uri.parse("package:" + context.applicationContext.packageName) val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, uri).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } if (intent.resolveActivity(context.packageManager) != null) { context.startActivity(intent) } } } }
bsd-3-clause
1a85f1ea4ba9c6c8850baea4e4158021
31.955752
88
0.744629
4.70202
false
false
false
false
AndrewJack/gatekeeper
mobile/src/main/java/technology/mainthread/apps/gatekeeper/data/RegisterDevices.kt
1
865
package technology.mainthread.apps.gatekeeper.data import android.os.Build import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import com.google.firebase.iid.FirebaseInstanceId import technology.mainthread.apps.gatekeeper.model.firebase.Device import javax.inject.Inject class RegisterDevices @Inject constructor(private val firebaseAuth: FirebaseAuth, private val firebaseDatabase: FirebaseDatabase, private val firebaseInstanceId: FirebaseInstanceId) { fun registerDevice() { val token = firebaseInstanceId.token val user = firebaseAuth.currentUser if (token != null && user != null) { val device = Device(user.uid, Build.MANUFACTURER + Build.PRODUCT, token) firebaseDatabase.reference.child("devices").setValue(device) } } }
apache-2.0
08b1ed02964889f6365dc817f1233020
36.608696
84
0.739884
4.805556
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/AchievementsAdapter.kt
1
5245
package com.habitrpg.android.habitica.ui.adapter import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.facebook.drawee.view.SimpleDraweeView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.models.Achievement import com.habitrpg.android.habitica.models.QuestAchievement import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils import com.habitrpg.android.habitica.ui.helpers.bindOptionalView import com.habitrpg.android.habitica.ui.helpers.bindView import com.habitrpg.android.habitica.ui.views.dialogs.AchievementDetailDialog class AchievementsAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>() { var useGridLayout: Boolean = false var entries = listOf<Any>() var questAchievements = listOf<QuestAchievement>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when (viewType) { 0 -> SectionViewHolder(parent.inflate(R.layout.achievement_section_header)) 3 -> QuestAchievementViewHolder(parent.inflate(R.layout.achievement_quest_item)) else -> AchievementViewHolder(if (useGridLayout) { parent.inflate(R.layout.achievement_grid_item) } else { parent.inflate(R.layout.achievement_list_item) }) } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when { entries.size > position -> when (val entry = entries[position]) { is Achievement -> (holder as? AchievementViewHolder)?.bind(entry) is Pair<*, *> -> (holder as? SectionViewHolder)?.bind(entry) } entries.size == position -> (holder as? SectionViewHolder)?.bind(Pair("Quests completed", questAchievements.size)) else -> (holder as? QuestAchievementViewHolder)?.bind(questAchievements[position - 1 - entries.size]) } } override fun getItemCount(): Int { return entries.size + questAchievements.size + 1 } override fun getItemViewType(position: Int): Int { return when { entries.size > position -> { val entry = entries[position] if (entry is Pair<*, *>) { 0 } else { if (useGridLayout) 1 else 2 } } entries.size == position -> 0 else -> 3 } } class SectionViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { private val titleView: TextView by bindView(R.id.title) private val countView: TextView by bindView(R.id.count_label) fun bind(category: Pair<*, *>) { titleView.text = category.first as? String countView.text = category.second.toString() } } class AchievementViewHolder(itemView: View): RecyclerView.ViewHolder(itemView), View.OnClickListener { private var achievement: Achievement? = null private val achievementContainer: ViewGroup? by bindOptionalView(R.id.achievement_container) private val achievementIconView: SimpleDraweeView by bindView(R.id.achievement_icon) private val achievementCountView: TextView by bindView(R.id.achievement_count_label) private val achievementTitleView: TextView by bindView(R.id.achievement_title) private val achievementDescriptionView: TextView? by bindOptionalView(R.id.achievement_description) init { itemView.setOnClickListener(this) } fun bind(achievement: Achievement) { this.achievement = achievement val iconName = if (achievement.earned) { achievement.icon + "2x" } else { "achievement-unearned2x" } DataBindingUtils.loadImage(achievementIconView, iconName) achievementTitleView.text = achievement.title achievementDescriptionView?.text = achievement.text if (achievement.optionalCount ?: 0 > 0) { achievementCountView.visibility = View.VISIBLE achievementCountView.text = achievement.optionalCount.toString() } else { achievementCountView.visibility = View.GONE } achievementContainer?.clipToOutline = true } override fun onClick(v: View?) { achievement?.let { AchievementDetailDialog(it, itemView.context).show() } } } class QuestAchievementViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { private var achievement: QuestAchievement? = null private val achievementCountView: TextView by bindView(R.id.achievement_count_label) private val achievementTitleView: TextView by bindView(R.id.achievement_title) fun bind(achievement: QuestAchievement) { this.achievement = achievement achievementTitleView.text = achievement.title achievementCountView.text = achievement.count.toString() } } }
gpl-3.0
728d42c89280065f391d51f02dd99362
40.626984
126
0.657388
5.004771
false
false
false
false
kohesive/kohesive-iac
model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/ElastiCache.kt
1
8061
package uy.kohesive.iac.model.aws.cloudformation.resources.builders import com.amazonaws.AmazonWebServiceRequest import com.amazonaws.services.elasticache.model.* import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder import uy.kohesive.iac.model.aws.cloudformation.resources.CloudFormation import uy.kohesive.iac.model.aws.cloudformation.resources.ElastiCache class ElastiCacheSecurityGroupIngressResourcePropertiesBuilder : ResourcePropertiesBuilder<AuthorizeCacheSecurityGroupIngressRequest> { override val requestClazz = AuthorizeCacheSecurityGroupIngressRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as AuthorizeCacheSecurityGroupIngressRequest).let { ElastiCache.SecurityGroupIngress( CacheSecurityGroupName = it.cacheSecurityGroupName, EC2SecurityGroupName = it.eC2SecurityGroupName, EC2SecurityGroupOwnerId = it.eC2SecurityGroupOwnerId ) } } class ElastiCacheCacheClusterResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateCacheClusterRequest> { override val requestClazz = CreateCacheClusterRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateCacheClusterRequest).let { ElastiCache.CacheCluster( AZMode = request.azMode, AutoMinorVersionUpgrade = request.autoMinorVersionUpgrade?.toString(), CacheNodeType = request.cacheNodeType, CacheParameterGroupName = request.cacheParameterGroupName, CacheSecurityGroupNames = request.cacheSecurityGroupNames, CacheSubnetGroupName = request.cacheSubnetGroupName, ClusterName = request.cacheClusterId, Engine = request.engine, EngineVersion = request.engineVersion, NotificationTopicArn = request.notificationTopicArn, NumCacheNodes = request.numCacheNodes.toString(), Port = request.port?.toString(), PreferredAvailabilityZone = request.preferredAvailabilityZone, PreferredAvailabilityZones = request.preferredAvailabilityZones, PreferredMaintenanceWindow = request.preferredMaintenanceWindow, SnapshotArns = request.snapshotArns, SnapshotName = request.snapshotName, SnapshotRetentionLimit = request.snapshotRetentionLimit?.toString(), SnapshotWindow = request.snapshotWindow, VpcSecurityGroupIds = request.securityGroupIds, Tags = request.tags?.map { CloudFormation.ResourceTag( Key = it.key, Value = it.value ) } ) } } class ElastiCacheReplicationGroupResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateReplicationGroupRequest> { override val requestClazz = CreateReplicationGroupRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateReplicationGroupRequest).let { ElastiCache.ReplicationGroup( AutoMinorVersionUpgrade = request.autoMinorVersionUpgrade?.toString(), AutomaticFailoverEnabled = request.automaticFailoverEnabled?.toString(), CacheNodeType = request.cacheNodeType, CacheParameterGroupName = request.cacheParameterGroupName, CacheSecurityGroupNames = request.cacheSecurityGroupNames, CacheSubnetGroupName = request.cacheSubnetGroupName, Engine = request.engine, EngineVersion = request.engineVersion, NodeGroupConfiguration = request.nodeGroupConfiguration?.map { ElastiCache.ReplicationGroup.NodeGroupConfigurationProperty( PrimaryAvailabilityZone = it.primaryAvailabilityZone, ReplicaAvailabilityZones = it.replicaAvailabilityZones, ReplicaCount = it.replicaCount?.toString(), Slots = it.slots ) }, NotificationTopicArn = request.notificationTopicArn, NumCacheClusters = request.numCacheClusters?.toString(), NumNodeGroups = request.numNodeGroups?.toString(), Port = request.port?.toString(), PreferredCacheClusterAZs = request.preferredCacheClusterAZs, PreferredMaintenanceWindow = request.preferredMaintenanceWindow, PrimaryClusterId = request.primaryClusterId, ReplicasPerNodeGroup = request.replicasPerNodeGroup?.toString(), ReplicationGroupDescription = request.replicationGroupDescription, ReplicationGroupId = request.replicationGroupId, SecurityGroupIds = request.securityGroupIds, SnapshotArns = request.snapshotArns, SnapshotName = request.snapshotName, SnapshotRetentionLimit = request.snapshotRetentionLimit?.toString(), SnapshotWindow = request.snapshotWindow, SnapshottingClusterId = relatedObjects.filterIsInstance<ModifyReplicationGroupRequest>()?.firstOrNull()?.snapshottingClusterId, Tags = request.tags?.map { CloudFormation.ResourceTag( Key = it.key, Value = it.value ) } ) } } class ElastiCacheSecurityGroupResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateCacheSecurityGroupRequest> { override val requestClazz = CreateCacheSecurityGroupRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateCacheSecurityGroupRequest).let { ElastiCache.SecurityGroup( Description = request.description ) } } class ElastiCacheSubnetGroupResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateCacheSubnetGroupRequest> { override val requestClazz = CreateCacheSubnetGroupRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateCacheSubnetGroupRequest).let { ElastiCache.SubnetGroup( CacheSubnetGroupName = request.cacheSubnetGroupName, Description = request.cacheSubnetGroupDescription, SubnetIds = request.subnetIds ) } } class ElastiCacheParameterGroupResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateCacheParameterGroupRequest> { override val requestClazz = CreateCacheParameterGroupRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateCacheParameterGroupRequest).let { ElastiCache.ParameterGroup( CacheParameterGroupFamily = request.cacheParameterGroupFamily, Description = request.description, Properties = relatedObjects.filterIsInstance<ModifyCacheParameterGroupRequest>().flatMap { it.parameterNameValues }.associate { it.parameterName to it.parameterValue } ) } }
mit
9b0f9788e0602d2d5a3305fa8fcb4d45
50.673077
158
0.630443
6.153435
false
false
false
false