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
AcornUI/Acorn
acornui-core/src/main_staging/com/acornui/input/interaction/pinch.kt
1
9583
/* * Copyright 2019 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package com.acornui.input.interaction import com.acornui.ExperimentalAcorn import com.acornui.component.UiComponent import com.acornui.component.createOrReuseAttachment import com.acornui.component.stage import com.acornui.di.ContextImpl import com.acornui.function.as1 import com.acornui.input.* import com.acornui.math.Vector2 import com.acornui.math.Vector2Ro import com.acornui.math.vec2 import com.acornui.recycle.Clearable import com.acornui.signal.Signal import com.acornui.signal.Signal1 import com.acornui.time.callLater interface PinchPointsRo { val first: Vector2Ro val second: Vector2Ro } data class PinchPoints(override val first: Vector2 = vec2(), override val second: Vector2 = vec2()) : PinchPointsRo, Clearable { fun set(value: PinchPointsRo): PinchPoints { first.set(value.first) second.set(value.second) return this } override fun clear() { first.clear() second.clear() } } interface PinchEventRo : EventRo { /** * The two touch points that initiated the pinch, in canvas coordinates. */ val startPoints: PinchPointsRo /** * The distance of [startPoints], in canvas coordinates. */ val startDistance: Double get() = startPoints.first.dst(startPoints.second) /** * The current manhattan distance of [startPoints], in canvas coordinates. */ val startManhattanDst: Double get() = startPoints.first.manhattanDst(startPoints.second) /** * The midpoint of the two starting touch points, in canvas coordinates. */ val startMidpoint: Vector2Ro get() = (startPoints.second + startPoints.first) * 0.5 /** * The starting angle of the pinch, in canvas coordinates. */ val startRotation: Double get() = (startPoints.second - startPoints.first).angle /** * The two current touch points, in canvas coordinates. */ val points: PinchPointsRo /** * The current distance of [points], in canvas coordinates. */ val distance: Double get() = points.first.dst(points.second) /** * The current manhattan distance of [points], in canvas coordinates. */ val manhattanDst: Double get() { return points.first.manhattanDst(points.second) } /** * The midpoint of the two touch points, in canvas coordinates. */ val midpoint: Vector2Ro get() = (points.second + points.first) * 0.5 /** * The current angle of the pinch, in canvas coordinates. */ val rotation: Double get() = (points.second - points.first).angle val distanceDelta: Double get() = distance - startDistance } class PinchEvent : PinchEventRo, EventBase() { override val startPoints = PinchPoints() override val points = PinchPoints() override fun clear() { super.clear() startPoints.clear() points.clear() } companion object { val PINCH_START = EventType<PinchEventRo>("pinchStart") val PINCH = EventType<PinchEventRo>("pinch") val PINCH_END = EventType<PinchEventRo>("pinchEnd") } } @ExperimentalAcorn class PinchAttachment( val target: UiComponent, /** * The manhattan distance delta the pinch must change before the pinch starts. */ var affordance: Double ) : ContextImpl(target) { private val stage = target.stage private var watchingTouch = false /** * The movement has passed the affordance, and is currently pinching. */ private var _isPinching = false /** * True if the user is currently pinching. */ val isPinching: Boolean get() = _isPinching private val pinchEvent: PinchEvent = PinchEvent() private val _pinchStart = Signal1<PinchEventRo>() /** * Dispatched when the pinch has begun. This will be after the pinch has passed the affordance value. */ val pinchStart = _pinchStart.asRo() private val _pinch = Signal1<PinchEventRo>() /** * Dispatched on each frame during a pinch. */ val pinch = _pinch.asRo() private val _pinchEnd = Signal1<PinchEventRo>() /** * Dispatched when the pinch has completed. * This may either be by stopping a touch point, or the target deactivating. */ val pinchEnd = _pinchEnd.asRo() private val startPoints = PinchPoints() private val points = PinchPoints() private fun targetDeactivatedHandler() { stop() } private fun clickBlocker(event: ClickEventRo) { event.handled = true event.preventDefault() } //-------------------------------------------------------------- // Touch UX //-------------------------------------------------------------- private fun touchStartHandler(event: TouchEventRo) { if (!watchingTouch && allowTouchStart(event)) { setWatchingTouch(true) event.handled = true val firstT = event.touches[0] startPoints.first.set(firstT.canvasX, firstT.canvasY) val secondT = event.touches[1] startPoints.second.set(secondT.canvasX, secondT.canvasY) points.set(startPoints) if (allowTouchPinchStart(event)) { setIsPinching(true) } } } /** * Return true if the pinch should start watching movement. * This does not determine if a pinch start may begin. * @see allowTouchPinchStart */ private fun allowTouchStart(event: TouchEventRo): Boolean { return enabled && event.touches.size == 2 } private fun allowTouchPinchStart(event: TouchEventRo): Boolean { return Vector2.manhattanDst(event.touches[0].canvasX, event.touches[0].canvasY, event.touches[1].canvasX, event.touches[1].canvasY) >= affordance } private fun allowTouchEnd(event: TouchEventRo): Boolean { return event.touches.size < 2 } private fun setWatchingTouch(value: Boolean) { if (watchingTouch == value) return watchingTouch = value if (value) { stage.touchMove().add(::stageTouchMoveHandler) stage.touchEnd().add(::stageTouchEndHandler) } else { stage.touchMove().remove(::stageTouchMoveHandler) stage.touchEnd().remove(::stageTouchEndHandler) } } private fun stageTouchMoveHandler(event: TouchEventRo) { if (event.touches.size < 2) return val firstT = event.touches[0] points.first.set(firstT.canvasX, firstT.canvasY) val secondT = event.touches[1] points.second.set(secondT.canvasX, secondT.canvasY) if (_isPinching) { event.handled = true event.preventDefault() dispatchPinchEvent(PinchEvent.PINCH, _pinch) } else { if (!_isPinching && allowTouchPinchStart(event)) { setIsPinching(true) } } } private fun stageTouchEndHandler(event: TouchEventRo) { if (allowTouchEnd(event)) { event.handled = true setWatchingTouch(false) setIsPinching(false) } } //-------------------------------------------------------------- // Pinch //-------------------------------------------------------------- private fun setIsPinching(value: Boolean) { if (_isPinching == value) return _isPinching = value if (value) { dispatchPinchEvent(PinchEvent.PINCH_START, _pinchStart) if (pinchEvent.defaultPrevented()) { _isPinching = false } else { stage.click(isCapture = true).add(::clickBlocker, true) // Set the next click to be marked as handled. dispatchPinchEvent(PinchEvent.PINCH, _pinch) } } else { if (target.isActive) { dispatchPinchEvent(PinchEvent.PINCH, _pinch) } dispatchPinchEvent(PinchEvent.PINCH_END, _pinchEnd) callLater { stage.click(isCapture = true).remove(::clickBlocker) } } } private fun dispatchPinchEvent(type: EventType<PinchEventRo>, signal: Signal1<PinchEventRo>) { pinchEvent.clear() pinchEvent.target = target pinchEvent.currentTarget = target pinchEvent.type = type pinchEvent.startPoints.set(startPoints) pinchEvent.points.set(points) signal.dispatch(pinchEvent) } private var _enabled = true /** * If true, pinch operations are enabled. */ var enabled: Boolean get() = _enabled set(value) { if (_enabled == value) return _enabled = value if (!value) stop() } fun stop() { setWatchingTouch(false) setIsPinching(false) } init { target.deactivated.add(::targetDeactivatedHandler.as1) target.touchStart().add(::touchStartHandler) } override fun dispose() { super.dispose() stop() _pinchStart.dispose() _pinch.dispose() _pinchEnd.dispose() target.deactivated.remove(::targetDeactivatedHandler.as1) target.touchStart().remove(::touchStartHandler) } companion object { /** * The manhattan distance the target must be pinched before the pinchStart and pinch events begin. */ const val DEFAULT_AFFORDANCE: Double = 5.0 } } @ExperimentalAcorn fun UiComponent.pinchAttachment(affordance: Double = PinchAttachment.DEFAULT_AFFORDANCE): PinchAttachment { return createOrReuseAttachment(PinchAttachment) { PinchAttachment(this, affordance) } } /** * @see PinchAttachment.pinchStart */ @ExperimentalAcorn fun UiComponent.pinchStart(): Signal<PinchEventRo> { return pinchAttachment().pinchStart } /** * @see PinchAttachment.pinch */ @ExperimentalAcorn fun UiComponent.pinch(): Signal<PinchEventRo> { return pinchAttachment().pinch } /** * @see PinchAttachment.pinchEnd */ @ExperimentalAcorn fun UiComponent.pinchEnd(): Signal<PinchEventRo> { return pinchAttachment().pinchEnd }
apache-2.0
3d015df98182dae11d1ac18771f2b8d7
24.28496
147
0.703224
3.42985
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/datatypes/VimDataType.kt
1
1270
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.datatypes abstract class VimDataType { abstract fun asDouble(): Double // string value that is used in arithmetic expressions (concatenation etc.) abstract fun asString(): String abstract fun toVimNumber(): VimInt // string value that is used in echo-like commands override fun toString(): String { throw NotImplementedError("implement me :(") } open fun asBoolean(): Boolean { return asDouble() != 0.0 } abstract fun deepCopy(level: Int = 100): VimDataType var lockOwner: Any? = null var isLocked: Boolean = false abstract fun lockVar(depth: Int) abstract fun unlockVar(depth: Int) // use in cases when VimDataType's value should be inserted into document // e.g. expression register or substitute with expression fun toInsertableString(): String { return when (this) { is VimList -> { this.values.joinToString(separator = "") { it.toString() + "\n" } } is VimDictionary -> this.asString() else -> this.toString() } } }
mit
1d0378574b4c0e880f1f5d714686bfa2
25.458333
77
0.688189
4.305085
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/ui/fragments/WebViewTopScroller.kt
1
1322
package forpdateam.ru.forpda.ui.fragments import com.google.android.material.appbar.AppBarLayout import androidx.recyclerview.widget.LinearLayoutManager import android.util.Log import forpdateam.ru.forpda.ui.views.ExtendedWebView class WebViewTopScroller( private val webView: ExtendedWebView, private val appBarLayout: AppBarLayout ) : TabTopScroller { private var lastScrollY = 0 private var scrolledToTop = false init { webView.setOnScrollListener { scrollX, scrollY, oldScrollX, oldScrollY -> Log.e("webosina", "setOnScrollListener $scrolledToTop, $lastScrollY, ${webView.scrollY}") if (scrolledToTop && webView.scrollY > 0) { resetState() } } } fun resetState() { lastScrollY = 0 scrolledToTop = false } override fun toggleScrollTop() { if (lastScrollY > 0) { //appBarLayout.setExpanded(false, true); val scrollY = lastScrollY lastScrollY = 0 scrolledToTop = false webView.scrollTo(webView.scrollX, scrollY) } else { appBarLayout.setExpanded(true, true) lastScrollY = webView.scrollY scrolledToTop = true webView.scrollTo(webView.scrollX, 0) } } }
gpl-3.0
8fe6b733af165ca11130ca93cead8fe1
29.068182
101
0.632375
4.896296
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/entity/remote/reputation/RepData.kt
1
532
package forpdateam.ru.forpda.entity.remote.reputation import java.util.ArrayList import forpdateam.ru.forpda.entity.remote.others.pagination.Pagination import forpdateam.ru.forpda.model.data.remote.api.reputation.ReputationApi /** * Created by radiationx on 20.03.17. */ class RepData { var id = 0 var positive = 0 var negative = 0 var nick: String? = null var mode = ReputationApi.MODE_TO var sort = ReputationApi.SORT_DESC var pagination = Pagination() val items = mutableListOf<RepItem>() }
gpl-3.0
be2ced106dde5876101ed7dd5a188166
24.333333
74
0.729323
3.72028
false
false
false
false
DanielGrech/anko
dsl/testData/compile/AndroidPropertiesTest.kt
3
4185
package com.example.android_test import android.app.Activity import android.os.Bundle import org.jetbrains.anko.* import android.widget.LinearLayout public open class MyActivity() : Activity() { public override fun onCreate(savedInstanceState: Bundle?): Unit { super.onCreate(savedInstanceState) UI { linearLayout { val bl = baseline baselineAlignedChildIndex = 0 dividerPadding = 1 orientation = -1 showDividers = 0 weightSum = 2.4f textSwitcher {} calendarView { date = 123456 showWeekNumber = true } zoomButton {} viewSwitcher {} digitalClock {} multiAutoCompleteTextView {} checkBox { checked = true } imageButton {} videoView { val vv_currentPosition = currentPosition } horizontalScrollView {} numberPicker { val np_displayedValues = displayedValues maxValue = 3 value = 2134 } analogClock {} scrollView {} textView { compoundDrawablePadding = 23 customSelectionActionModeCallback = null error = "error" freezesText = false imeOptions = 0 linksClickable = true } tabWidget { val tw_tabCount = tabCount } radioButton {} toggleButton { textOff = "12354" textOn = "qwerty" } seekBar {} datePicker { val dp_calendarView = calendarView val dp_month = month val dp_year = year } timePicker { currentHour = 3 } zoomControls {} imageView { baseline = 234 imageMatrix = android.graphics.Matrix() } autoCompleteTextView { dropDownAnchor = 0 dropDownHeight = 0 dropDownHorizontalOffset = 2 threshold = 2 validator = null } switch { textOff = "918237" } progressBar { progress = 34 secondaryProgress = 9 } space {} listView { val lv_checkItemIds = checkItemIds itemsCanFocus = true overscrollHeader = null } gridView { gravity = 68 numColumns = 3 } spinner {} gallery {} imageSwitcher {} checkedTextView {} chronometer { base = 9 format = "%d%Y%m" } button {} editText {} ratingBar { numStars = 3 rating = 3.4f stepSize = 0.7f } stackView {} quickContactBadge {} twoLineListItem {} dialerFilter { val df_digits = digits } tabHost { currentTab = 2 val th_currentTabView = currentTabView } viewAnimator {} expandableListView { adapter = null val elv_selectedPosition = selectedPosition } viewFlipper {} } } } }
apache-2.0
70b09b74ace5a595303b909ceb797e52
30
69
0.380884
7.540541
false
false
false
false
mbrlabs/Mundus
editor/src/main/com/mbrlabs/mundus/editor/ui/modules/dialogs/assets/AssetPickerDialog.kt
1
4513
/* * Copyright (c) 2016. See AUTHORS file. * * 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.mbrlabs.mundus.editor.ui.modules.dialogs.assets import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.Touchable import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.badlogic.gdx.utils.Array import com.kotcrab.vis.ui.util.adapter.SimpleListAdapter import com.kotcrab.vis.ui.widget.ListView import com.kotcrab.vis.ui.widget.VisTable import com.kotcrab.vis.ui.widget.VisTextButton import com.mbrlabs.mundus.commons.assets.Asset import com.mbrlabs.mundus.editor.Mundus import com.mbrlabs.mundus.editor.assets.AssetFilter import com.mbrlabs.mundus.editor.core.project.ProjectManager import com.mbrlabs.mundus.editor.events.AssetImportEvent import com.mbrlabs.mundus.editor.events.ProjectChangedEvent import com.mbrlabs.mundus.editor.ui.UI import com.mbrlabs.mundus.editor.ui.modules.dialogs.BaseDialog /** * A filterable list of materials. * * The user can pick one or no asset. The list of materials can be filtered by type before * showing it to the user. * * @author Marcus Brummer * @version 02-10-2016 */ class AssetPickerDialog : BaseDialog(AssetPickerDialog.TITLE), AssetImportEvent.AssetImportListener, ProjectChangedEvent.ProjectChangedListener { private companion object { private val TITLE = "Select an asset" } private val root = VisTable() private val listAdapter = SimpleListAdapter(Array<Asset>()) private val list = ListView(listAdapter) private val noneBtn = VisTextButton("None / Remove old asset") private var filter: AssetFilter? = null private var listener: AssetPickerListener? = null private val projectManager: ProjectManager = Mundus.inject() init { Mundus.registerEventListener(this) setupUI() setupListeners() } private fun setupUI() { root.add(list.mainTable).grow().size(350f, 450f).row() root.add<VisTextButton>(noneBtn).padTop(10f).grow().row() add<VisTable>(root).padRight(5f).padBottom(5f).grow().row() } private fun setupListeners() { list.setItemClickListener { item -> if (listener != null) { listener!!.onSelected(item) close() } } noneBtn.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { if (listener != null) { listener!!.onSelected(null) close() } } }) } override fun onProjectChanged(event: ProjectChangedEvent) { reloadData() } override fun onAssetImported(event: AssetImportEvent) { reloadData() } private fun reloadData() { val assetManager = projectManager.current().assetManager listAdapter.clear() // filter assets for (asset in assetManager.assets) { if (filter != null) { if (filter!!.ignore(asset)) { continue } } listAdapter.add(asset) } listAdapter.itemsDataChanged() } /** * Shows the dialog. * * @param showNoneAsset if true the user will be able to select a NONE asset * @param filter optional asset type filter * @listener picker listener */ fun show(showNoneAsset: Boolean, filter: AssetFilter?, listener: AssetPickerListener) { this.listener = listener this.filter = filter if (showNoneAsset) { noneBtn.isDisabled = false noneBtn.touchable = Touchable.enabled } else { noneBtn.isDisabled = true noneBtn.touchable = Touchable.disabled } reloadData() UI.showDialog(this) } /** */ interface AssetPickerListener { fun onSelected(asset: Asset?) } }
apache-2.0
96a68f2e53e37173336b51602882f09c
29.70068
91
0.656326
4.356178
false
false
false
false
android/nowinandroid
core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstAuthorsRepositoryTest.kt
1
6347
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.data.repository import com.google.samples.apps.nowinandroid.core.data.Synchronizer import com.google.samples.apps.nowinandroid.core.data.model.asEntity import com.google.samples.apps.nowinandroid.core.data.testdoubles.CollectionType import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestAuthorDao import com.google.samples.apps.nowinandroid.core.data.testdoubles.TestNiaNetworkDataSource import com.google.samples.apps.nowinandroid.core.database.dao.AuthorDao import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity import com.google.samples.apps.nowinandroid.core.database.model.asExternalModel import com.google.samples.apps.nowinandroid.core.datastore.NiaPreferencesDataSource import com.google.samples.apps.nowinandroid.core.datastore.test.testUserPreferencesDataStore import com.google.samples.apps.nowinandroid.core.model.data.Author import com.google.samples.apps.nowinandroid.core.network.model.NetworkAuthor import com.google.samples.apps.nowinandroid.core.network.model.NetworkChangeList import kotlin.test.assertEquals import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder class OfflineFirstAuthorsRepositoryTest { private lateinit var subject: OfflineFirstAuthorsRepository private lateinit var authorDao: AuthorDao private lateinit var network: TestNiaNetworkDataSource private lateinit var synchronizer: Synchronizer @get:Rule val tmpFolder: TemporaryFolder = TemporaryFolder.builder().assureDeletion().build() @Before fun setup() { authorDao = TestAuthorDao() network = TestNiaNetworkDataSource() val niaPreferencesDataSource = NiaPreferencesDataSource( tmpFolder.testUserPreferencesDataStore() ) synchronizer = TestSynchronizer(niaPreferencesDataSource) subject = OfflineFirstAuthorsRepository( authorDao = authorDao, network = network, ) } @Test fun offlineFirstAuthorsRepository_Authors_stream_is_backed_by_Authors_dao() = runTest { assertEquals( authorDao.getAuthorEntitiesStream() .first() .map(AuthorEntity::asExternalModel), subject.getAuthorsStream() .first() ) } @Test fun offlineFirstAuthorsRepository_sync_pulls_from_network() = runTest { subject.syncWith(synchronizer) val networkAuthors = network.getAuthors() .map(NetworkAuthor::asEntity) val dbAuthors = authorDao.getAuthorEntitiesStream() .first() assertEquals( networkAuthors.map(AuthorEntity::id), dbAuthors.map(AuthorEntity::id) ) // After sync version should be updated assertEquals( network.latestChangeListVersion(CollectionType.Authors), synchronizer.getChangeListVersions().authorVersion ) } @Test fun offlineFirstAuthorsRepository_incremental_sync_pulls_from_network() = runTest { // Set author version to 5 synchronizer.updateChangeListVersions { copy(authorVersion = 5) } subject.syncWith(synchronizer) val changeList = network.changeListsAfter( CollectionType.Authors, version = 5 ) val changeListIds = changeList .map(NetworkChangeList::id) .toSet() val network = network.getAuthors() .map(NetworkAuthor::asEntity) .filter { it.id in changeListIds } val db = authorDao.getAuthorEntitiesStream() .first() assertEquals( network.map(AuthorEntity::id), db.map(AuthorEntity::id) ) // After sync version should be updated assertEquals( changeList.last().changeListVersion, synchronizer.getChangeListVersions().authorVersion ) } @Test fun offlineFirstAuthorsRepository_sync_deletes_items_marked_deleted_on_network() = runTest { val networkAuthors = network.getAuthors() .map(NetworkAuthor::asEntity) .map(AuthorEntity::asExternalModel) // Delete half of the items on the network val deletedItems = networkAuthors .map(Author::id) .partition { it.chars().sum() % 2 == 0 } .first .toSet() deletedItems.forEach { network.editCollection( collectionType = CollectionType.Authors, id = it, isDelete = true ) } subject.syncWith(synchronizer) val dbAuthors = authorDao.getAuthorEntitiesStream() .first() .map(AuthorEntity::asExternalModel) // Assert that items marked deleted on the network have been deleted locally assertEquals( networkAuthors.map(Author::id) - deletedItems, dbAuthors.map(Author::id) ) // After sync version should be updated assertEquals( network.latestChangeListVersion(CollectionType.Authors), synchronizer.getChangeListVersions().authorVersion ) } }
apache-2.0
0365ec17fde17e58fcf4ecf5a42c0c91
34.261111
92
0.641563
5.041303
false
true
false
false
GunoH/intellij-community
plugins/markdown/test/src/org/intellij/plugins/markdown/preview/jcef/MarkdownPreviewSecurityTest.kt
2
5008
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.preview.jcef import com.intellij.testFramework.ExtensionTestUtil import com.intellij.util.ui.UIUtil import org.cef.browser.CefBrowser import org.cef.browser.CefFrame import org.cef.handler.CefLoadHandler import org.cef.handler.CefLoadHandlerAdapter import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension import org.junit.After import org.junit.Before import org.junit.Test import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @RunWith(Parameterized::class) class MarkdownPreviewSecurityTest(enableOsr: Boolean): MarkdownJcefTestCase(enableOsr) { @Before fun disablePreviewExtensions() { ExtensionTestUtil.maskExtensions(MarkdownBrowserPreviewExtension.Provider.EP, emptyList(), disposable) } @After fun ensureEdtIsPumped() { // wait until com.intellij.ui.jcef.JBCefOsrHandler.onPaint is called which call invokeLater() Thread.sleep(500) UIUtil.pump() } @Test fun `test meta redirects are not allowed`() { val maliciousUrl = "https://evil.example.com/poc.html" // language=HTML val content = """ <html> <body> <meta http-equiv="refresh" content="0;url=$maliciousUrl"> </body> </html> """.trimIndent() val latch = CountDownLatch(2) var canceledUrl: String? = null setupPreview(content) { browser -> browser.addLoadHandler(object: CefLoadHandlerAdapter() { override fun onLoadEnd(browser: CefBrowser, frame: CefFrame, httpStatusCode: Int) { latch.countDown() } override fun onLoadError(browser: CefBrowser, frame: CefFrame, errorCode: CefLoadHandler.ErrorCode, errorText: String, failedUrl: String) { canceledUrl = failedUrl latch.countDown() } }) } assertTrue(latch.await(latchAwaitTimeout, TimeUnit.SECONDS)) assertEquals(maliciousUrl, canceledUrl) } @Test fun `test panel won't reload on manual location change`() { val maliciousUrl = "https://google.com/" // language=HTML val content = "<html><body></body></html>" val latch = CountDownLatch(1) var canceledUrl: String? = null setupPreview(content) { browser -> browser.addLoadHandler(object: CefLoadHandlerAdapter() { override fun onLoadEnd(browser: CefBrowser, frame: CefFrame, httpStatusCode: Int) { browser.executeJavaScript("window.location.replace('$maliciousUrl')", null, 0) } override fun onLoadError(browser: CefBrowser, frame: CefFrame, errorCode: CefLoadHandler.ErrorCode, errorText: String, failedUrl: String) { canceledUrl = failedUrl latch.countDown() } }) } assertTrue(latch.await(latchAwaitTimeout, TimeUnit.SECONDS)) assertEquals(maliciousUrl, canceledUrl) } @Test fun `test external scripts are not allowed`() { val maliciousUrl = "https://evil.example.com/some-script.js" // language=HTML val content = "<html><body><script src='$maliciousUrl'></body></html>" val latch = CountDownLatch(1) setupPreview(content) { browser -> browser.addConsoleMessageHandler { _, message, _, _ -> if (message.contains("Refused to load the script 'https://evil.example.com/some-script.js'")) { latch.countDown() } } } assertTrue(latch.await(latchAwaitTimeout, TimeUnit.SECONDS)) } @Test fun `test dynamically added inline scripts are not allowed`() { // language=HTML val content = "<html><body><script>console.log('Ops!');</script></body></html>" val latch = CountDownLatch(1) setupPreview(content) { browser -> browser.addLoadHandler(object: CefLoadHandlerAdapter() { override fun onLoadEnd(browser: CefBrowser, frame: CefFrame, httpStatusCode: Int) { // language=JavaScript val scriptContent = """ const element = document.createElement("script"); element.innerHTML = "console.log('Ops!!')"; document.body.appendChild(element); """.trimIndent() browser.executeJavaScript(scriptContent, null, 0) } }) browser.addConsoleMessageHandler { _, message, _, _ -> if (message.contains("Refused to execute inline script because it violates the following Content Security Policy directive")) { latch.countDown() } } } assertTrue(latch.await(latchAwaitTimeout, TimeUnit.SECONDS)) } companion object { private const val latchAwaitTimeout = 10L @Suppress("unused") @JvmStatic @get:Parameterized.Parameters(name = "enableOsr = {0}") val modes = listOf(true) } }
apache-2.0
377abf5947f02a6e6fa7e2f9bc246484
35.554745
158
0.688898
4.20487
false
true
false
false
GunoH/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/secondStep/SecondStepWizardComponent.kt
4
3539
// 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.tools.projectWizard.wizard.ui.secondStep import com.intellij.util.ui.JBUI import org.jetbrains.kotlin.idea.statistics.WizardStatsService.UiEditorUsageStats import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module import org.jetbrains.kotlin.tools.projectWizard.wizard.IdeWizard import org.jetbrains.kotlin.tools.projectWizard.wizard.KotlinNewProjectWizardUIBundle import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.* import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.secondStep.modulesEditor.ModulesEditorComponent import java.awt.BorderLayout class SecondStepWizardComponent( wizard: IdeWizard, uiEditorUsagesStats: UiEditorUsageStats ) : WizardStepComponent(wizard.context) { private val moduleEditorComponent = ProjectStructureEditorComponent(wizard.context, uiEditorUsagesStats, ::onNodeSelected).asSubComponent() private val moduleSettingsComponent = ModuleSettingsSubStep(wizard, uiEditorUsagesStats).asSubComponent() override val component = SmartTwoComponentPanel( moduleSettingsComponent.component, moduleEditorComponent.component, sideIsOnTheRight = false ) override fun navigateTo(error: ValidationResult.ValidationError) { moduleEditorComponent.navigateTo(error) moduleSettingsComponent.navigateTo(error) } private fun onNodeSelected(data: DisplayableSettingItem?) { moduleSettingsComponent.selectedNode = data } } class ProjectStructureEditorComponent( context: Context, uiEditorUsagesStats: UiEditorUsageStats, onNodeSelected: (data: DisplayableSettingItem?) -> Unit ) : DynamicComponent(context) { private val moduleSettingComponent = ModulesEditorComponent( context, uiEditorUsagesStats, needBorder = true, editable = true, oneEntrySelected = onNodeSelected ).asSubComponent() override val component = borderPanel { addToCenter(moduleSettingComponent.component.addBorder(JBUI.Borders.empty(UIConstants.PADDING))) } } class ModuleSettingsSubStep( wizard: IdeWizard, uiEditorUsagesStats: UiEditorUsageStats ) : SubStep(wizard.context) { private val moduleSettingsComponent = ModuleSettingsComponent(wizard.context, uiEditorUsagesStats).asSubComponent() private val nothingSelected = PanelWithStatusText( BorderLayout(), KotlinNewProjectWizardUIBundle.message("error.nothing.selected"), isStatusTextVisible = true ) private val panel = customPanel { add(nothingSelected, BorderLayout.CENTER) } var selectedNode: DisplayableSettingItem? = null set(value) { field = value moduleSettingsComponent.module = value as? Module changeComponent() } private fun changeComponent() { panel.removeAll() val component = when (selectedNode) { is Module -> moduleSettingsComponent.component else -> nothingSelected } panel.add(component, BorderLayout.CENTER) panel.updateUI() } override fun buildContent() = panel }
apache-2.0
e3a5b3ebfb7eb3816dc74d962e67ddc0
36.648936
158
0.751625
4.942737
false
false
false
false
google-developer-training/android-basics-kotlin-lunch-tray-app
app/src/main/java/com/example/lunchtray/ui/order/CheckoutFragment.kt
1
3434
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.ui.order import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import com.example.lunchtray.R import com.example.lunchtray.databinding.FragmentCheckoutBinding import com.example.lunchtray.model.OrderViewModel import com.google.android.material.snackbar.Snackbar /** * [CheckoutFragment] allows people to apply a coupon to their order, submit order, or cancel order. */ class CheckoutFragment : Fragment() { // Binding object instance corresponding to the fragment_start_order.xml layout // This property is non-null between the onCreateView() and onDestroyView() lifecycle callbacks, // when the view hierarchy is attached to the fragment. private var _binding: FragmentCheckoutBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! // Use the 'by activityViewModels()' Kotlin property delegate from the fragment-ktx artifact private val sharedViewModel: OrderViewModel by activityViewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentCheckoutBinding.inflate(inflater, container, false) val root = binding.root // Calculate tax and total upon creating the CheckoutFragment view sharedViewModel.calculateTaxAndTotal() return root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { lifecycleOwner = viewLifecycleOwner // TODO: initialize the OrderViewModel and CheckoutFragment variables } } /** * Cancel the order and start over. */ fun cancelOrder() { // TODO: Reset order in view model // TODO: Navigate back to the [StartFragment] to start over } /** * Submit order and navigate to home screen. */ fun submitOrder() { // Show snackbar to "confirm" order Snackbar.make(binding.root, R.string.submit_order, Snackbar.LENGTH_SHORT).show() // TODO: Reset order in view model // TODO: Navigate back to the [StartFragment] to start over } /** * This fragment lifecycle method is called when the view hierarchy associated with the fragment * is being removed. As a result, clear out the binding object. */ override fun onDestroyView() { super.onDestroyView() _binding = null } }
apache-2.0
f8533250371c2b89e27dd08c70b8ef48
35.147368
100
0.708794
4.776078
false
false
false
false
GunoH/intellij-community
plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigUnexpectedCommaInspection.kt
2
2238
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.codeinsight.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.editorconfig.language.codeinsight.quickfixes.EditorConfigCleanupValueListQuickFix import org.editorconfig.language.messages.EditorConfigBundle import org.editorconfig.language.psi.EditorConfigElementTypes import org.editorconfig.language.psi.EditorConfigOptionValueList import org.editorconfig.language.psi.EditorConfigVisitor import org.editorconfig.language.util.EditorConfigPsiTreeUtil class EditorConfigUnexpectedCommaInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() { override fun visitOptionValueList(list: EditorConfigOptionValueList) { val badCommas = findBadCommas(list) val message by lazy { EditorConfigBundle["inspection.value.list.comma.unexpected.message"] } val quickFix by lazy { EditorConfigCleanupValueListQuickFix() } badCommas.forEach { holder.registerProblem(it, message, quickFix) } } } companion object { fun findBadCommas(list: EditorConfigOptionValueList): List<PsiElement> { val ranges = list.optionValueIdentifierList .asSequence() .zipWithNext() .map { (previous, current) -> TextRange(previous.textRange.endOffset, current.textRange.startOffset) } .toMutableList() val commas = findCommas(list) return commas.filter { comma -> val range = ranges.firstOrNull { it.contains(comma.textOffset) } ?: return@filter true ranges.remove(range) false } } private fun findCommas(list: EditorConfigOptionValueList): List<PsiElement> { val result = mutableListOf<PsiElement>() EditorConfigPsiTreeUtil.iterateVisibleChildren(list) { if (it.node.elementType == EditorConfigElementTypes.COMMA) { result.add(it) } } return result } } }
apache-2.0
f2e9aed9c826e8f39730ad910a3ae3fb
41.226415
140
0.752011
4.844156
false
true
false
false
CzBiX/v2ex-android
app/src/main/kotlin/com/czbix/v2ex/helper/JsoupObjects.kt
1
3825
package com.czbix.v2ex.helper import android.util.LruCache import com.google.common.graph.Traverser import org.jsoup.nodes.Element import org.jsoup.select.Evaluator import org.jsoup.select.QueryParser /** * Jsoup use bottom-up parsing to find element, it's slow when we only used a few elements. * This class provided a more direct way to find elements. */ class JsoupObjects(vararg elements: Element) : Iterable<Element> { private var mResult: Sequence<Element> init { mResult = elements.asSequence() } private fun addOneQuery(evaluator: Evaluator, getElement: (Element) -> Element?) { mResult = mResult.mapNotNull { ele -> getElement(ele)?.let { if (evaluator(it)) it else null } } } private fun addQuery(evaluator: Evaluator, getElements: (Element) -> Sequence<Element>) { mResult = mResult.flatMap { ele -> getElements(ele).filter { e -> evaluator(e) } } } fun exclude(query: String): JsoupObjects { val evaluator = parseQuery(query) mResult = mResult.filterNot { evaluator(it) } return this } infix fun child(query: String): JsoupObjects { val evaluator = parseQuery(query) addQuery(evaluator) { it.children().asSequence() } return this } fun child(vararg queries: String): JsoupObjects { return queries.fold(this) { thiz, query -> thiz.child(query) } } /** * find elements by pre-order depth-first-search * @see .bfs */ infix fun dfs(query: String): JsoupObjects { val evaluator = parseQuery(query) addQuery(evaluator) { TREE_TRAVERSER.depthFirstPreOrder(it).asSequence() } return this } fun head(): JsoupObjects = bfs("head") fun body(): JsoupObjects = bfs("body") /** * find elements by breadth-first-search * @see .dfs */ infix fun bfs(query: String): JsoupObjects { val evaluator = parseQuery(query) addQuery(evaluator) { TREE_TRAVERSER.breadthFirst(it).asSequence() } return this } infix fun parents(query: String): JsoupObjects { val evaluator = parseQuery(query) addQuery(evaluator) { PARENT_TRAVERSER.breadthFirst(it).asSequence() } return this } infix fun adjacent(query: String): JsoupObjects { val evaluator = parseQuery(query) addOneQuery(evaluator, Element::nextElementSibling) return this } override fun iterator(): Iterator<Element> = mResult.iterator() private operator fun Evaluator.invoke(e: Element) = this.matches(e, e) companion object { private val EVALUATOR_LRU_CACHE: LruCache<String, Evaluator> init { EVALUATOR_LRU_CACHE = object : LruCache<String, Evaluator>(64) { override fun create(key: String): Evaluator { return QueryParser.parse(key) } } } @JvmStatic fun Element.query(): JsoupObjects { return JsoupObjects(this) } @JvmStatic fun child(ele: Element, query: String): Element { return JsoupObjects(ele).child(query).first() } @JvmStatic fun parents(ele: Element, query: String): Element { return JsoupObjects(ele).parents(query).first() } private fun parseQuery(query: String) = EVALUATOR_LRU_CACHE.get(query) private val TREE_TRAVERSER = Traverser.forTree<Element> { it.children() } private val PARENT_TRAVERSER = Traverser.forTree<Element> { listOf(it.parent()) } } }
apache-2.0
1cf577fd024d8a3da8efa58ec9da89d5
26.52518
93
0.593203
4.401611
false
false
false
false
jk1/Intellij-idea-mail
src/main/kotlin/github/jk1/smtpidea/server/smtp/MailSession.kt
1
2267
package github.jk1.smtpidea.server.smtp import org.subethamail.smtp.MessageHandler import java.util.Date import java.util.ArrayList import org.subethamail.smtp.MessageContext import javax.mail.internet.MimeMessage import java.io.InputStream import javax.mail.Session import java.util.Properties import github.jk1.smtpidea.store.OutboxFolder import java.io.ByteArrayOutputStream import javax.mail.Message import javax.mail.Multipart /** * */ public class MailSession(val context: MessageContext?) : MessageHandler{ public var receivedDate: Date? = null public var envelopeFrom: String? = null public var envelopeRecipients: ArrayList<String> = ArrayList<String>() public var message: MimeMessage? = null public val ip: String = context?.getRemoteAddress().toString() override fun from(from: String?) { envelopeFrom = from } override fun recipient(recipient: String?) { envelopeRecipients.add(recipient as String) } override fun data(data: InputStream?) { message = MimeMessage(Session.getInstance(Properties()), data) } override fun done() { receivedDate = Date() OutboxFolder.add(this) } public fun getRawMessage(): String { val stream = ByteArrayOutputStream() message?.writeTo(stream) return String(stream.toByteArray()) } public fun getFormattedMessage(): String { val builder = StringBuilder() handleMessage(message, builder) return builder.toString() } public fun handleMessage(message: Message?, builder: StringBuilder) { val content = message?.getContent() when (content) { is Multipart -> handleMultipart(content, builder) else -> builder.append(content) } } public fun handleMultipart(mp: Multipart, builder: StringBuilder) { for (i in 0..mp.getCount() - 1) { val bodyPart = mp.getBodyPart(i) val content = bodyPart?.getContent() when (content) { is Multipart -> handleMultipart(content, builder) is InputStream -> builder.append("\n").append("[Binary data]").append("\n") else -> builder.append(content) } } } }
gpl-2.0
6abc18da44d94beec4c53134e6e90263
29.226667
91
0.659021
4.579798
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/buildsystem/BuildSystem.kt
1
3486
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.buildsystem import com.demonwav.mcdev.platform.ProjectConfiguration import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile /** * Base class for build system project creation. */ abstract class BuildSystem { val dependencies = mutableListOf<BuildDependency>() val repositories = mutableListOf<BuildRepository>() lateinit var artifactId: String lateinit var groupId: String lateinit var version: String lateinit var rootDirectory: VirtualFile lateinit var sourceDirectory: VirtualFile lateinit var resourceDirectory: VirtualFile lateinit var testSourceDirectory: VirtualFile lateinit var testResourceDirectory: VirtualFile /** * This refers to the plugin name from the perspective of the build system, that being a name field in the build * system's configuration. This is not the actual plugin name, which would be stated in the plugin's description * file, or the main class file, depending on the project. */ lateinit var pluginName: String lateinit var buildVersion: String /** * Assuming the artifact ID, group ID, and version are set, along with whatever dependencies and repositories and * the root directory, create a base module consisting of the necessary build system configuration files and * directory structure. This method does not create any classes or project-specific things, nor does it set up * any build configurations or enable the plugin for this build config. This will be done in * [finishSetup]. * * * It is legal for this method to have different default setups for each platform type, so the PlatformType and * ProjectConfiguration are provided here as well. * @param project The project * @param configuration The configuration object for the project * @param indicator The progress indicator */ abstract fun create(project: Project, configuration: ProjectConfiguration, indicator: ProgressIndicator) /** * This is called after [create], and after the module has set * itself up. This is when the build system should make whatever calls are necessary to enable the build system's * plugin, and setup whatever run configs should be setup for this build system. * * * It is legal for this method to have different default setups for each platform type, so the PlatformType and * ProjectConfiguration are provided here as well. * @param rootModule the root module * @param configurations The configuration object for the project * @param indicator The progress indicator */ abstract fun finishSetup(rootModule: Module, configurations: Collection<ProjectConfiguration>, indicator: ProgressIndicator) fun createDirectories(dir: VirtualFile = rootDirectory) { sourceDirectory = VfsUtil.createDirectories(dir.path + "/src/main/java") resourceDirectory = VfsUtil.createDirectories(dir.path + "/src/main/resources") testSourceDirectory = VfsUtil.createDirectories(dir.path + "/src/test/java") testResourceDirectory = VfsUtil.createDirectories(dir.path + "/src/test/resources") } }
mit
bd0ca7b2ce9583e39e41c78a4c38d3df
39.534884
128
0.740964
5.044863
false
true
false
false
programmerr47/ganalytics
sample/src/main/java/com/github/programmerr47/ganalyticssample/GanalyticsActivity.kt
1
2273
package com.github.programmerr47.ganalyticssample import android.support.v7.app.AppCompatActivity import android.os.Bundle import com.github.programmerr47.ganalytics.core.* import kotlinx.android.synthetic.main.activity_ganalytics.* class GanalyticsActivity : AppCompatActivity() { private val placeholderStr: String by lazy { getString(R.string.no) } private val ganalytics: AnalyticsGroupWrapper by lazy { initGanalytics() } private val analytics: Analytics by lazy { ganalytics.create(Analytics::class) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_ganalytics) placeholderStr.let { Event(it, it, it) }.printOnScreen() b_car_price.setOnClickListener { analytics.car.price(Price(200, "dollars")) } b_car_sold.setOnClickListener { analytics.car.isSold() } b_car_type.setOnClickListener { analytics.car.type(CarType.CROSSOVER) } b_customer_buy.setOnClickListener { analytics.customer.buyCar(Car(CarType.SEDAN, Price(300, "euro"))) } b_customer_start.setOnClickListener { analytics.customer.startedSearching() } b_customer_end.setOnClickListener { analytics.customer.endedSearching() } b_seller_add.setOnClickListener { analytics.seller.addNewCarToSellList(Car(CarType.HATCHBACK, Price(256, "pounds"))) } b_seller_fair.setOnClickListener { analytics.seller.isFair() } b_seller_sell.setOnClickListener { analytics.seller.sellCar(Car(CarType.SUV, Price(500, "rubles"))) } } private fun initGanalytics() = Ganalytics({ it.printOnScreen() }) { prefixSplitter = "_" namingConvention = NamingConventions.LOWER_SNAKE_CASE labelTypeConverters += TypeConverterPair<Price> { it.userFriendlyStr() } + TypeConverterPair<Car> { it.run { "t: ${type.name.toLowerCase()}, p: ${price.userFriendlyStr()}" } } } private fun Price.userFriendlyStr() = "$amount $currency" private fun Event.printOnScreen() { tv_category.text = getString(R.string.category, category) tv_action.text = getString(R.string.action, action) tv_label.text = getString(R.string.label, if (label == "") placeholderStr else label) } }
mit
73e5de822bc047c7ac4c81919c3cf2d7
47.361702
126
0.711835
3.987719
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/page/LinkMovementMethodExt.kt
1
2090
package org.wikipedia.page import android.text.Spannable import android.text.method.LinkMovementMethod import android.text.style.URLSpan import android.view.MotionEvent import android.widget.TextView import org.wikipedia.util.UriUtil import org.wikipedia.util.log.L class LinkMovementMethodExt : LinkMovementMethod { fun interface UrlHandler { fun onUrlClick(url: String) } fun interface UrlHandlerWithText { fun onUrlClick(url: String, titleString: String?, linkText: String) } private var handler: UrlHandler? = null private var handlerWithText: UrlHandlerWithText? = null constructor(handler: UrlHandler?) { this.handler = handler } constructor(handler: UrlHandlerWithText?) { handlerWithText = handler } override fun onTouchEvent(widget: TextView, buffer: Spannable, event: MotionEvent): Boolean { val action = event.action if (action == MotionEvent.ACTION_UP) { val x = event.x.toInt() - widget.totalPaddingLeft + widget.scrollX val y = event.y.toInt() - widget.totalPaddingTop + widget.scrollY val layout = widget.layout val line = layout.getLineForVertical(y) val off = layout.getOffsetForHorizontal(line, x.toFloat()) val links = buffer.getSpans(off, off, URLSpan::class.java) if (links.isNotEmpty()) { val linkText = try { buffer.subSequence(buffer.getSpanStart(links[0]), buffer.getSpanEnd(links[0])).toString() } catch (e: Exception) { e.printStackTrace() "" } L.d(linkText) val url = UriUtil.decodeURL(links[0].url) handler?.run { onUrlClick(url) } handlerWithText?.run { onUrlClick(url, UriUtil.getTitleFromUrl(url), linkText) } return true } } return super.onTouchEvent(widget, buffer, event) } }
apache-2.0
85213d781b04f151bf39c6af15ca0b62
31.65625
109
0.601435
4.728507
false
false
false
false
openium/auvergne-webcams-droid
app/src/main/java/fr/openium/auvergnewebcams/service/DownloadWorker.kt
1
6294
package fr.openium.auvergnewebcams.service import android.content.ContentValues import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Build import android.os.Environment import android.os.SystemClock import android.provider.MediaStore import androidx.core.net.toUri import androidx.work.Worker import androidx.work.WorkerParameters import fr.openium.auvergnewebcams.R import fr.openium.auvergnewebcams.broadcast.AppNotifier import fr.openium.auvergnewebcams.utils.PreferencesUtils import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.android.closestKodein import org.kodein.di.generic.instance import timber.log.Timber import java.io.File import java.io.FileOutputStream import java.io.OutputStream import java.net.URL class DownloadWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams), KodeinAware { private var mUrl: String? = null private var mFileName: String = "" private var webcamName: String = "" private var mIsPhoto: Boolean = true private var mUri: Uri? = null override val kodein: Kodein by closestKodein(applicationContext) private val preferencesUtils: PreferencesUtils by instance() override fun doWork(): Result { mUrl = inputData.getString(KEY_PATH_URL) mIsPhoto = inputData.getBoolean(KEY_IS_PHOTO, true) mFileName = inputData.getString(KEY_FILENAME) ?: "" webcamName = mFileName.split("_").first().replace("\n", " - ") return downloadFile() } private fun downloadFile(): Result { val notifBaseId = preferencesUtils.newNotifId Timber.d("[Worker] Start download notification n°$notifBaseId") var result = Result.success() if (!mUrl.isNullOrEmpty()) { val oS = getOutputStream() val connection = URL(mUrl).openConnection() connection.connect() val contentLength = connection.contentLength if (contentLength > 0) { try { val iS = connection.getInputStream() val buffer = ByteArray(contentLength) var total = 0 var currentProgress = 0 var count = iS.read(buffer) while (count != -1) { total += count val progress = (total * 100) / contentLength if (currentProgress != progress) { Timber.d("[Worker] Downloading $currentProgress%") AppNotifier.SaveWebcamAction.downloadingFile(applicationContext, webcamName, notifBaseId, progress) currentProgress = progress } oS.write(buffer, 0, count) count = iS.read(buffer) } // Create the bitmap var bitmap: Bitmap? = null if (mIsPhoto && mUri != null) { applicationContext.contentResolver.openInputStream(mUri!!)?.let { bitmap = BitmapFactory.decodeStream(it) it.close() } } oS.flush() oS.close() iS.close() SystemClock.sleep(100) Timber.d("[Worker] Finish download notification n°$notifBaseId with SUCCESS") AppNotifier.SaveWebcamAction.downloadSuccess( applicationContext, webcamName, notifBaseId, bitmap, mUri ) } catch (e: Exception) { Timber.e(e) Timber.d("[Worker] Finish download notification n°$notifBaseId with ERROR") AppNotifier.SaveWebcamAction.downloadError(applicationContext, webcamName, notifBaseId) result = Result.failure() } } } else { AppNotifier.SaveWebcamAction.downloadError(applicationContext, webcamName, notifBaseId) result = Result.failure() } return result } private fun getOutputStream(): OutputStream { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { getOutPutStreamForApiAboveQ() ?: getOutputStreamForApiUnderQ() } else { getOutputStreamForApiUnderQ() } } private fun getOutPutStreamForApiAboveQ(): OutputStream? { val relativePath = if (mIsPhoto) { Environment.DIRECTORY_PICTURES } else { Environment.DIRECTORY_MOVIES } + File.separator + applicationContext.getString(R.string.app_name) val resolver = applicationContext.contentResolver val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, mFileName) put(MediaStore.MediaColumns.MIME_TYPE, if (mIsPhoto) "image/*" else "video/*") put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath) } val baseUri = if (mIsPhoto) { MediaStore.Images.Media.EXTERNAL_CONTENT_URI } else { MediaStore.Video.Media.EXTERNAL_CONTENT_URI } return resolver.insert(baseUri, contentValues)?.let { mUri = it resolver.openOutputStream(it) } } private fun getOutputStreamForApiUnderQ(): FileOutputStream { val directory = if (mIsPhoto) { Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) } else { Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) } directory.mkdirs() val file = File(directory, mFileName) mUri = file.toUri() return FileOutputStream(file) } companion object { const val KEY_PATH_URL = "KEY_PATH_URL" const val KEY_IS_PHOTO = "KEY_IS_PHOTO" const val KEY_FILENAME = "KEY_FILENAME" } }
mit
12133c1452ca46ff77a59dc5b784e3b4
33.955556
127
0.588937
5.182043
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/settings/DatePreferenceDialogFragmentCompat.kt
1
2155
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.features.settings import android.app.DatePickerDialog import android.app.Dialog import android.os.Bundle import androidx.fragment.app.DialogFragment import androidx.preference.DialogPreference import androidx.preference.Preference import androidx.preference.PreferenceDialogFragmentCompat import android.widget.DatePicker import org.threeten.bp.LocalDate class DatePreferenceDialogFragmentCompat : PreferenceDialogFragmentCompat(), DialogPreference.TargetFragment, DatePickerDialog.OnDateSetListener { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val pref = preference as DatePreference return DatePickerDialog( context!!, this, pref.date.year, pref.date.monthValue - 1, pref.date.dayOfMonth ) } override fun onDialogClosed(b: Boolean) { } override fun findPreference(charSequence: CharSequence): Preference { return preference } override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) { val pref = preference as DatePreference pref.date = LocalDate.of(year, monthOfYear + 1, dayOfMonth) if (pref.callChangeListener(pref.date)) { pref.persistDateValue(pref.date) } } companion object { fun newInstance(key: String): DialogFragment { val dialogFragment = DatePreferenceDialogFragmentCompat() val bundle = Bundle(1) bundle.putString("key", key) dialogFragment.arguments = bundle return dialogFragment } } }
gpl-2.0
c87e79ef4d53a220ef3eb0c1338dc1ac
31.164179
92
0.709049
5.046838
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/web/vo/platform/users/AvatarVo.kt
1
241
package top.zbeboy.isy.web.vo.platform.users /** * Created by zbeboy 2017-11-19 . **/ open class AvatarVo { var x: Int? = null var y: Int? = null var height: Int? = null var width: Int? = null var rotate: Int? = null }
mit
db149c27459cec141bc6d02c74bb1b57
19.166667
44
0.605809
3.089744
false
false
false
false
paplorinc/intellij-community
plugins/editorconfig/src/org/editorconfig/language/codeinsight/quickfixes/EditorConfigMergeSectionsQuickFix.kt
4
1976
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.codeinsight.quickfixes import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.intellij.psi.codeStyle.CodeStyleManager import org.editorconfig.language.codeinsight.inspections.EditorConfigHeaderUniquenessInspection.Companion.findDuplicateSection import org.editorconfig.language.messages.EditorConfigBundle import org.editorconfig.language.psi.EditorConfigHeader import org.editorconfig.language.psi.EditorConfigSection import org.editorconfig.language.services.EditorConfigElementFactory class EditorConfigMergeSectionsQuickFix : LocalQuickFix { override fun getFamilyName() = EditorConfigBundle["quickfix.section.merge-duplicate.description"] override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val header = descriptor.psiElement as? EditorConfigHeader ?: return val duplicateSection = findDuplicateSection(header.section) ?: return val elementFactory = EditorConfigElementFactory.getInstance(project) val replacementText = createReplacementText(header.section, duplicateSection) val replacement = elementFactory.createSection(replacementText) val manager = CodeStyleManager.getInstance(project) ?: return manager.performActionWithFormatterDisabled { duplicateSection.replace(replacement) header.section.delete() } } private fun createReplacementText(source: EditorConfigSection, destination: EditorConfigSection): String { val result = StringBuilder(destination.textLength + source.textLength) result.append(destination.text) for (child in source.children) { if (child is EditorConfigHeader) continue result.append('\n') result.append(child.text) } return result.toString() } }
apache-2.0
0f1e8bb0bcedd06b11ba9fe5408efad6
46.047619
140
0.808198
5.132468
false
true
false
false
esafirm/android-playground
app/src/main/java/com/esafirm/androidplayground/androidarch/room/RoomGettingStartedController.kt
1
3498
package com.esafirm.androidplayground.androidarch.room import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import com.esafirm.androidplayground.androidarch.room.database.AppDatabase import com.esafirm.androidplayground.androidarch.room.database.User import com.esafirm.androidplayground.common.BaseController import com.esafirm.androidplayground.libs.Logger import com.esafirm.androidplayground.utils.button import com.esafirm.androidplayground.utils.column import com.esafirm.androidplayground.utils.logger import com.esafirm.androidplayground.utils.matchParent import com.esafirm.androidplayground.utils.row import io.reactivex.Completable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers class RoomGettingStartedController : BaseController() { private val database: AppDatabase by lazy { AppDatabase.get(requiredContext) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { return row { addView(column { button("Insert") { inserUsers().subscribeOn(Schedulers.io()).subscribe() } button("Read") { getUsersWithAge().subscribeOn(Schedulers.io()).subscribe() } button("Delete") { deleteOldestUser().subscribeOn(Schedulers.io()).subscribe() } button("Update") { update().subscribeOn(Schedulers.io()).subscribe() } }.also { matchParent(horizontal = true, vertical = false) }) logger() } } override fun onAttach(view: View) { super.onAttach(view) init() } @SuppressLint("CheckResult") private fun init() { inserUsers() .subscribeOn(Schedulers.io()) .andThen(getUsers()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { users, error -> Logger.log("Getting all users: ${users.size}") } } private fun buttonOf(container: View, resId: Int): Button = container.findViewById(resId) private fun getUsers(): Single<List<User>> = Single.fromCallable { database.userDao().getUsers() } private fun update(): Completable = Completable.fromAction { val userDao = database.userDao() val nika = userDao.getUserWithAge(18).firstOrNull() if (nika != null) { userDao.insertUser(nika.copy(age = 22)) } Logger.log("Changing nika age to 22") } private fun getUsersWithAge(): Completable = Completable.fromAction { val users = database.userDao().getUserWithAge(18) Logger.log("There are ${users.size} users with age 18") } private fun deleteOldestUser(): Completable = Completable.fromAction { val userDao = database.userDao() val nara = userDao.getUserWithAge(17).firstOrNull() nara?.let { userDao.deleteUsers(it) } } private fun inserUsers(): Completable = Completable.fromAction { Logger.log("Adding users to database") listOf( User(name = "Nara", age = 17), User(name = "Nika", age = 18), User(name = "Nana", age = 19) ).forEach { database.userDao().insertUser(it) } } }
mit
4671c0a4935e65ace759b7d604f75cce
34.693878
93
0.642367
4.739837
false
false
false
false
google/intellij-community
java/compiler/tests/com/intellij/compiler/artifacts/propertybased/ArtifactsPropertyTest.kt
1
42786
// 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.compiler.artifacts.propertybased import com.intellij.openapi.Disposable import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.packaging.artifacts.* import com.intellij.packaging.elements.* import com.intellij.packaging.impl.artifacts.PlainArtifactType import com.intellij.packaging.impl.artifacts.workspacemodel.ArtifactBridge import com.intellij.packaging.impl.artifacts.workspacemodel.ArtifactManagerBridge.Companion.artifactsMap import com.intellij.packaging.impl.artifacts.workspacemodel.forThisAndFullTree import com.intellij.packaging.impl.elements.ArtifactRootElementImpl import com.intellij.packaging.impl.elements.DirectoryPackagingElement import com.intellij.packaging.impl.elements.FileCopyPackagingElement import com.intellij.packaging.ui.ArtifactEditorContext import com.intellij.packaging.ui.PackagingElementPresentation import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.UsefulTestCase.assertNotEmpty import com.intellij.testFramework.rules.ProjectModelRule import com.intellij.util.ui.EmptyIcon import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.addArtifactEntity import com.intellij.workspaceModel.storage.bridgeEntities.addArtifactRootElementEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ArtifactEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.CompositePackagingElementEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.PackagingElementEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageImpl import org.jetbrains.jetCheck.Generator import org.jetbrains.jetCheck.ImperativeCommand import org.jetbrains.jetCheck.PropertyChecker import org.junit.Assert.* import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.util.function.Supplier import javax.swing.Icon class ArtifactsPropertyTest { companion object { @ClassRule @JvmField val application = ApplicationRule() private const val MAX_ARTIFACT_NUMBER = 50 } @Rule @JvmField val projectModel = ProjectModelRule() @Rule @JvmField val disposableRule = DisposableRule() // This is a code generator for failed tests. // At the moment it's incomplete and should be updated if some execution paths are missing lateinit var codeMaker: CodeMaker @Test fun `property test`() { val writeDisposable = writeActionDisposable(disposableRule.disposable) invokeAndWaitIfNeeded { PackagingElementType.EP_NAME.point.registerExtension(MyWorkspacePackagingElementType, writeDisposable) PackagingElementType.EP_NAME.point.registerExtension(MyCompositeWorkspacePackagingElementType, writeDisposable) customArtifactTypes.forEach { ArtifactType.EP_NAME.point.registerExtension(it, writeDisposable) } } PropertyChecker.checkScenarios { codeMaker = CodeMaker() ImperativeCommand { try { it.executeCommands(Generator.sampledFrom( RenameArtifact(), AddArtifact(), RemoveArtifact(), ChangeBuildOnMake(), ChangeArtifactType(), AddPackagingElementTree(), GetPackagingElement(), FindCompositeChild(), RemoveAllChildren(), GetAllArtifacts(), GetSortedArtifacts(), GetAllArtifactsIncludingInvalid(), FindByNameExisting(), FindByNameNonExisting(), FindByType(), CreateViaWorkspaceModel(), RenameViaWorkspaceModel(), ChangeOnBuildViaWorkspaceModel(), ChangeArtifactTypeViaWorkspaceModel(), RemoveViaWorkspaceModel(), )) } finally { codeMaker.finish() makeChecksHappy { val artifacts = ArtifactManager.getInstance(projectModel.project).artifacts val modifiableModel = ArtifactManager.getInstance(projectModel.project).createModifiableModel() artifacts.forEach { modifiableModel.removeArtifact(it) } modifiableModel.commit() WorkspaceModel.getInstance(projectModel.project).updateProjectModel { it.replaceBySource({ true }, MutableEntityStorage.create()) } } it.logMessage("------- Code -------") it.logMessage(codeMaker.get()) } } } } inner class GetPackagingElement : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val artifactBridge = selectArtifactBridge(env, "get packaging element") ?: return makeChecksHappy { val modifiableModel = ArtifactManager.getInstance(projectModel.project).createModifiableModel() val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifactBridge) val (parent, child) = chooseSomeElementFromTree(env, modifiableArtifact) if (parent == null) { modifiableModel.dispose() return@makeChecksHappy } val newChild = parent.addOrFindChild(child) checkResult(env) { assertSame(child, newChild) } modifiableModel.commit() } } } inner class FindCompositeChild : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val artifactBridge = selectArtifactBridge(env, "get packaging element") ?: return makeChecksHappy { val modifiableModel = ArtifactManager.getInstance(projectModel.project).createModifiableModel() val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifactBridge) val (parent, child) = chooseSomeElementFromTree(env, modifiableArtifact) if (parent == null || child !is CompositePackagingElement<*>) { modifiableModel.dispose() return@makeChecksHappy } val names = parent.children.filterIsInstance<CompositePackagingElement<*>>().map { it.name } if (names.size != names.toSet().size) { modifiableModel.dispose() return@makeChecksHappy } val newChild = parent.findCompositeChild(child.name) checkResult(env) { assertSame(child, newChild) } modifiableModel.commit() } } } inner class RemoveAllChildren : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val artifactBridge = selectArtifactBridge(env, "get packaging element") ?: return val (rootElement, removedChild, parent) = makeChecksHappy { val modifiableModel = ArtifactManager.getInstance(projectModel.project).createModifiableModel() val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifactBridge) val modifiableModelVal = codeMaker.makeVal("modifiableModel", "ArtifactManager.getInstance(project).createModifiableModel()") val modifiableArtifactVal = codeMaker.makeVal("modifiableArtifact", "${modifiableModelVal}.getOrCreateModifiableArtifact(${ codeMaker.v("chosenArtifact") })") val (parent, child) = chooseSomeElementFromTree(env, modifiableArtifact) if (parent == null) { modifiableModel.dispose() return@makeChecksHappy null } parent.removeAllChildren() env.logMessage("Removing some package element for ${artifactBridge.name}") codeMaker.addLine("${codeMaker.v("chosenParent")}.removeAllChildren()") // It's important to get root element // Otherwise diff will be injected into the root element val rootElement = modifiableArtifact.rootElement modifiableModel.commit() val rootElementVal = codeMaker.makeVal("rootElement", "$modifiableArtifactVal.rootElement") codeMaker.addLine("$modifiableModelVal.commit()") codeMaker.addLine("return@runWriteAction Triple($rootElementVal, ${codeMaker.v("chosenChild")}, ${codeMaker.v("chosenParent")})") Triple(rootElement, child, parent) } ?: return checkResult(env) { val manager = ArtifactManager.getInstance(projectModel.project) val foundArtifact = runReadAction { manager.findArtifact(artifactBridge.name) }!! val managerVal = codeMaker.makeVal("manager", "ArtifactManager.getInstance(project)") val foundArtifactVal = codeMaker.makeVal("foundArtifact", "$managerVal.findArtifact(${codeMaker.v("chosenArtifact")}.name)!!") val artifactEntity = WorkspaceModel.getInstance(projectModel.project).entityStorage.current .entities(ArtifactEntity::class.java).find { it.name == artifactBridge.name }!! assertElementsEquals(rootElement, foundArtifact.rootElement) assertTreesEquals(projectModel.project, foundArtifact.rootElement, artifactEntity.rootElement!!) codeMaker.scope("$foundArtifactVal.rootElement.forThisAndFullTree") { codeMaker.scope("if (it === ${codeMaker.v("happyResult")}.third)") { codeMaker.addLine("assertTrue(it.children.none { it.isEqualTo(${codeMaker.v("happyResult")}.second) })") } } foundArtifact.rootElement.forThisAndFullTree { if (it === parent) { assertTrue(it.children.none { it.isEqualTo(removedChild) }) } } } } } inner class AddPackagingElementTree : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val (selectedArtifact, manager) = selectArtifactViaBridge(env, "adding package element") ?: return env.logMessage("Add new packaging elements tree to: ${selectedArtifact.name}") val rootElement = makeChecksHappy { val modifiableModel = manager.createModifiableModel() val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(selectedArtifact) val (parent, _) = chooseSomeElementFromTree(env, modifiableArtifact) val newTree = makeElementsTree(env).first parent?.let { addChildSomehow(env, it, newTree) } // It's important to get root element // Otherwise diff will be injected into the root element val rootElement = modifiableArtifact.rootElement modifiableModel.commit() rootElement } checkResult(env) { val foundArtifact = runReadAction { manager.findArtifact(selectedArtifact.name) }!! val artifactEntity = WorkspaceModel.getInstance(projectModel.project).entityStorage.current .entities(ArtifactEntity::class.java).find { it.name == selectedArtifact.name }!! assertElementsEquals(rootElement, foundArtifact.rootElement) assertTreesEquals(projectModel.project, foundArtifact.rootElement, artifactEntity.rootElement!!) } } private fun addChildSomehow(env: ImperativeCommand.Environment, parent: CompositePackagingElement<*>, newTree: PackagingElement<*>) { when (env.generateValue(Generator.integers(0, 1), null)) { 0 -> parent.addOrFindChild(newTree) 1 -> parent.addFirstChild(newTree) else -> error("Unexpected") } } } inner class CreateViaWorkspaceModel : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val workspaceModel = WorkspaceModel.getInstance(projectModel.project) val artifactName = selectArtifactName( env, workspaceModel.entityStorage .current .entities(ArtifactEntity::class.java) .map { it.name } .toList() ) ?: run { env.logMessage("Cannot select name for new artifact via workspace model") return } makeChecksHappy { workspaceModel.updateProjectModel { val rootElement = createCompositeElementEntity(env, it) val (_, id, _) = selectArtifactType(env) it.addArtifactEntity(artifactName, id, true, null, rootElement, TestEntitySource) } } env.logMessage("Add artifact via model: $artifactName") checkResult(env) { val foundArtifact = runReadAction { ArtifactManager.getInstance(projectModel.project).findArtifact(artifactName) } assertNotNull(foundArtifact) } } } inner class RenameViaWorkspaceModel : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val workspaceModel = WorkspaceModel.getInstance(projectModel.project) val artifactName = selectArtifactName( env, workspaceModel.entityStorage .current .entities(ArtifactEntity::class.java) .map { it.name } .toList() ) ?: run { env.logMessage("Cannot select name for new artifact via workspace model") return } val selectedArtifact = selectArtifactViaModel(env, workspaceModel, "renaming") ?: return env.logMessage("Rename artifact via workspace model: ${selectedArtifact.name} -> $artifactName") makeChecksHappy { workspaceModel.updateProjectModel { it.modifyEntity(selectedArtifact) { this.name = artifactName } } } checkResult(env) { val entities = workspaceModel.entityStorage.current.entities(ArtifactEntity::class.java) assertTrue(entities.none { it.name == selectedArtifact.name }) assertTrue(entities.any { it.name == artifactName }) onManager(env) { manager -> val allArtifacts = runReadAction{ manager.artifacts } assertTrue(allArtifacts.none { it.name == selectedArtifact.name }) assertTrue(allArtifacts.any { it.name == artifactName }) } } } } inner class ChangeOnBuildViaWorkspaceModel : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val workspaceModel = WorkspaceModel.getInstance(projectModel.project) val selectedArtifact = selectArtifactViaModel(env, workspaceModel, "changing option") ?: return env.logMessage("Change build on make option for ${selectedArtifact.name}: Prev value: ${selectedArtifact.includeInProjectBuild}") makeChecksHappy { workspaceModel.updateProjectModel { it.modifyEntity(selectedArtifact) { this.includeInProjectBuild = !this.includeInProjectBuild } } } checkResult(env) { val artifactEntity = workspaceModel.entityStorage.current.resolve(selectedArtifact.persistentId)!! assertEquals(!selectedArtifact.includeInProjectBuild, artifactEntity.includeInProjectBuild) onManager(env) { manager -> val artifact = runReadAction { manager.findArtifact(selectedArtifact.name) }!! assertEquals(!selectedArtifact.includeInProjectBuild, artifact.isBuildOnMake) } } } } inner class ChangeArtifactTypeViaWorkspaceModel : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val workspaceModel = WorkspaceModel.getInstance(projectModel.project) val selectedArtifact = selectArtifactViaModel(env, workspaceModel, "changing artifact type") ?: return val (_, id, _) = selectArtifactType(env) env.logMessage("Change artifact type for ${selectedArtifact.name}: Prev value: ${selectedArtifact.artifactType}") makeChecksHappy { workspaceModel.updateProjectModel { it.modifyEntity(selectedArtifact) { this.artifactType = id } } } checkResult(env) { val artifactEntity = artifactEntity(projectModel.project, selectedArtifact.name) assertEquals(id, artifactEntity.artifactType) onManager(env) { manager -> val artifact = runReadAction { manager.findArtifact(selectedArtifact.name)!! } assertEquals(id, artifact.artifactType.id) } } } } inner class RemoveViaWorkspaceModel : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val workspaceModel = WorkspaceModel.getInstance(projectModel.project) val selectedArtifact = selectArtifactViaModel(env, workspaceModel, "removing") ?: return env.logMessage("Remove artifact: ${selectedArtifact.name}") makeChecksHappy { workspaceModel.updateProjectModel { it.removeEntity(selectedArtifact) } } checkResult(env) { val entities = workspaceModel.entityStorage.current.entities(ArtifactEntity::class.java) assertTrue(entities.none { it.name == selectedArtifact.name }) onManager(env) { manager -> val allArtifacts = runReadAction { manager.artifacts } assertTrue(allArtifacts.none { it.name == selectedArtifact.name }) } } } } inner class FindByType : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val (selectedArtifact, _) = selectArtifactViaBridge(env, "finding by type") ?: return val searchType = selectedArtifact.artifactType.id env.logMessage("Search for artifact by type: $searchType") onManager(env) { manager -> assertNotEmpty(runReadAction { manager.getArtifactsByType(ArtifactType.findById(searchType)!!) }) } } } inner class FindByNameNonExisting : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val artifactEntities = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities( ArtifactEntity::class.java).toList() val artifactName = selectArtifactName(env, artifactEntities.map { it.name }) ?: run { env.logMessage("Cannot select non-existing name for search") return } env.logMessage("Search for artifact by name: $artifactName") onManager(env) { manager -> assertNull(runReadAction { manager.findArtifact (artifactName) }) } } } inner class FindByNameExisting : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val artifactEntities = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities( ArtifactEntity::class.java).toList() if (artifactEntities.isEmpty()) { env.logMessage("Cannot select artifact for finding") return } val artifactName = env.generateValue(Generator.sampledFrom(artifactEntities), null).name env.logMessage("Search for artifact by name: $artifactName") onManager(env) { manager -> assertNotNull(runReadAction { manager.findArtifact (artifactName) }) } } } inner class GetAllArtifactsIncludingInvalid : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val manager = ArtifactManager.getInstance(projectModel.project) env.logMessage("Get all artifacts including invalid") val artifacts = runReadAction { manager.allArtifactsIncludingInvalid } artifacts.forEach { _ -> // Nothing } } } inner class GetAllArtifacts : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val manager = ArtifactManager.getInstance(projectModel.project) env.logMessage("Get all artifacts") val artifacts = runReadAction { manager.artifacts } artifacts.forEach { _ -> // Nothing } } } inner class GetSortedArtifacts : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val manager = ArtifactManager.getInstance(projectModel.project) env.logMessage("Get all artifacts sorted") val artifacts = runReadAction { manager.sortedArtifacts } artifacts.forEach { _ -> // Nothing } } } inner class RemoveArtifact : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val (artifactForRemoval, _) = selectArtifactViaBridge(env, "removing") ?: return val manager = ArtifactManager.getInstance(projectModel.project) val initialArtifactsSize = runReadAction { manager.artifacts }.size val removalName = artifactForRemoval.name invokeAndWaitIfNeeded { runWriteAction { val modifiableModel = manager.createModifiableModel() modifiableModel.removeArtifact(artifactForRemoval) modifiableModel.commit() } } checkResult(env) { val newArtifactsList = runReadAction { manager.artifacts } assertEquals(initialArtifactsSize - 1, newArtifactsList.size) assertTrue(newArtifactsList.none { it.name == removalName }) val artifactEntities = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities(ArtifactEntity::class.java) assertTrue(artifactEntities.none { it.name == removalName }) } } } inner class AddArtifact : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val artifactName = selectArtifactName(env) val createRootElement = env.generateValue(Generator.sampledFrom(false, true, true, true, true, true), null) val (rootElement, rootVal) = if (createRootElement) createCompositeElement(env) else null to null val newArtifact = makeChecksHappy { val (instance, _, typeVal) = selectArtifactType(env) codeMaker.addLine("ArtifactManager.getInstance(project).addArtifact(\"$artifactName\", $typeVal, $rootVal)") ArtifactManager.getInstance(projectModel.project).addArtifact(artifactName, instance, rootElement) } val newArtifactName = newArtifact.name env.logMessage("Add new artifact via bridge: $newArtifactName. Final name: $newArtifactName") checkResult(env) { val bridgeVal = codeMaker.makeVal("bridgeArtifact", "artifact(project, \"$newArtifactName\")") val bridgeArtifact = artifact(projectModel.project, newArtifactName) val artifactEntityVal = codeMaker.makeVal("artifactEntity", "artifactEntity(project, \"$newArtifactName\")") val artifactEntity = artifactEntity(projectModel.project, newArtifactName) codeMaker.addLine("assertTreesEquals(project, $bridgeVal.rootElement, $artifactEntityVal.rootElement)") assertTreesEquals(projectModel.project, bridgeArtifact.rootElement, artifactEntity.rootElement!!) } } } inner class RenameArtifact : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val manager = ArtifactManager.getInstance(projectModel.project) val artifacts = runReadAction { manager.artifacts } if (artifacts.isEmpty()) return val index = env.generateValue(Generator.integers(0, artifacts.lastIndex), null) val newName = selectArtifactName(env, artifacts.map { it.name }) ?: run { env.logMessage("Cannot select name for new artifact via workspace model") return } val artifact = artifacts[index] val oldName = artifact.name env.logMessage("Rename artifact: $oldName -> $newName") makeChecksHappy { val modifiableModel = manager.createModifiableModel() val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) modifiableArtifact.name = newName modifiableModel.commit() } checkResult(env) { assertEquals(newName, runReadAction{ manager.artifacts }[index].name) val artifactEntities = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities(ArtifactEntity::class.java) assertTrue(artifactEntities.any { it.name == newName }) assertTrue(artifactEntities.none { it.name == oldName }) } } } inner class ChangeBuildOnMake : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val manager = ArtifactManager.getInstance(projectModel.project) val artifacts = runReadAction { manager.artifacts } if (artifacts.isEmpty()) return val index = env.generateValue(Generator.integers(0, artifacts.lastIndex), null) val artifact = artifacts[index] val oldBuildOnMake = artifact.isBuildOnMake env.logMessage("Change isBuildOnMake for ${artifact.name}. New value: ${oldBuildOnMake}") makeChecksHappy { val modifiableModel = manager.createModifiableModel() val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) modifiableArtifact.isBuildOnMake = !modifiableArtifact.isBuildOnMake modifiableModel.commit() } checkResult(env) { assertEquals(!oldBuildOnMake, runReadAction{ manager.artifacts }[index].isBuildOnMake) val artifactEntities = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities(ArtifactEntity::class.java) assertTrue(artifactEntities.single { it.name == artifact.name }.includeInProjectBuild == !oldBuildOnMake) } } } inner class ChangeArtifactType : ImperativeCommand { override fun performCommand(env: ImperativeCommand.Environment) { val artifact = selectArtifactBridge(env, "change artifact type") ?: return val artifactVal = codeMaker.v("chosenArtifact") val (newArtifactType, id, typeVal) = selectArtifactType(env) env.logMessage("Change artifact type for ${artifact.name}. New value: ${newArtifactType}") makeChecksHappy { modifyArtifact(artifact, artifactVal) { codeMaker.addLine("$it.artifactType = $typeVal") artifactType = newArtifactType } } checkResult(env) { assertEquals(newArtifactType, artifact(projectModel.project, artifact.name).artifactType) val artifactEntityVal = codeMaker.makeVal("artifactEntity", "artifactEntity(project, \"${artifact.name}\")") codeMaker.addLine("assertTrue($artifactEntityVal.artifactType == \"$id\")") val artifactEntity = artifactEntity(projectModel.project, artifact.name) assertTrue(artifactEntity.artifactType == id) } } } private fun modifyArtifact(artifact: Artifact, artifactVal: String, modification: ModifiableArtifact.(String) -> Unit) { val modifiableModel = ArtifactManager.getInstance(projectModel.project).createModifiableModel() val modifiableArtifact = modifiableModel.getOrCreateModifiableArtifact(artifact) val modifiableModelVal = codeMaker.makeVal("modifiableModel", "ArtifactManager.getInstance(project).createModifiableModel()") val modifiableArtifactVal = codeMaker.makeVal("modifiableArtifact", "$modifiableModelVal.getOrCreateModifiableArtifact($artifactVal)") modifiableArtifact.modification(modifiableArtifactVal) codeMaker.addLine("$modifiableModelVal.commit()") modifiableModel.commit() } private fun selectArtifactName(env: ImperativeCommand.Environment): String { return "Artifact-${env.generateValue(Generator.integers(0, MAX_ARTIFACT_NUMBER), null)}" } private fun selectArtifactName(env: ImperativeCommand.Environment, notLike: List<String>): String? { var counter = 50 while (counter > 0) { val name = selectArtifactName(env) if (name !in notLike) return name counter-- } return null } private fun createCompositeElement(env: ImperativeCommand.Environment): Pair<CompositePackagingElement<*>, String> { val root = ArtifactRootElementImpl() val rootVal = codeMaker.makeVal("artifactRoot", "ArtifactRootElementImpl()") val value = env.generateValue(Generator.booleans(), null) if (value) { root.addFirstChild(makeElementsTree(env).first) codeMaker.addLine("$rootVal.addFirstChild(${codeMaker.v("element_0")})") } return root to rootVal } private fun makeElementsTree(env: ImperativeCommand.Environment, depth: Int = 0): Pair<PackagingElement<*>, String> { val value = env.generateValue(Generator.integers(0, 3), null) val indent = " ".repeat(depth) val (element, elementName) = when (value) { 0 -> { val directoryName = env.generateValue(Generator.sampledFrom(names), null) val element = DirectoryPackagingElement(directoryName) val currentElementName = codeMaker.makeVal("element_$depth", "DirectoryPackagingElement(\"$directoryName\")") env.logMessage("${indent}Generate DirectoryPackagingElement: $directoryName") element to currentElementName } 1 -> { val outputName = env.generateValue(Generator.sampledFrom(names), null) val pathName = "/" + env.generateValue(Generator.sampledFrom(names), null) env.logMessage("${indent}Generate FileCopyPackagingElement ($pathName -> $outputName)") val currentElementName = codeMaker.makeVal("element_$depth", "FileCopyPackagingElement(\"$pathName\", \"$outputName\")") FileCopyPackagingElement(pathName, outputName) to currentElementName } 2 -> { val data = env.generateValue(Generator.sampledFrom(names), null) env.logMessage("${indent}Generate MyWorkspacePackagingElement ($data)") val currentElementName = codeMaker.makeVal("element_$depth", "MyWorkspacePackagingElement(\"$data\")") MyWorkspacePackagingElement(data) to currentElementName } 3 -> { val data = env.generateValue(Generator.sampledFrom(names), null) val name = env.generateValue(Generator.sampledFrom(names), null) env.logMessage("${indent}Generate MyCompositeWorkspacePackagingElement ($data, $name)") val currentElementName = codeMaker.makeVal("element_$depth", "MyCompositeWorkspacePackagingElement(\"$data\", \"$name\")") MyCompositeWorkspacePackagingElement(data, name) to currentElementName } else -> error("Unexpected branch") } if (element is CompositePackagingElement<*>) { if (depth < 5) { // This is all magic numbers. Just trying to make less children for deeper layers of package elements tree val maxChildren = when { depth == 0 -> 5 depth in 1..2 -> 3 depth in 3..4 -> 2 depth > 4 -> 1 else -> 0 } val amountOfChildren = env.generateValue(Generator.integers(0, maxChildren), null) env.logMessage("${indent}- Generate $amountOfChildren children:") for (i in 0 until amountOfChildren) { val (child, name) = makeElementsTree(env, depth + 1) element.addFirstChild(child) codeMaker.addLine("$elementName.addFirstChild($name)") } } } return element to elementName } private fun createCompositeElementEntity(env: ImperativeCommand.Environment, builder: MutableEntityStorage): CompositePackagingElementEntity { return builder.addArtifactRootElementEntity(emptyList(), TestEntitySource) } private fun chooseSomeElementFromTree(env: ImperativeCommand.Environment, artifact: Artifact): Pair<CompositePackagingElement<*>?, PackagingElement<*>> { val root = artifact.rootElement val allElements: MutableList<Pair<CompositePackagingElement<*>?, PackagingElement<*>>> = mutableListOf(null to root) flatElements(root, allElements) val (parent, child) = env.generateValue(Generator.sampledFrom(allElements), null) val artifactVal = codeMaker.vOrNull("modifiableArtifact") ?: codeMaker.v("chosenArtifact") var rootElementVal = codeMaker.makeVal("rootElement", "$artifactVal.rootElement") if (root != child) { val address = generateAddress(root, child)!! var childElementVal = "($rootElementVal as CompositePackagingElement<*>).children[${address[0]}]" address.drop(1).forEach { rootElementVal = childElementVal childElementVal = "($rootElementVal as CompositePackagingElement<*>).children[$it]" } codeMaker.makeVal("chosenParent", "$rootElementVal as CompositePackagingElement<*>") codeMaker.makeVal("chosenChild", childElementVal) } else { codeMaker.makeVal("chosenParent", null) codeMaker.makeVal("chosenChild", rootElementVal) } return parent to child } private fun generateAddress(root: CompositePackagingElement<*>, child: PackagingElement<*>): List<Int>? { root.children.forEachIndexed { index, packagingElement -> val indexList = listOf(index) if (packagingElement === child) return indexList if (packagingElement is CompositePackagingElement<*>) { val result = generateAddress(packagingElement, child) if (result != null) { return indexList + result } } } return null } private fun generateAddress(root: CompositePackagingElementEntity, child: PackagingElementEntity): List<Int>? { root.children.forEachIndexed { index, packagingElement -> if (packagingElement == child) return listOf(index) if (packagingElement is CompositePackagingElementEntity) { val result = generateAddress(packagingElement, child) if (result != null) { return result } } } return null } private fun selectArtifactType(env: ImperativeCommand.Environment): Triple<ArtifactType, String, String> { val selector = env.generateValue(Generator.integers(0, allArtifactTypes.lastIndex), null) val artifactVal = codeMaker.makeVal("artifactType", "allArtifactTypes[$selector]") val instance = allArtifactTypes[selector] return Triple(instance, instance.id, artifactVal) } private fun flatElements(currentElement: CompositePackagingElement<*>, result: MutableList<Pair<CompositePackagingElement<*>?, PackagingElement<*>>>) { currentElement.children.forEach { result.add(currentElement to it) if (it is CompositePackagingElement<*>) { flatElements(it, result) } } } private fun selectArtifactViaBridge(env: ImperativeCommand.Environment, reason: String): Pair<Artifact, ArtifactManager>? { val manager = ArtifactManager.getInstance(projectModel.project) val artifacts = runReadAction { manager.artifacts } if (artifacts.isEmpty()) { env.logMessage("Cannot select artifact for $reason") return null } val selectedArtifact = env.generateValue(Generator.sampledFrom(*artifacts), null) val artifactIndex = artifacts.indexOf(selectedArtifact) val managerVal = codeMaker.makeVal("manager", "ArtifactManager.getInstance(project)") val artifactsVal = codeMaker.makeVal("artifacts", "$managerVal.artifacts") codeMaker.makeVal("chosenArtifact", "$artifactsVal[$artifactIndex]") return selectedArtifact to manager } fun selectArtifactViaModel(env: ImperativeCommand.Environment, workspaceModel: WorkspaceModel, reason: String): ArtifactEntity? { val existingArtifacts = workspaceModel.entityStorage.current.entities(ArtifactEntity::class.java).toList() if (existingArtifacts.isEmpty()) { env.logMessage("Cannot select artifact for $reason") return null } val selectedArtifact = env.generateValue(Generator.sampledFrom(existingArtifacts), null) val artifactEntityId = existingArtifacts.indexOf(selectedArtifact) codeMaker.makeVal("chosenArtifactEntity", "WorkspaceModel.getInstance(project).entityStorage.current.entities(ArtifactEntity::class.java).toList()[$artifactEntityId]") return selectedArtifact } private fun selectArtifactBridge(env: ImperativeCommand.Environment, reason: String): Artifact? { val viaBridge = env.generateValue(Generator.booleans(), null) return if (viaBridge) { selectArtifactViaBridge(env, reason)?.first } else { val workspaceModel = WorkspaceModel.getInstance(projectModel.project) val entity = selectArtifactViaModel(env, workspaceModel, reason) ?: return null codeMaker.makeVal("chosenArtifact", "WorkspaceModel.getInstance(project).entityStorage.current.artifactsMap.getDataByEntity(${codeMaker.v("chosenArtifactEntity")})") workspaceModel.entityStorage.current.artifactsMap.getDataByEntity(entity) } } private inline fun checkResult(env: ImperativeCommand.Environment, action: () -> Unit) { val checkResult = env.generateValue(Generator.booleans(), null) env.logMessage("Check result: $checkResult") if (checkResult) { action() } assertArtifactsHaveStableStore() } private inline fun onManager(env: ImperativeCommand.Environment, action: (ArtifactModel) -> Unit) { val onModifiableModel = env.generateValue(Generator.booleans(), null) val manager = if (onModifiableModel) { ArtifactManager.getInstance(projectModel.project).createModifiableModel() } else { ArtifactManager.getInstance(projectModel.project) } action(manager) if (onModifiableModel) (manager as ModifiableArtifactModel).dispose() } private fun assertArtifactsHaveStableStore() { val manager = ArtifactManager.getInstance(projectModel.project) runReadAction{ manager.artifacts }.forEach { assertTrue((it as ArtifactBridge).entityStorage is VersionedEntityStorageImpl) } } private val names = List(20) { "Name-$it" } private fun <T> makeChecksHappy(action: () -> T): T { return invokeAndWaitIfNeeded { runWriteAction { codeMaker.startScope("happyResult", "invokeAndWaitIfNeeded") codeMaker.startScope("runWriteAction") try { return@runWriteAction action() } finally { if (codeMaker.last()?.trimIndent()?.startsWith("return") != true) { codeMaker.addLine("return@runWriteAction null") } codeMaker.finishScope() codeMaker.finishScope() } } } } private fun writeActionDisposable(parent: Disposable): Disposable { val writeDisposable = Disposer.newDisposable() Disposer.register(parent) { invokeAndWaitIfNeeded { runWriteAction { Disposer.dispose(writeDisposable) } } } return writeDisposable } } object TestEntitySource : EntitySource class MyWorkspacePackagingElement(data: String) : PackagingElement<MyWorkspacePackagingElementState>(PackagingElementType.EP_NAME.findExtensionOrFail(MyWorkspacePackagingElementType::class.java)) { constructor(): this("") private val state: MyWorkspacePackagingElementState = MyWorkspacePackagingElementState(data) override fun getState(): MyWorkspacePackagingElementState = state override fun loadState(state: MyWorkspacePackagingElementState) { this.state.data = state.data } override fun isEqualTo(element: PackagingElement<*>): Boolean = (element as? MyWorkspacePackagingElement)?.state?.data == state.data override fun createPresentation(context: ArtifactEditorContext): PackagingElementPresentation { throw UnsupportedOperationException() } } class MyWorkspacePackagingElementState(var data: String = "") object MyWorkspacePackagingElementType : PackagingElementType<MyWorkspacePackagingElement>("Custom-element", Supplier { "Custom Element" }) { override fun canCreate(context: ArtifactEditorContext, artifact: Artifact): Boolean = true override fun chooseAndCreate(context: ArtifactEditorContext, artifact: Artifact, parent: CompositePackagingElement<*>): MutableList<out PackagingElement<*>> { throw UnsupportedOperationException() } override fun createEmpty(project: Project): MyWorkspacePackagingElement { return MyWorkspacePackagingElement() } } class MyCompositeWorkspacePackagingElement(data: String, name: String) : CompositePackagingElement<MyCompositeWorkspacePackagingElementState>(PackagingElementType.EP_NAME.findExtensionOrFail(MyCompositeWorkspacePackagingElementType::class.java)) { constructor(): this("", "") private val state: MyCompositeWorkspacePackagingElementState = MyCompositeWorkspacePackagingElementState(data, name) override fun getState(): MyCompositeWorkspacePackagingElementState = state override fun loadState(state: MyCompositeWorkspacePackagingElementState) { this.state.data = state.data } override fun isEqualTo(element: PackagingElement<*>): Boolean = (element as? MyCompositeWorkspacePackagingElement)?.state?.data == state.data override fun getName(): String = state.name override fun rename(newName: String) { state.name = newName } override fun createPresentation(context: ArtifactEditorContext): PackagingElementPresentation { throw UnsupportedOperationException() } override fun toString(): String { return "MyCompositeWorkspacePackagingElement(state=$state)" } } data class MyCompositeWorkspacePackagingElementState(var data: String = "", var name: String = "") object MyCompositeWorkspacePackagingElementType : PackagingElementType<MyCompositeWorkspacePackagingElement>("Composite-custom-element", Supplier { "Composite Custom Element" }) { override fun canCreate(context: ArtifactEditorContext, artifact: Artifact): Boolean = true override fun chooseAndCreate(context: ArtifactEditorContext, artifact: Artifact, parent: CompositePackagingElement<*>): MutableList<out PackagingElement<*>> { throw UnsupportedOperationException() } override fun createEmpty(project: Project): MyCompositeWorkspacePackagingElement { return MyCompositeWorkspacePackagingElement() } } internal val customArtifactTypes: List<ArtifactType> = List(10) { object : ArtifactType("myArtifactType-$it", Supplier{ "myArtifactType-$it" }) { override fun getIcon(): Icon = EmptyIcon.ICON_16 override fun getDefaultPathFor(kind: PackagingElementOutputKind): String = "" override fun createRootElement(artifactName: String): CompositePackagingElement<*> { return PackagingElementFactory.getInstance().createArtifactRootElement() } } } internal val allArtifactTypes = customArtifactTypes + PlainArtifactType.getInstance()
apache-2.0
13b3d145f8b433211a849ad3afd87647
40.661149
247
0.71063
5.159913
false
false
false
false
GraphGrid/neo4j-graphql
src/main/kotlin/org/neo4j/graphql/GraphSchemaScanner.kt
1
5618
package org.neo4j.graphql import org.neo4j.graphdb.Direction import org.neo4j.graphdb.GraphDatabaseService import org.neo4j.graphdb.Label import org.neo4j.graphdb.Node import org.neo4j.helpers.collection.Iterators import org.neo4j.kernel.impl.core.GraphProperties import org.neo4j.kernel.impl.core.NodeManager import org.neo4j.kernel.internal.GraphDatabaseAPI import java.util.* class GraphSchemaScanner { companion object { fun fieldName(type: String) : String = type.split("_").mapIndexed { i, s -> if (i==0) s.toLowerCase() else s.toLowerCase().capitalize() }.joinToString("") internal val allTypes = LinkedHashMap<String, MetaData>() internal var schema : String? = null val DENSE_NODE = 50 @JvmStatic fun from(db: GraphDatabaseService, label: Label): MetaData { val metaData = MetaData(label.name()) inspectIndexes(metaData, db, label) sampleNodes(metaData, db, label) return metaData } fun storeIdl(db: GraphDatabaseService, schema: String) : Map<String, MetaData> { val tx = db.beginTx() try { val metaDatas = IDLParser.parse(schema) graphProperties(db).setProperty("graphql.idl", schema) tx.success() return metaDatas } finally { tx.close() GraphSchema.reset() } } private fun graphProperties(db: GraphDatabaseService): GraphProperties { val nodeManager = (db as (GraphDatabaseAPI)).getDependencyResolver().resolveDependency(NodeManager::class.java) val props = nodeManager.newGraphProperties(); return props } fun deleteIdl(db: GraphDatabaseService) { val tx = db.beginTx() try { graphProperties(db).removeProperty("graphql.idl") tx.success() } finally { tx.close() } } fun readIdlMetadata(db: GraphDatabaseService) = readIdl(db)?.let { IDLParser.parse(it) } fun readIdl(db: GraphDatabaseService) : String? { val tx = db.beginTx() try { val schema = graphProperties(db).getProperty("graphql.idl", null) as String? tx.success() return schema } finally { tx.close() } } fun databaseSchema(db: GraphDatabaseService) { allTypes.clear(); schema = readIdl(db) val idlMetaData = readIdlMetadata(db) if (idlMetaData != null) { allTypes.putAll(idlMetaData) } if (allTypes.isEmpty()) { allTypes.putAll(sampleDataBase(db)) } } fun allTypes(): Map<String, MetaData> = allTypes fun allMetaDatas() = allTypes.values fun getMetaData(type: String): MetaData? { return allTypes[type] } private fun inspectIndexes(md: MetaData, db: GraphDatabaseService, label: Label) { for (index in db.schema().getIndexes(label)) { for (s in index.propertyKeys) { if (index.isConstraintIndex) md.addIdProperty(s) md.addIndexedProperty(s) } } } private fun sampleDataBase(db: GraphDatabaseService): Map<String, MetaData> { val tx = db.beginTx() try { val result = db.allLabels.associate { label -> label.name() to from(db,label) } tx.success() return result } finally { tx.close() } } private fun sampleNodes(md: MetaData, db: GraphDatabaseService, label: Label) { var count = 10 val nodes = db.findNodes(label) while (nodes.hasNext() && count-- > 0) { val node = nodes.next() for (l in node.labels) md.addLabel(l.name()) node.allProperties.forEach { k, v -> md.addProperty(k, v.javaClass) } sampleRelationships(md, node) } } private fun sampleRelationships(md: MetaData, node: Node) { val dense = node.degree > DENSE_NODE for (type in node.relationshipTypes) { val itOut = node.getRelationships(Direction.OUTGOING, type).iterator() val out = Iterators.firstOrNull(itOut) val typeName = type.name() val fieldName = fieldName(typeName) // todo handle end-label if (out != null) { if (!dense || node.getDegree(type, Direction.OUTGOING) < DENSE_NODE) { labelsFor(out.endNode) { label -> md.mergeRelationship(typeName, fieldName,label,true,itOut.hasNext(),null,0) } } } val itIn = node.getRelationships(Direction.INCOMING, type).iterator() val `in` = Iterators.firstOrNull(itIn) if (`in` != null) { if (!dense || node.getDegree(type, Direction.INCOMING) < DENSE_NODE) { labelsFor(`in`.startNode) { label -> md.mergeRelationship(typeName, fieldName,label,false,itIn.hasNext(),null,0) } } } } } private fun labelsFor(node: Node, consumer: (String) -> Unit) { for (label in node.labels) { consumer.invoke(label.name()) } } } }
apache-2.0
66701ae174a1db74c8abf75478f8f70d
36.704698
163
0.545924
4.662241
false
false
false
false
SimpleMobileTools/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PhotoVideoActivity.kt
1
16749
package com.simplemobiletools.gallery.pro.activities import android.content.Intent import android.content.res.Configuration import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.text.Html import android.view.View import android.widget.RelativeLayout import com.simplemobiletools.commons.dialogs.PropertiesDialog import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.gallery.pro.BuildConfig import com.simplemobiletools.gallery.pro.R import com.simplemobiletools.gallery.pro.extensions.* import com.simplemobiletools.gallery.pro.fragments.PhotoFragment import com.simplemobiletools.gallery.pro.fragments.VideoFragment import com.simplemobiletools.gallery.pro.fragments.ViewPagerFragment import com.simplemobiletools.gallery.pro.helpers.* import com.simplemobiletools.gallery.pro.models.Medium import kotlinx.android.synthetic.main.bottom_actions.* import kotlinx.android.synthetic.main.fragment_holder.* import java.io.File import java.io.FileInputStream open class PhotoVideoActivity : SimpleActivity(), ViewPagerFragment.FragmentListener { private var mMedium: Medium? = null private var mIsFullScreen = false private var mIsFromGallery = false private var mFragment: ViewPagerFragment? = null private var mUri: Uri? = null var mIsVideo = false public override fun onCreate(savedInstanceState: Bundle?) { showTransparentTop = true showTransparentNavigation = true super.onCreate(savedInstanceState) setContentView(R.layout.fragment_holder) if (checkAppSideloading()) { return } setupOptionsMenu() refreshMenuItems() handlePermission(getPermissionToRequest()) { if (it) { checkIntent(savedInstanceState) } else { toast(R.string.no_storage_permissions) finish() } } } override fun onResume() { super.onResume() if (config.bottomActions) { window.navigationBarColor = Color.TRANSPARENT } else { setTranslucentNavigation() } if (config.blackBackground) { updateStatusbarColor(Color.BLACK) } } fun refreshMenuItems() { val visibleBottomActions = if (config.bottomActions) config.visibleBottomActions else 0 fragment_viewer_toolbar.menu.apply { findItem(R.id.menu_set_as).isVisible = mMedium?.isImage() == true && visibleBottomActions and BOTTOM_ACTION_SET_AS == 0 findItem(R.id.menu_edit).isVisible = mMedium?.isImage() == true && mUri?.scheme == "file" && visibleBottomActions and BOTTOM_ACTION_EDIT == 0 findItem(R.id.menu_properties).isVisible = mUri?.scheme == "file" && visibleBottomActions and BOTTOM_ACTION_PROPERTIES == 0 findItem(R.id.menu_share).isVisible = visibleBottomActions and BOTTOM_ACTION_SHARE == 0 findItem(R.id.menu_show_on_map).isVisible = visibleBottomActions and BOTTOM_ACTION_SHOW_ON_MAP == 0 } } private fun setupOptionsMenu() { (fragment_viewer_appbar.layoutParams as RelativeLayout.LayoutParams).topMargin = statusBarHeight fragment_viewer_toolbar.apply { setTitleTextColor(Color.WHITE) overflowIcon = resources.getColoredDrawableWithColor(R.drawable.ic_three_dots_vector, Color.WHITE) navigationIcon = resources.getColoredDrawableWithColor(R.drawable.ic_arrow_left_vector, Color.WHITE) } updateMenuItemColors(fragment_viewer_toolbar.menu, forceWhiteIcons = true) fragment_viewer_toolbar.setOnMenuItemClickListener { menuItem -> if (mMedium == null || mUri == null) { return@setOnMenuItemClickListener true } when (menuItem.itemId) { R.id.menu_set_as -> setAs(mUri!!.toString()) R.id.menu_open_with -> openPath(mUri!!.toString(), true) R.id.menu_share -> sharePath(mUri!!.toString()) R.id.menu_edit -> openEditor(mUri!!.toString()) R.id.menu_properties -> showProperties() R.id.menu_show_on_map -> showFileOnMap(mUri!!.toString()) else -> return@setOnMenuItemClickListener false } return@setOnMenuItemClickListener true } fragment_viewer_toolbar.setNavigationOnClickListener { finish() } } private fun checkIntent(savedInstanceState: Bundle? = null) { if (intent.data == null && intent.action == Intent.ACTION_VIEW) { hideKeyboard() startActivity(Intent(this, MainActivity::class.java)) finish() return } mUri = intent.data ?: return val uri = mUri.toString() if (uri.startsWith("content:/") && uri.contains("/storage/") && !intent.getBooleanExtra(IS_IN_RECYCLE_BIN, false)) { val guessedPath = uri.substring(uri.indexOf("/storage/")) if (getDoesFilePathExist(guessedPath)) { val extras = intent.extras ?: Bundle() extras.apply { putString(REAL_FILE_PATH, guessedPath) intent.putExtras(this) } } } var filename = getFilenameFromUri(mUri!!) mIsFromGallery = intent.getBooleanExtra(IS_FROM_GALLERY, false) if (mIsFromGallery && filename.isVideoFast() && config.openVideosOnSeparateScreen) { launchVideoPlayer() return } if (intent.extras?.containsKey(REAL_FILE_PATH) == true) { val realPath = intent.extras!!.getString(REAL_FILE_PATH) if (realPath != null && getDoesFilePathExist(realPath)) { val isFileFolderHidden = (File(realPath).isHidden || File(realPath.getParentPath(), NOMEDIA).exists() || realPath.contains("/.")) val preventShowingHiddenFile = (isRPlus() && !isExternalStorageManager()) && isFileFolderHidden if (!preventShowingHiddenFile) { if (realPath.getFilenameFromPath().contains('.') || filename.contains('.')) { if (isFileTypeVisible(realPath)) { bottom_actions.beGone() sendViewPagerIntent(realPath) finish() return } } else { filename = realPath.getFilenameFromPath() } } } } if (mUri!!.scheme == "file") { if (filename.contains('.')) { bottom_actions.beGone() rescanPaths(arrayListOf(mUri!!.path!!)) sendViewPagerIntent(mUri!!.path!!) finish() } return } else { val realPath = applicationContext.getRealPathFromURI(mUri!!) ?: "" val isFileFolderHidden = (File(realPath).isHidden || File(realPath.getParentPath(), NOMEDIA).exists() || realPath.contains("/.")) val preventShowingHiddenFile = (isRPlus() && !isExternalStorageManager()) && isFileFolderHidden if (!preventShowingHiddenFile) { if (realPath != mUri.toString() && realPath.isNotEmpty() && mUri!!.authority != "mms" && filename.contains('.') && getDoesFilePathExist(realPath)) { if (isFileTypeVisible(realPath)) { bottom_actions.beGone() rescanPaths(arrayListOf(mUri!!.path!!)) sendViewPagerIntent(realPath) finish() return } } } } top_shadow.layoutParams.height = statusBarHeight + actionBarHeight if (!portrait && navigationBarOnSide && navigationBarWidth > 0) { fragment_viewer_toolbar.setPadding(0, 0, navigationBarWidth, 0) } else { fragment_viewer_toolbar.setPadding(0, 0, 0, 0) } checkNotchSupport() showSystemUI(true) val bundle = Bundle() val file = File(mUri.toString()) val intentType = intent.type ?: "" val type = when { filename.isVideoFast() || intentType.startsWith("video/") -> TYPE_VIDEOS filename.isGif() || intentType.equals("image/gif", true) -> TYPE_GIFS filename.isRawFast() -> TYPE_RAWS filename.isSvg() -> TYPE_SVGS file.isPortrait() -> TYPE_PORTRAITS else -> TYPE_IMAGES } mIsVideo = type == TYPE_VIDEOS mMedium = Medium(null, filename, mUri.toString(), mUri!!.path!!.getParentPath(), 0, 0, file.length(), type, 0, false, 0L, 0) fragment_viewer_toolbar.title = Html.fromHtml("<font color='${Color.WHITE.toHex()}'>${mMedium!!.name}</font>") bundle.putSerializable(MEDIUM, mMedium) if (savedInstanceState == null) { mFragment = if (mIsVideo) VideoFragment() else PhotoFragment() mFragment!!.listener = this mFragment!!.arguments = bundle supportFragmentManager.beginTransaction().replace(R.id.fragment_placeholder, mFragment!!).commit() } if (config.blackBackground) { fragment_holder.background = ColorDrawable(Color.BLACK) } if (config.maxBrightness) { val attributes = window.attributes attributes.screenBrightness = 1f window.attributes = attributes } window.decorView.setOnSystemUiVisibilityChangeListener { visibility -> val isFullscreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0 mFragment?.fullscreenToggled(isFullscreen) } initBottomActions() } private fun launchVideoPlayer() { val newUri = getFinalUriFromPath(mUri.toString(), BuildConfig.APPLICATION_ID) if (newUri == null) { toast(R.string.unknown_error_occurred) return } var isPanorama = false val realPath = intent?.extras?.getString(REAL_FILE_PATH) ?: "" try { if (realPath.isNotEmpty()) { val fis = FileInputStream(File(realPath)) parseFileChannel(realPath, fis.channel, 0, 0, 0) { isPanorama = true } } } catch (ignored: Exception) { } catch (ignored: OutOfMemoryError) { } hideKeyboard() if (isPanorama) { Intent(applicationContext, PanoramaVideoActivity::class.java).apply { putExtra(PATH, realPath) startActivity(this) } } else { val mimeType = getUriMimeType(mUri.toString(), newUri) Intent(applicationContext, VideoPlayerActivity::class.java).apply { setDataAndType(newUri, mimeType) addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT) if (intent.extras != null) { putExtras(intent.extras!!) } startActivity(this) } } finish() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) initBottomActionsLayout() top_shadow.layoutParams.height = statusBarHeight + actionBarHeight (fragment_viewer_appbar.layoutParams as RelativeLayout.LayoutParams).topMargin = statusBarHeight if (!portrait && navigationBarOnSide && navigationBarWidth > 0) { fragment_viewer_toolbar.setPadding(0, 0, navigationBarWidth, 0) } else { fragment_viewer_toolbar.setPadding(0, 0, 0, 0) } } private fun sendViewPagerIntent(path: String) { ensureBackgroundThread { if (isPathPresentInMediaStore(path)) { openViewPager(path) } else { rescanPath(path) { openViewPager(path) } } } } private fun openViewPager(path: String) { if (!intent.getBooleanExtra(IS_FROM_GALLERY, false)) { MediaActivity.mMedia.clear() } runOnUiThread { hideKeyboard() Intent(this, ViewPagerActivity::class.java).apply { putExtra(SKIP_AUTHENTICATION, intent.getBooleanExtra(SKIP_AUTHENTICATION, false)) putExtra(SHOW_FAVORITES, intent.getBooleanExtra(SHOW_FAVORITES, false)) putExtra(IS_VIEW_INTENT, true) putExtra(IS_FROM_GALLERY, mIsFromGallery) putExtra(PATH, path) startActivity(this) } } } private fun isPathPresentInMediaStore(path: String): Boolean { val uri = MediaStore.Files.getContentUri("external") val selection = "${MediaStore.Images.Media.DATA} = ?" val selectionArgs = arrayOf(path) try { val cursor = contentResolver.query(uri, null, selection, selectionArgs, null) cursor?.use { return cursor.moveToFirst() } } catch (e: Exception) { } return false } private fun showProperties() { PropertiesDialog(this, mUri!!.path!!) } private fun isFileTypeVisible(path: String): Boolean { val filter = config.filterMedia return !(path.isImageFast() && filter and TYPE_IMAGES == 0 || path.isVideoFast() && filter and TYPE_VIDEOS == 0 || path.isGif() && filter and TYPE_GIFS == 0 || path.isRawFast() && filter and TYPE_RAWS == 0 || path.isSvg() && filter and TYPE_SVGS == 0 || path.isPortrait() && filter and TYPE_PORTRAITS == 0) } private fun initBottomActions() { initBottomActionButtons() initBottomActionsLayout() } private fun initBottomActionsLayout() { bottom_actions.layoutParams.height = resources.getDimension(R.dimen.bottom_actions_height).toInt() + navigationBarHeight if (config.bottomActions) { bottom_actions.beVisible() } else { bottom_actions.beGone() } } private fun initBottomActionButtons() { arrayListOf( bottom_favorite, bottom_delete, bottom_rotate, bottom_properties, bottom_change_orientation, bottom_slideshow, bottom_show_on_map, bottom_toggle_file_visibility, bottom_rename, bottom_copy, bottom_move, bottom_resize ).forEach { it.beGone() } val visibleBottomActions = if (config.bottomActions) config.visibleBottomActions else 0 bottom_edit.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_EDIT != 0 && mMedium?.isImage() == true) bottom_edit.setOnClickListener { if (mUri != null && bottom_actions.alpha == 1f) { openEditor(mUri!!.toString()) } } bottom_share.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_SHARE != 0) bottom_share.setOnClickListener { if (mUri != null && bottom_actions.alpha == 1f) { sharePath(mUri!!.toString()) } } bottom_set_as.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_SET_AS != 0 && mMedium?.isImage() == true) bottom_set_as.setOnClickListener { setAs(mUri!!.toString()) } bottom_show_on_map.beVisibleIf(visibleBottomActions and BOTTOM_ACTION_SHOW_ON_MAP != 0) bottom_show_on_map.setOnClickListener { showFileOnMap(mUri!!.toString()) } } override fun fragmentClicked() { mIsFullScreen = !mIsFullScreen if (mIsFullScreen) { hideSystemUI(true) } else { showSystemUI(true) } val newAlpha = if (mIsFullScreen) 0f else 1f top_shadow.animate().alpha(newAlpha).start() if (!bottom_actions.isGone()) { bottom_actions.animate().alpha(newAlpha).start() } fragment_viewer_toolbar.animate().alpha(newAlpha).withStartAction { fragment_viewer_toolbar.beVisible() }.withEndAction { fragment_viewer_toolbar.beVisibleIf(newAlpha == 1f) }.start() } override fun videoEnded() = false override fun goToPrevItem() {} override fun goToNextItem() {} override fun launchViewVideoIntent(path: String) {} override fun isSlideShowActive() = false }
gpl-3.0
691001c4e7dac7c29888554c14abd43d
37.770833
164
0.598722
4.864653
false
false
false
false
Leifzhang/AndroidRouter
Plugin/BasePlugin/src/main/java/com/kronos/plugin/base/JarUtils.kt
1
4364
package com.kronos.plugin.base import com.kronos.plugin.base.utils.DigestUtils import java.io.File import java.io.FileOutputStream import java.util.* import java.util.jar.JarFile import java.util.jar.JarOutputStream import java.util.zip.ZipEntry internal object JarUtils { fun modifyJarFile(jarFile: File, tempDir: File?, transform: BaseTransform): File { /** 设置输出到的jar */ val hexName = DigestUtils.md5Hex(jarFile.absolutePath).substring(0, 8) val optJar = File(tempDir, hexName + jarFile.name) val jarOutputStream = JarOutputStream(FileOutputStream(optJar)) jarOutputStream.use { val file = JarFile(jarFile) val enumeration = file.entries() enumeration.iterator().forEach { jarEntry -> val inputStream = file.getInputStream(jarEntry) val entryName = jarEntry.name if (entryName.contains("module-info.class") && !entryName.contains("META-INF")) { Log.info("jar file module-info:$entryName jarFileName:${jarFile.path}") } else { val zipEntry = ZipEntry(entryName) jarOutputStream.putNextEntry(zipEntry) var modifiedClassBytes: ByteArray? = null val sourceClassBytes = inputStream.readBytes() if (entryName.endsWith(".class")) { try { modifiedClassBytes = transform.process(entryName, sourceClassBytes) } catch (ignored: Exception) { } } /** * 读取原jar */ if (modifiedClassBytes == null) { jarOutputStream.write(sourceClassBytes) } else { jarOutputStream.write(modifiedClassBytes) } jarOutputStream.closeEntry() } } } return optJar } fun scanJarFile(jarFile: File): HashSet<String> { val hashSet = HashSet<String>() val file = JarFile(jarFile) file.use { val enumeration = file.entries() while (enumeration.hasMoreElements()) { val jarEntry = enumeration.nextElement() val entryName = jarEntry.name if (entryName.contains("module-info.class")) { Log.info("module-info:$entryName") continue } if (entryName.endsWith(".class")) { hashSet.add(entryName) } } } return hashSet } fun deleteJarScan(jarFile: File?, removeClasses: List<String>, callBack: DeleteCallBack?) { /** * 读取原jar */ val file = JarFile(jarFile) file.use { val enumeration = file.entries() while (enumeration.hasMoreElements()) { val jarEntry = enumeration.nextElement() val entryName = jarEntry.name if (entryName.endsWith(".class") && removeClasses.contains(entryName)) { val inputStream = file.getInputStream(jarEntry) val sourceClassBytes = inputStream.readBytes() try { callBack?.delete(entryName, sourceClassBytes) } catch (ignored: Exception) { } } } } } fun deleteJarScan(jarFile: File?, callBack: DeleteCallBack?) { /** * 读取原jar */ val file = JarFile(jarFile) file.use { val enumeration = file.entries() while (enumeration.hasMoreElements()) { val jarEntry = enumeration.nextElement() val inputStream = file.getInputStream(jarEntry) val entryName = jarEntry.name val sourceClassBytes = inputStream.readBytes() if (entryName.endsWith(".class")) { try { callBack?.delete(entryName, sourceClassBytes) } catch (ignored: Exception) { } } } } } }
mit
e2cc4c9b350816726c511055e9727f13
36.695652
97
0.51246
5.486076
false
false
false
false
DmytroTroynikov/aemtools
lang/src/main/kotlin/com/aemtools/lang/htl/file/HtlFileType.kt
1
1487
package com.aemtools.lang.htl.file import com.aemtools.lang.htl.HtlLanguage import com.aemtools.lang.htl.highlight.HtlTemplateHighlighter import com.aemtools.lang.htl.icons.HtlIcons.HTL_FILE_ICON import com.aemtools.lang.htl.service.HtlDetectionService import com.intellij.openapi.fileTypes.FileTypeEditorHighlighterProviders import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.openapi.fileTypes.TemplateLanguageFileType import com.intellij.openapi.fileTypes.ex.FileTypeIdentifiableByVirtualFile import com.intellij.openapi.project.ProjectLocator import com.intellij.openapi.vfs.VirtualFile import javax.swing.Icon /** * @author Dmytro Troynikov */ object HtlFileType : LanguageFileType(HtlLanguage), TemplateLanguageFileType, FileTypeIdentifiableByVirtualFile { init { FileTypeEditorHighlighterProviders.INSTANCE.addExplicitExtension(this) { project, _, virtualFile, colors -> HtlTemplateHighlighter(project, virtualFile, colors) } } override fun isMyFileType(file: VirtualFile): Boolean { val project = ProjectLocator.getInstance().guessProjectForFile(file) if (file.isDirectory || project == null || file.extension != "html") { return false } val path = file.path return HtlDetectionService.isHtlFile(path, project) } override fun getIcon(): Icon = HTL_FILE_ICON override fun getName() = "HTL" override fun getDefaultExtension() = "htl" override fun getDescription() = "HTL File" }
gpl-3.0
e339e3d21759306fca3d6097a829d030
31.326087
113
0.780767
4.412463
false
false
false
false
zpao/buck
src/com/facebook/buck/multitenant/service/IndexBuilder.kt
1
9597
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.multitenant.service import com.facebook.buck.core.model.UnconfiguredBuildTarget import com.facebook.buck.core.path.ForwardRelativePath import com.facebook.buck.multitenant.fs.FsAgnosticPath import com.facebook.buck.util.json.ObjectMappers import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.NullNode import com.fasterxml.jackson.databind.node.ObjectNode import com.google.common.collect.ImmutableMap import java.io.InputStream import java.io.OutputStream /** * Read commit state from JSON and populate index with data * @return List of hashes of all commits processed */ fun populateIndexFromStream( indexAppender: IndexAppender, stream: InputStream, packageParser: (JsonNode) -> BuildPackage ): List<String> { val parser = ObjectMappers.createParser(stream) .enable(JsonParser.Feature.ALLOW_COMMENTS) .enable(JsonParser.Feature.ALLOW_TRAILING_COMMA) val result = mutableListOf<String>() // Loading a big JSON file with `readValueAsTree` is slow and very memory hungry. We use // a mixed approach - stream load JSON by reading token sequentially up to the package // definition and use `readValueAsTree` to load the package itself and transform it into // `BuildPackage`, allowing garbage collector to pick up JsonNode afterwards as we progress // with other packages. // Granularity can be improved by streaming each target individually if packages are too // big, at this moment it seems to be good enough. // top level data structure is an array of commits check(parser.nextToken() == JsonToken.START_ARRAY) while (parser.nextToken() != JsonToken.END_ARRAY) { check(parser.currentToken == JsonToken.START_OBJECT) var commit: String? = null val added = mutableListOf<BuildPackage>() val modified = mutableListOf<BuildPackage>() val removed = mutableListOf<ForwardRelativePath>() while (parser.nextToken() != JsonToken.END_OBJECT) { // commit data is defined with 4 possible fields: commit, added, modified, removed // 'added' and 'modified' contain a list of packages // 'removed' contain a list of paths denoting removed packages check(parser.currentToken == JsonToken.FIELD_NAME) when (val fieldName = parser.currentName()) { "commit" -> { check(parser.nextToken() == JsonToken.VALUE_STRING) commit = parser.valueAsString } "added" -> parsePackages(parser, added, packageParser) "modified" -> parsePackages(parser, modified, packageParser) "removed" -> parsePaths(parser, removed) else -> throw IllegalStateException("Unrecognized field $fieldName") } } val commitRequired = requireNotNull(commit) indexAppender.addCommitData(commitRequired, BuildPackageChanges(added, modified, removed)) result.add(commitRequired) } return result } /** * Read packages from JSON */ fun parsePackagesFromStream( stream: InputStream, packageParser: (JsonNode) -> BuildPackage ): MutableList<BuildPackage> { val parser = createParser(stream) val packages = mutableListOf<BuildPackage>() parsePackages(parser, packages, packageParser) return packages } /** * Write packages to JSON */ fun serializePackagesToStream(packages: List<BuildPackage>, stream: OutputStream) { ObjectMappers.WRITER.without(JsonGenerator.Feature.AUTO_CLOSE_TARGET) .writeValue(stream, packages) } /** * Write paths to JSON */ fun serializePathsToStream(paths: List<ForwardRelativePath>, stream: OutputStream) { ObjectMappers.WRITER.without(JsonGenerator.Feature.AUTO_CLOSE_TARGET).writeValue(stream, paths) } private fun createParser(stream: InputStream): JsonParser { return ObjectMappers.createParser(stream) .enable(JsonParser.Feature.ALLOW_COMMENTS) .enable(JsonParser.Feature.ALLOW_TRAILING_COMMA) } private fun parsePaths(parser: JsonParser, list: MutableList<ForwardRelativePath>) { check(parser.nextToken() == JsonToken.START_ARRAY) val removeNode = parser.readValueAsTree<JsonNode>() // 'removeNode' is an Array node, iterating through which gives paths of removed packages if (removeNode !is NullNode) { list.addAll(removeNode.map { p -> FsAgnosticPath.of(p.asText()) }) } } private fun parsePackages( parser: JsonParser, list: MutableList<BuildPackage>, packageParser: (JsonNode) -> BuildPackage ) { check(parser.nextToken() == JsonToken.START_ARRAY) while (parser.nextToken() != JsonToken.END_ARRAY) { val packageNode = parser.readValueAsTree<JsonNode>() // 'removeNode' is an Object which is a fully parsed package node // with the same structure as UnconfiguredTargetNodeWithDepsPackage if (packageNode !is NullNode) { list.add(packageParser(packageNode)) } } } /** * Convert Json produced by multitenant service to [BuildPackage] */ fun multitenantJsonToBuildPackageParser(nodes: JsonNode): BuildPackage { return ObjectMappers.READER_INTERNED.forType(BuildPackage::class.java).readValue(nodes) } /** * Convert Json produced by BUCK to [BuildPackage] */ fun buckJsonToBuildPackageParser(nodes: JsonNode): BuildPackage { val path = FsAgnosticPath.of(nodes.toText("path")) val rules = nodes.get("nodes").fields().asSequence().map { (name, rule) -> var ruleType: String? = null val deps = mutableSetOf<String>() val attrs = ImmutableMap.builder<String, Any>() for (field in rule.fields()) { when (field.key) { "attributes" -> { for (attr in field.value.fields()) { attrs.put(attr.key.intern(), normalizeJsonValue(attr.value)) if (attr.key == "buck.type") { ruleType = attr.value.asText() } } } "deps" -> deps.addAll(field.value.asSequence().map { it.asText() }) } } requireNotNull(ruleType) val buildTarget = BuildTargets.createBuildTargetFromParts(path, name) val depsAsTargets = deps.map { BuildTargets.parseOrThrow(it) }.toSet() createRawRule(buildTarget, ruleType, depsAsTargets, attrs.build()) }.toSet() val errors = nodes.mapIterable("errors") { error -> BuildPackageParsingError(error.toText("message"), error.mapIterable("stacktrace") { it.asText() }?.toList() ?: listOf()) }?.toList() ?: listOf() val includes = nodes.mapIterable("includes") { FsAgnosticPath.of(it.asText()) }?.toHashSet() ?: hashSetOf() return BuildPackage( buildFileDirectory = path, rules = rules, errors = errors, includes = includes ) } private fun JsonNode.toText(nodeName: String): String { return get(nodeName).asText() } private fun <R> JsonNode.mapIterable( iterableNodeName: String, transform: (JsonNode) -> R ): Sequence<R>? { return get(iterableNodeName)?.elements()?.asSequence()?.map(transform) } /** * Parse Json object into a primitive type object * Maps and arrays are parsed recursively * All strings are interned */ fun normalizeJsonValue(value: JsonNode): Any { // Note that if we need to support other values, such as null or Object, we will add support for // them as needed. // We intern all the strings here. It is not very well measured the impact of interning here // as those strings are attribute values and cardinality of those is not well known. We still // intern because it is only used during loading the data for multitenant service and thus // cheap to do. This could be reconsidered later. return when { value.isBoolean -> value.asBoolean() value.isTextual -> value.asText().intern() value.isInt -> value.asInt() value.isLong -> value.asLong() value.isDouble -> value.asDouble() value.isArray -> (value as ArrayNode).map { normalizeJsonValue(it) } value.isObject -> (value as ObjectNode).fields().asSequence().map { it.key.intern() to normalizeJsonValue(it.value) }.toMap() else -> value.asText().intern() } } private fun createRawRule( target: UnconfiguredBuildTarget, ruleType: String, deps: Set<UnconfiguredBuildTarget>, attrs: ImmutableMap<String, Any> ): RawBuildRule { val node = ServiceUnconfiguredTargetNode(target, RuleTypeFactory.createBuildRule(ruleType), attrs) return RawBuildRule(node, deps) }
apache-2.0
55382bbe97b10835993334067c619007
37.854251
102
0.681567
4.50775
false
false
false
false
allotria/intellij-community
platform/inspect/src/com/intellij/codeInspection/AsyncInspectionToolResultWriter.kt
1
2660
// 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.codeInspection import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.stream.JsonWriter import com.intellij.codeInspection.ex.InspectionProblemConsumer import com.intellij.codeInspection.ex.InspectionToolWrapper import com.intellij.codeInspection.ex.JsonInspectionsReportConverter import com.intellij.openapi.diagnostic.Logger import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import org.jdom.Element import java.io.Writer import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption internal const val asyncBufferCapacity = 1000 private val LOG = Logger.getInstance(AsyncInspectionToolResultWriter::class.java) open class AsyncInspectionToolResultWriter(val outputPath: Path) : InspectionProblemConsumer { val channel: Channel<Pair<String, Element>> = Channel(asyncBufferCapacity) init { GlobalScope.runWriteJob() } private fun CoroutineScope.runWriteJob(): Job { return launch(Dispatchers.IO) { LOG.info("Async result writer started") val writers = mutableMapOf<String, JsonResultWriter>() for ((inspectionId, element) in channel) { val resultWriter = writers.computeIfAbsent(inspectionId) { JsonResultWriter(it, outputPath) } resultWriter.writeElement(element) } writers.forEach { (_, writer) -> writer.stop() } LOG.info("Async result writer finished") } } override fun consume(element: Element, toolWrapper: InspectionToolWrapper<*, *>) { runBlocking(Dispatchers.IO) { channel.send(toolWrapper.shortName to element) } } fun close() { channel.close() } class JsonResultWriter(inspectionId: String, outputPath: Path) { val path: Path = outputPath.resolve("$inspectionId.json") val gson: Gson = GsonBuilder().setPrettyPrinting().create() val writer: Writer = Files.newBufferedWriter(path, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE, StandardOpenOption.WRITE) var first = true init { start() } fun start() { writer.write("{\"problems\":[\n") } fun writeElement(element: Element) { if (first) first = false else writer.write(",\n") val jsonWriter: JsonWriter = gson.newJsonWriter(writer) JsonInspectionsReportConverter.convertProblem(jsonWriter, element) jsonWriter.flush() } fun stop() { writer.write("\n]}") writer.close() } } }
apache-2.0
ca93b2892e34e7c9b696b61b10cb2c69
31.839506
140
0.718421
4.448161
false
false
false
false
allotria/intellij-community
platform/statistics/src/com/intellij/internal/statistic/utils/PluginInfoDetector.kt
1
6393
// 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.internal.statistic.utils import com.intellij.ide.plugins.PluginInfoProvider import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.Getter import com.intellij.openapi.util.TimeoutCachedValue import java.util.concurrent.TimeUnit /** * Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository, * so API from it may be reported */ fun getPluginInfo(clazz: Class<*>): PluginInfo { val classLoader = clazz.classLoader return when { classLoader is PluginAwareClassLoader -> { getPluginInfoByDescriptor(classLoader.pluginDescriptor) } PluginManagerCore.isRunningFromSources() && !PluginManagerCore.isUnitTestMode -> { builtFromSources } else -> { getPluginInfo(clazz.name) } } } fun getPluginInfo(className: String): PluginInfo { if (className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("kotlin.") || className.startsWith("groovy.")) { return platformPlugin } val plugin = PluginManagerCore.getPluginDescriptorOrPlatformByClassName(className) ?: return unknownPlugin return getPluginInfoByDescriptor(plugin) } /** * Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository, * so API from it may be reported. * * Use only if you don't have [PluginDescriptor]. */ fun getPluginInfoById(pluginId: PluginId?): PluginInfo { if (pluginId == null) { return unknownPlugin } val plugin = PluginManagerCore.getPlugin(pluginId) @Suppress("FoldInitializerAndIfToElvis") if (plugin == null) { // we can't load plugin descriptor for a not installed plugin but we can check if it's from JB repo return if (isPluginFromOfficialJbPluginRepo(pluginId)) PluginInfo(PluginType.LISTED, pluginId.idString, null) else unknownPlugin } return getPluginInfoByDescriptor(plugin) } /** * Returns if this code is coming from IntelliJ platform, a plugin created by JetBrains (bundled or not) or from official repository, * so API from it may be reported */ fun getPluginInfoByDescriptor(plugin: PluginDescriptor): PluginInfo { if (PluginManagerCore.CORE_ID == plugin.pluginId) { return platformPlugin } val id = plugin.pluginId.idString val version = plugin.version if (PluginManager.getInstance().isDevelopedByJetBrains(plugin)) { val pluginType = when { plugin.isBundled -> PluginType.JB_BUNDLED PluginManagerCore.isUpdatedBundledPlugin(plugin) -> PluginType.JB_UPDATED_BUNDLED else -> PluginType.JB_NOT_BUNDLED } return PluginInfo(pluginType, id, version) } // only plugins installed from some repository (not bundled and not provided via classpath in development IDE instance - // they are also considered bundled) would be reported val listed = !plugin.isBundled && !PluginManagerCore.isUpdatedBundledPlugin(plugin) && isSafeToReportFrom(plugin) return if (listed) PluginInfo(PluginType.LISTED, id, version) else notListedPlugin } enum class PluginType { PLATFORM, JB_BUNDLED, JB_NOT_BUNDLED, LISTED, NOT_LISTED, UNKNOWN, FROM_SOURCES, JB_UPDATED_BUNDLED; fun isPlatformOrJetBrainsBundled(): Boolean { return this == PLATFORM || this == JB_BUNDLED || this == FROM_SOURCES || this == JB_UPDATED_BUNDLED } fun isDevelopedByJetBrains(): Boolean { return isPlatformOrJetBrainsBundled() || this == JB_NOT_BUNDLED } fun isSafeToReport(): Boolean { return isDevelopedByJetBrains() || this == LISTED } } fun findPluginTypeByValue(value: String): PluginType? { for (type in PluginType.values()) { if (type.name == value) { return type } } return null } data class PluginInfo(val type: PluginType, val id: String?, val version: String?) { /** * @return true if code is from IntelliJ platform or JB plugin. */ fun isDevelopedByJetBrains() = type.isDevelopedByJetBrains() /** * @return true if code is from IntelliJ platform, JB plugin or plugin from JB plugin repository. */ fun isSafeToReport() = type.isSafeToReport() } val platformPlugin: PluginInfo = PluginInfo(PluginType.PLATFORM, null, null) val unknownPlugin: PluginInfo = PluginInfo(PluginType.UNKNOWN, null, null) private val notListedPlugin = PluginInfo(PluginType.NOT_LISTED, null, null) // Mock plugin info used when we can't detect plugin by class loader because IDE is built from sources val builtFromSources: PluginInfo = PluginInfo(PluginType.FROM_SOURCES, null, null) private val pluginIdsFromOfficialJbPluginRepo: Getter<Set<PluginId>> = TimeoutCachedValue(1, TimeUnit.HOURS) { // before loading default repository plugins lets check it's not changed, and is really official JetBrains repository val infoProvider = PluginInfoProvider.getInstance() infoProvider.loadCachedPlugins() ?: emptySet<PluginId?>().also { infoProvider.loadPlugins(null) } // schedule plugins loading, report nothing until repo plugins loaded } /** * Checks this plugin is created by JetBrains or from official repository, so API from it may be reported */ private fun isSafeToReportFrom(descriptor: PluginDescriptor): Boolean { return when { PluginManager.getInstance().isDevelopedByJetBrains(descriptor) -> true descriptor.isBundled -> false // bundled, but not from JetBrains, so, some custom unknown plugin else -> descriptor.pluginId?.let { isPluginFromOfficialJbPluginRepo(it) } ?: false // only plugins installed from some repository (not bundled and not provided via classpath in development IDE instance - they are also considered bundled) would be reported } } private fun isPluginFromOfficialJbPluginRepo(pluginId: PluginId?): Boolean { // not official JetBrains repository - is used, so, not safe to report return if (ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()) pluginIdsFromOfficialJbPluginRepo.get().contains(pluginId) else false }
apache-2.0
8160aaf28d1d940592e1d81e0a723d2e
39.468354
176
0.757391
4.563169
false
false
false
false
leafclick/intellij-community
plugins/git4idea/src/git4idea/branch/GitRebaseParams.kt
1
2685
// 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 git4idea.branch import git4idea.config.GitVersion import git4idea.config.GitVersionSpecialty import git4idea.rebase.GitRebaseEditorHandler class GitRebaseParams private constructor(private val version: GitVersion, branch: String?, newBase: String?, val upstream: String, val interactive: Boolean, private val preserveMerges: Boolean, private val autoSquash: AutoSquashOption, val editorHandler: GitRebaseEditorHandler? = null) { companion object { fun editCommits(version: GitVersion, base: String, editorHandler: GitRebaseEditorHandler?, preserveMerges: Boolean, autoSquash: AutoSquashOption = AutoSquashOption.DEFAULT): GitRebaseParams = GitRebaseParams(version, null, null, base, true, preserveMerges, autoSquash, editorHandler) } enum class AutoSquashOption { DEFAULT, ENABLE, DISABLE } val branch: String? = branch?.takeIf { it.isNotBlank() } val newBase: String? = newBase?.takeIf { it.isNotBlank() } constructor(version: GitVersion, upstream: String) : this(version, null, null, upstream, false, false) constructor(version: GitVersion, branch: String?, newBase: String?, upstream: String, interactive: Boolean, preserveMerges: Boolean) : this(version, branch, newBase, upstream, interactive, preserveMerges, AutoSquashOption.DEFAULT) fun asCommandLineArguments(): List<String> = mutableListOf<String>().apply { if (interactive) { add("--interactive") } if (preserveMerges) { if (GitVersionSpecialty.REBASE_MERGES_REPLACES_PRESERVE_MERGES.existsIn(version)) { add("--rebase-merges") } else { add("--preserve-merges") } } when (autoSquash) { AutoSquashOption.DEFAULT -> { } AutoSquashOption.ENABLE -> add("--autosquash") AutoSquashOption.DISABLE -> add("--no-autosquash") } if (newBase != null) { addAll(listOf("--onto", newBase)) } add(upstream) if (branch != null) { add(branch) } } fun isInteractive(): Boolean = interactive override fun toString(): String = asCommandLineArguments().joinToString(" ") }
apache-2.0
9bc9d61e52974c6a26d0150585805b96
35.794521
140
0.594786
4.981447
false
false
false
false
leafclick/intellij-community
plugins/devkit/devkit-core/src/inspections/StatefulEpInspection.kt
1
3360
// 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 org.jetbrains.idea.devkit.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.lang.jvm.DefaultJvmElementVisitor import com.intellij.lang.jvm.JvmClass import com.intellij.lang.jvm.JvmField import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.types.JvmReferenceType import com.intellij.lang.jvm.util.JvmInheritanceUtil.isInheritor import com.intellij.lang.jvm.util.JvmUtil import com.intellij.openapi.components.ProjectComponent import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.xml.XmlTag import com.intellij.util.SmartList import org.jetbrains.idea.devkit.util.processExtensionsByClassName class StatefulEpInspection : DevKitJvmInspection() { override fun buildVisitor(project: Project, sink: HighlightSink, isOnTheFly: Boolean): DefaultJvmElementVisitor<Boolean?> = object : DefaultJvmElementVisitor<Boolean?> { override fun visitField(field: JvmField): Boolean? { val clazz = field.containingClass ?: return null val fieldTypeClass = JvmUtil.resolveClass(field.type as? JvmReferenceType) ?: return null val isQuickFix by lazy(LazyThreadSafetyMode.NONE) { isInheritor(clazz, localQuickFixFqn) } val targets = findEpCandidates(project, clazz) if (targets.isEmpty() && !isQuickFix) { return null } if (isInheritor(fieldTypeClass, PsiElement::class.java.canonicalName)) { sink.highlight( "Potential memory leak: don't hold PsiElement, use SmartPsiElementPointer instead${if (isQuickFix) "; also see LocalQuickFixOnPsiElement" else ""}" ) return false } if (isInheritor(fieldTypeClass, PsiReference::class.java.canonicalName)) { sink.highlight(message(PsiReference::class.java.simpleName, isQuickFix)) return false } if (!isProjectFieldAllowed(field, clazz, targets) && isInheritor(fieldTypeClass, Project::class.java.canonicalName)) { sink.highlight(message(Project::class.java.simpleName, isQuickFix)) return false } return false } } } private val localQuickFixFqn = LocalQuickFix::class.java.canonicalName private val projectComponentFqn = ProjectComponent::class.java.canonicalName private fun findEpCandidates(project: Project, clazz: JvmClass): Collection<XmlTag> { val name = clazz.name ?: return emptyList() val result = SmartList<XmlTag>() processExtensionsByClassName(project, name) { tag, _ -> val forClass = tag.getAttributeValue("forClass") if (forClass == null || !forClass.contains(name)) { result.add(tag) } true } return result } private fun isProjectFieldAllowed(field: JvmField, clazz: JvmClass, targets: Collection<XmlTag>): Boolean { if (field.hasModifier(JvmModifier.FINAL)) { return true } return targets.any { candidate -> val name = candidate.name "projectService" == name || "projectConfigurable" == name } || isInheritor(clazz, projectComponentFqn) } private fun message(what: String, quickFix: Boolean): String { val where = if (quickFix) "quick fix" else "extension" return "Don't use $what as a field in $where" }
apache-2.0
277a4404d5dc0b5cb6bb4958cad7d31f
38.069767
171
0.744048
4.432718
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/call/simpleTopLevelFunctions.kt
2
680
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT fun String.foo(): Int = length var state = "Fail" fun bar(result: String) { state = result } fun box(): String { val f = (String::foo).call("abc") if (f != 3) return "Fail: $f" try { (String::foo).call() return "Fail: IllegalArgumentException should have been thrown" } catch (e: IllegalArgumentException) {} try { (String::foo).call(42) return "Fail: IllegalArgumentException should have been thrown" } catch (e: IllegalArgumentException) {} (::bar).call("OK") return state }
apache-2.0
019e5dd59e7e4683ea0718aa91498b75
20.25
72
0.616176
3.820225
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/safeCall/kt247.kt
5
653
fun t1() : Boolean { val s1 : String? = "sff" val s2 : String? = null return s1?.length == 3 && s2?.length == null } fun t2() : Boolean { val c1: C? = C(1) val c2: C? = null return c1?.x == 1 && c2?.x == null } fun t3() { val d: D = D("s") val x = d?.s if (!(d?.s == "s")) throw AssertionError() } fun t4() { val e: E? = E() if (!(e?.bar() == e)) throw AssertionError() val x = e?.foo() } fun box() : String { if(!t1 ()) return "fail" if(!t2 ()) return "fail" t3() t4() return "OK" } class C(val x: Int) class D(val s: String) class E() { fun foo() = 1 fun bar() = this }
apache-2.0
2fcf25740d5aa53966791ea8f375c77e
16.184211
48
0.468606
2.570866
false
false
false
false
mpcjanssen/simpletask-android
app/src/encrypted/java/nl/mpcjanssen/simpletask/remote/FileStore.kt
1
11868
package nl.mpcjanssen.simpletask.remote import android.Manifest import android.content.pm.PackageManager import android.os.* import androidx.core.content.ContextCompat import android.util.Log import android.widget.Toast import androidx.annotation.RequiresApi import nl.mpcjanssen.simpletask.R import nl.mpcjanssen.simpletask.Simpletask import nl.mpcjanssen.simpletask.TodoApplication import nl.mpcjanssen.simpletask.util.broadcastAuthFailed import nl.mpcjanssen.simpletask.util.join import nl.mpcjanssen.simpletask.util.writeToFile import other.de.stanetz.jpencconverter.JavaPasswordbasedCryption import other.de.stanetz.jpencconverter.JavaPasswordbasedCryption.EncryptionFailedException import other.de.stanetz.jpencconverter.PasswordStore import other.net.gsantner.opoc.util.MFileUtils import java.io.File import java.io.FileInputStream import java.io.FileNotFoundException import java.io.FilenameFilter import java.lang.IllegalArgumentException import java.nio.charset.StandardCharsets import java.security.SecureRandom import java.util.* import kotlin.reflect.KClass object FileStore : IFileStore { private var lastSeenRemoteId by TodoApplication.config.StringOrNullPreference(R.string.file_current_version_id) @RequiresApi(api = Build.VERSION_CODES.M) fun getDefaultPassword(): CharArray? { return PasswordStore(TodoApplication.app).loadKey(R.string.pref_key__default_encryption_password) } @RequiresApi(api = Build.VERSION_CODES.M) fun isDefaultPasswordSet(): Boolean { val key = getDefaultPassword() return key != null && key.isNotEmpty() } @RequiresApi(api = Build.VERSION_CODES.M) fun setDefaultPassword(password: String?) { PasswordStore(TodoApplication.app).storeKey( password, R.string.pref_key__default_encryption_password ) } override val isOnline = true private const val TAG = "FileStore" private var observer: TodoObserver? = null init { Log.i(TAG, "onCreate") Log.i(TAG, "Default path: ${getDefaultFile().path}") observer = null } override val isEncrypted: Boolean get() = true val isAuthenticated: Boolean get() { val permissionCheck = ContextCompat.checkSelfPermission(TodoApplication.app, Manifest.permission.WRITE_EXTERNAL_STORAGE) return permissionCheck == PackageManager.PERMISSION_GRANTED } @RequiresApi(Build.VERSION_CODES.M) override fun loadTasksFromFile(file: File): List<String> { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return emptyList() } Log.i(TAG, "Loading tasks") val lines = readEncrypted(file).split("\n") Log.i(TAG, "Read ${lines.size} lines from $file") setWatching(file) lastSeenRemoteId = file.lastModified().toString() return lines } override fun needSync(file: File): Boolean { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return true } return lastSeenRemoteId != file.lastModified().toString() } override fun todoNameChanged() { lastSeenRemoteId = "" } @RequiresApi(Build.VERSION_CODES.M) override fun writeFile(file: File, contents: String) { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return } writeEncryptedToFile(file, contents) } @RequiresApi(Build.VERSION_CODES.M) override fun readFile(file: File, fileRead: (contents: String) -> Unit) { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return } Log.i(TAG, "Reading file: ${file.path}") val contents: String = readEncrypted(file) fileRead(contents) } @RequiresApi(Build.VERSION_CODES.M) fun readEncrypted(file: File): String { val content: String val pw = getPasswordWithWarning() if (isEncrypted(file) && pw != null) { content = try { val encryptedContext: ByteArray = MFileUtils.readCloseStreamWithSize( FileInputStream(file), file.length().toInt() ) if (encryptedContext.size > JavaPasswordbasedCryption.Version.NAME_LENGTH) { JavaPasswordbasedCryption.getDecryptedText(encryptedContext, pw) } else { String(encryptedContext, StandardCharsets.UTF_8) } } catch (e: FileNotFoundException) { // TODO error log "" } catch (e: EncryptionFailedException) { // TODO error log "" } catch (e: IllegalArgumentException) { // TODO error log "" } } else { //TODO log its not encrypted content = join(file.readLines(), "\n") // same as cloudless for plain txt files } return content } override fun loginActivity(): KClass<*>? { return LoginScreen::class } private fun setWatching(file: File) { Log.i(TAG, "Observer: adding folder watcher on ${file.parent}") val obs = observer if (obs != null && file.canonicalPath == obs.fileName) { Log.w(TAG, "Observer: already watching: ${file.canonicalPath}") return } else if (obs != null) { Log.w(TAG, "Observer: already watching different path: ${obs.fileName}") obs.ignoreEvents(true) obs.stopWatching() observer = null } observer = TodoObserver(file) Log.i(TAG, "Observer: modifying done") } @RequiresApi(Build.VERSION_CODES.M) override fun saveTasksToFile(file: File, lines: List<String>, eol: String) : File { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return file } Log.i(TAG, "Saving tasks to file: ${file.path}") val obs = observer obs?.ignoreEvents(true) writeEncryptedToFile(file, lines, eol) obs?.delayedStartListen(1000) lastSeenRemoteId = file.lastModified().toString() return file } private fun isEncrypted(file: File): Boolean { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && file.name.endsWith( JavaPasswordbasedCryption.DEFAULT_ENCRYPTION_EXTENSION ) } @RequiresApi(api = Build.VERSION_CODES.M) private fun getPasswordWithWarning(): CharArray? { val pw: CharArray? = getDefaultPassword() if (pw == null || pw.isEmpty()) { val warningText = "No password!" // Toast.makeText(context, warningText, Toast.LENGTH_LONG).show() // TODO Log.w(TAG, warningText) return null } return pw } @RequiresApi(Build.VERSION_CODES.M) fun writeEncryptedToFile(file: File, lines: List<String>, eol: String) { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return } val content = lines.joinToString(eol) writeEncryptedToFile(file, content) } @RequiresApi(Build.VERSION_CODES.M) fun writeEncryptedToFile(file: File, content: String) { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return } Log.i(TAG, "Writing file to ${file.canonicalPath}") try { val pw = getPasswordWithWarning() val contentAsBytes: ByteArray = if (isEncrypted(file) && pw != null) { JavaPasswordbasedCryption( Build.VERSION.SDK_INT, SecureRandom() ).encrypt(content, pw) } else { // TODO log not encrypting content.toByteArray() } writeToFile(contentAsBytes, file) } catch (e: EncryptionFailedException) { Log.w(TAG, "Failed to encrypt! $e") } } @RequiresApi(Build.VERSION_CODES.M) override fun appendTaskToFile(file: File, lines: List<String>, eol: String) { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return } Log.i(TAG, "Appending ${lines.size} tasks to ${file.path}") val oldLines = readEncrypted(file).split(eol) val appended = oldLines + lines writeEncryptedToFile(file, appended, eol) } override fun logout() { } override fun getDefaultFile(): File { return File(TodoApplication.app.getExternalFilesDir(null), "todo.txt" + JavaPasswordbasedCryption.DEFAULT_ENCRYPTION_EXTENSION) } override fun loadFileList(file: File, txtOnly: Boolean): List<FileEntry> { if (!isAuthenticated) { broadcastAuthFailed(TodoApplication.app.localBroadCastManager) return emptyList() } val result = ArrayList<FileEntry>() if (file.canonicalPath == "/") { TodoApplication.app.getExternalFilesDir(null)?.let { result.add(FileEntry(it, true)) } } val filter = FilenameFilter { dir, filename -> val sel = File(dir,filename) if (!sel.canRead()) false else { if (sel.isDirectory) { result.add(FileEntry(File(filename), true)) } else { !txtOnly || filename.toLowerCase(Locale.getDefault()).endsWith(".txt") result.add(FileEntry(File(filename), false)) } } } // Run the file applyFilter for side effects file.list(filter) return result } class TodoObserver(val file: File) : FileObserver(file.canonicalPath) { private val tag = "FileWatchService" val fileName : String = file.canonicalPath private var ignoreEvents: Boolean = false private val handler: Handler private val delayedEnable = Runnable { Log.i(tag, "Observer: Delayed enabling events for: $fileName ") ignoreEvents(false) } init { this.startWatching() Log.i(tag, "Observer: creating observer on: $fileName") this.ignoreEvents = false this.handler = Handler(Looper.getMainLooper()) } fun ignoreEvents(ignore: Boolean) { Log.i(tag, "Observer: observing events on $fileName? ignoreEvents: $ignore") this.ignoreEvents = ignore } override fun onEvent(event: Int, eventPath: String?) { if (eventPath != null && eventPath == fileName) { Log.d(tag, "Observer event: $fileName:$event") if (event == CLOSE_WRITE || event == MODIFY || event == MOVED_TO) { if (ignoreEvents) { Log.i(tag, "Observer: ignored event on: $fileName") } else { Log.i(tag, "File changed {}$fileName") FileStore.remoteTodoFileChanged() } } } } fun delayedStartListen(ms: Int) { // Cancel any running timers handler.removeCallbacks(delayedEnable) // Reschedule Log.i(tag, "Observer: Adding delayed enabling to todoQueue") handler.postDelayed(delayedEnable, ms.toLong()) } } }
gpl-3.0
f6e2b7085bfc8275ddd5d58acf40992e
34.216617
135
0.603387
4.717011
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/dependency/analyzer/GradleDependencyAnalyzerGoToAction.kt
1
1361
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.dependency.analyzer import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerDependency import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerView import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import org.jetbrains.plugins.gradle.util.GradleConstants class GradleDependencyAnalyzerGoToAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { logger<GradleDependencyAnalyzerGoToAction>().error("TODO: GradleDependencyAnalyzerGoToAction") } override fun update(e: AnActionEvent) { val systemId = e.getData(DependencyAnalyzerView.EXTERNAL_SYSTEM_ID) val dependency = e.getData(DependencyAnalyzerView.DEPENDENCY) e.presentation.isEnabledAndVisible = systemId == GradleConstants.SYSTEM_ID && dependency?.data is DependencyAnalyzerDependency.Data.Artifact } init { templatePresentation.icon = null templatePresentation.text = ExternalSystemBundle.message("external.system.dependency.analyzer.go.to", "build.gradle") } }
apache-2.0
f020c69f380855a805a75fd486fc1761
45.965517
121
0.815577
4.809187
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/highlighting/highlightUsages.kt
10
5589
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:ApiStatus.Internal package com.intellij.codeInsight.highlighting import com.intellij.find.FindManager import com.intellij.find.findUsages.FindUsagesHandler import com.intellij.find.impl.FindManagerImpl import com.intellij.find.usages.api.* import com.intellij.find.usages.impl.AllSearchOptions import com.intellij.find.usages.impl.buildQuery import com.intellij.find.usages.impl.symbolSearchTarget import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.model.Symbol import com.intellij.model.psi.PsiSymbolService import com.intellij.model.psi.impl.targetSymbols import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiReference import com.intellij.psi.impl.source.tree.injected.InjectedLanguageEditorUtil import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.annotations.ApiStatus internal fun highlightUsages(project: Project, editor: Editor, file: PsiFile): Boolean { val allTargets = targetSymbols(file, editor.caretModel.offset) if (allTargets.isEmpty()) { return false } val clearHighlights = HighlightUsagesHandler.isClearHighlights(editor) for (symbol in allTargets) { highlightSymbolUsages(project, editor, file, symbol, clearHighlights) } return true } private fun highlightSymbolUsages(project: Project, editor: Editor, file: PsiFile, symbol: Symbol, clearHighlights: Boolean) { val hostEditor = InjectedLanguageEditorUtil.getTopLevelEditor(editor) val (readRanges, writeRanges, readDeclarationRanges, writeDeclarationRanges) = getUsageRanges(file, symbol) ?: return HighlightUsagesHandler.highlightUsages( project, hostEditor, readRanges + readDeclarationRanges, writeRanges + writeDeclarationRanges, clearHighlights ) HighlightUsagesHandler.setStatusText(project, null, readRanges.size + writeRanges.size, clearHighlights) } internal fun getUsageRanges(file: PsiFile, symbol: Symbol): UsageRanges? { val psiTarget: PsiElement? = PsiSymbolService.getInstance().extractElementFromSymbol(symbol) if (psiTarget != null) { return getPsiUsageRanges(file, psiTarget) } else { return getSymbolUsageRanges(file, symbol) } } private fun getPsiUsageRanges(file: PsiFile, psiTarget: PsiElement): UsageRanges { val readRanges = ArrayList<TextRange>() val writeRanges = ArrayList<TextRange>() val readDeclarationRanges = ArrayList<TextRange>() val writeDeclarationRanges = ArrayList<TextRange>() val project = file.project val hostFile: PsiFile = psiTarget.containingFile?.let { targetContainingFile -> val injectedManager = InjectedLanguageManager.getInstance(project) if (injectedManager.isInjectedFragment(file) != injectedManager.isInjectedFragment(targetContainingFile)) { // weird case when injected symbol references host file injectedManager.getTopLevelFile(file) } else { null } } ?: file val searchScope: SearchScope = LocalSearchScope(hostFile) val detector: ReadWriteAccessDetector? = ReadWriteAccessDetector.findDetector(psiTarget) val oldHandler: FindUsagesHandler? = (FindManager.getInstance(project) as FindManagerImpl) .findUsagesManager .getFindUsagesHandler(psiTarget, true) val refs = oldHandler?.findReferencesToHighlight(psiTarget, searchScope) ?: ReferencesSearch.search(psiTarget, searchScope).findAll() for (ref: PsiReference in refs) { val write: Boolean = detector != null && detector.getReferenceAccess(psiTarget, ref) != ReadWriteAccessDetector.Access.Read HighlightUsagesHandler.collectHighlightRanges(ref, if (write) writeRanges else readRanges) } val declRange = HighlightUsagesHandler.getNameIdentifierRange(hostFile, psiTarget) if (declRange != null) { val write = detector != null && detector.isDeclarationWriteAccess(psiTarget) if (write) { writeDeclarationRanges.add(declRange) } else { readDeclarationRanges.add(declRange) } } return UsageRanges(readRanges, writeRanges, readDeclarationRanges, writeDeclarationRanges) } private fun getSymbolUsageRanges(file: PsiFile, symbol: Symbol): UsageRanges? { val project: Project = file.project val searchTarget = symbolSearchTarget(project, symbol) ?: return null return getSearchTargetUsageRanges(project, file, searchTarget, searchTarget.usageHandler) } private fun <O> getSearchTargetUsageRanges( project: Project, file: PsiFile, searchTarget: SearchTarget, usageHandler: UsageHandler<O> ): UsageRanges { val searchScope = LocalSearchScope(file) val usages: Collection<Usage> = buildQuery(project, searchTarget, usageHandler, AllSearchOptions( options = UsageOptions.createOptions(searchScope), textSearch = true, customOptions = usageHandler.getCustomOptions(UsageHandler.UsageAction.HIGHLIGHT_USAGES) )).findAll() val readRanges = ArrayList<TextRange>() val readDeclarationRanges = ArrayList<TextRange>() for (usage in usages) { if (usage !is PsiUsage) { continue } HighlightUsagesHandler.collectHighlightRanges(usage.file, usage.range, if (usage.declaration) readDeclarationRanges else readRanges) } return UsageRanges(readRanges, emptyList(), readDeclarationRanges, emptyList()) }
apache-2.0
f766aecc31846b0e45d2d763a67ea3ba
41.022556
140
0.786008
4.400787
false
false
false
false
mdaniel/intellij-community
platform/configuration-store-impl/src/ProjectStoreBase.kt
1
11125
// 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.configurationStore import com.intellij.ide.highlighter.ProjectFileType import com.intellij.ide.highlighter.WorkspaceFileType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.appSystemDir import com.intellij.openapi.components.* import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectCoreUtil import com.intellij.openapi.project.doGetProjectFileName import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.project.ex.ProjectNameProvider import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.SmartList import com.intellij.util.io.Ksuid import com.intellij.util.io.systemIndependentPath import com.intellij.util.messages.MessageBus import com.intellij.util.text.nullize import org.jetbrains.annotations.NonNls import java.nio.file.Files import java.nio.file.Path import java.util.* @NonNls internal const val PROJECT_FILE = "\$PROJECT_FILE$" @NonNls internal const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$" internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false) private val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true) // cannot be `internal`, used in Upsource abstract class ProjectStoreBase(final override val project: Project) : ComponentStoreWithExtraComponents(), IProjectStore { private var dirOrFile: Path? = null private var dotIdea: Path? = null internal fun getNameFile(): Path { for (projectNameProvider in ProjectNameProvider.EP_NAME.iterable) { LOG.runAndLogException { projectNameProvider.getNameFile(project)?.let { return it } } } return directoryStorePath!!.resolve(ProjectEx.NAME_FILE) } final override var loadPolicy = StateLoadPolicy.LOAD final override fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD final override fun getStorageScheme() = if (dotIdea == null) StorageScheme.DEFAULT else StorageScheme.DIRECTORY_BASED abstract override val storageManager: StateStorageManagerImpl protected val isDirectoryBased: Boolean get() = dotIdea != null final override fun setOptimiseTestLoadSpeed(value: Boolean) { loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD } final override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE) final override fun getWorkspacePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE) final override fun clearStorages() = storageManager.clearStorages() private fun loadProjectFromTemplate(defaultProject: Project) { val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return LOG.runAndLogException { val dotIdea = dotIdea if (dotIdea != null) { normalizeDefaultProjectElement(defaultProject, element, dotIdea) } else { moveComponentConfiguration(defaultProject, element, storagePathResolver = { /* doesn't matter, any path will be resolved as projectFilePath (see fileResolver below) */ PROJECT_FILE }) { if (it == "workspace.xml") { workspacePath } else { dirOrFile!! } } } } } final override fun getProjectBasePath(): Path { val path = dirOrFile ?: throw IllegalStateException("setPath was not yet called") if (isDirectoryBased) { val useParent = System.getProperty("store.basedir.parent.detection", "true").toBoolean() && (path.fileName?.toString()?.startsWith("${Project.DIRECTORY_STORE_FOLDER}.") ?: false) return if (useParent) path.parent.parent else path } else { return path.parent } } override fun getPresentableUrl(): String { if (isDirectoryBased) { return (dirOrFile ?: throw IllegalStateException("setPath was not yet called")).systemIndependentPath } else { return projectFilePath.systemIndependentPath } } override fun getProjectWorkspaceId() = ProjectIdManager.getInstance(project).state.id override fun setPath(file: Path, isRefreshVfsNeeded: Boolean, template: Project?) { dirOrFile = file val storageManager = storageManager val isUnitTestMode = ApplicationManager.getApplication().isUnitTestMode val macros = ArrayList<Macro>(5) if (file.toString().endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) { macros.add(Macro(PROJECT_FILE, file)) val workspacePath = file.parent.resolve("${file.fileName.toString().removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}") macros.add(Macro(StoragePathMacros.WORKSPACE_FILE, workspacePath)) if (isUnitTestMode) { // we don't load default state in tests as app store does because // 1) we should not do it // 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations) // load state only if there are existing files val componentStoreLoadingEnabled = project.getUserData(IProjectStore.COMPONENT_STORE_LOADING_ENABLED) if (if (componentStoreLoadingEnabled == null) !Files.exists(file) else !componentStoreLoadingEnabled) { loadPolicy = StateLoadPolicy.NOT_LOAD } macros.add(Macro(StoragePathMacros.PRODUCT_WORKSPACE_FILE, workspacePath)) } } else { val dotIdea = file.resolve(Project.DIRECTORY_STORE_FOLDER) this.dotIdea = dotIdea // PROJECT_CONFIG_DIR must be first macro macros.add(Macro(PROJECT_CONFIG_DIR, dotIdea)) macros.add(Macro(StoragePathMacros.WORKSPACE_FILE, dotIdea.resolve("workspace.xml"))) macros.add(Macro(PROJECT_FILE, dotIdea.resolve("misc.xml"))) if (isUnitTestMode) { // load state only if there are existing files isOptimiseTestLoadSpeed = !Files.exists(file) macros.add(Macro(StoragePathMacros.PRODUCT_WORKSPACE_FILE, dotIdea.resolve("product-workspace.xml"))) } } val presentableUrl = (if (dotIdea == null) file else projectBasePath) val cacheFileName = doGetProjectFileName(presentableUrl.systemIndependentPath, (presentableUrl.fileName ?: "") .toString().lowercase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION), ".", ".xml") macros.add(Macro(StoragePathMacros.CACHE_FILE, appSystemDir.resolve("workspace").resolve(cacheFileName))) storageManager.setMacros(macros) if (template != null) { loadProjectFromTemplate(template) } if (isUnitTestMode) { return } val productSpecificWorkspaceParentDir = PathManager.getConfigDir().resolve("workspace") val projectIdManager = ProjectIdManager.getInstance(project) var projectId = projectIdManager.state.id if (projectId == null) { // do not use project name as part of id, to ensure that project dir renaming also will not cause data loss projectId = Ksuid.generate() projectIdManager.state.id = projectId } macros.add(Macro(StoragePathMacros.PRODUCT_WORKSPACE_FILE, productSpecificWorkspaceParentDir.resolve("$projectId.xml"))) storageManager.setMacros(macros) } override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> { val storages = stateSpec.storages if (isDirectoryBased) { if (storages.size == 2 && ApplicationManager.getApplication().isUnitTestMode && isSpecialStorage(storages.first()) && storages[1].path == StoragePathMacros.WORKSPACE_FILE) { return listOf(storages.first()) } var result: MutableList<Storage>? = null for (storage in storages) { if (storage.path != PROJECT_FILE) { if (result == null) { result = SmartList() } result.add(storage) } } if (result.isNullOrEmpty()) { result = mutableListOf(PROJECT_FILE_STORAGE_ANNOTATION) } result.sortWith(deprecatedComparator) if (isDirectoryBased) { for (providerFactory in StreamProviderFactory.EP_NAME.getIterable(project)) { LOG.runAndLogException { // yes, DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION is not added in this case providerFactory.customizeStorageSpecs(component, storageManager, stateSpec, result!!, operation)?.let { return it } } } } // if we create project from default, component state written not to own storage file, but to project file, // we don't have time to fix it properly, so, ancient hack restored if (!isSpecialStorage(result.first())) { result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION) } return result } else { var result: MutableList<Storage>? = null // FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry var hasOnlyDeprecatedStorages = true for (storage in storages) { if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE || isSpecialStorage(storage)) { if (result == null) { result = SmartList() } result.add(storage) if (!storage.deprecated) { hasOnlyDeprecatedStorages = false } } } if (result.isNullOrEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { if (hasOnlyDeprecatedStorages) { result.add(PROJECT_FILE_STORAGE_ANNOTATION) } result.sortWith(deprecatedComparator) return result } } } override fun isProjectFile(file: VirtualFile): Boolean { if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file)) { return false } val filePath = file.path if (!isDirectoryBased) { return filePath == projectFilePath.systemIndependentPath || filePath == workspacePath.systemIndependentPath } return VfsUtilCore.isAncestorOrSelf(projectFilePath.parent.systemIndependentPath, file) } override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = dotIdea?.systemIndependentPath.nullize() final override fun getDirectoryStorePath() = dotIdea final override fun reloadStates(componentNames: Set<String>, messageBus: MessageBus) { runBatchUpdate(project) { reinitComponents(componentNames) } } } private fun isSpecialStorage(storage: Storage) = isSpecialStorage(storage.path) internal fun isSpecialStorage(collapsedPath: String): Boolean { return collapsedPath == StoragePathMacros.CACHE_FILE || collapsedPath == StoragePathMacros.PRODUCT_WORKSPACE_FILE }
apache-2.0
29d57e95c5449d5609de9f876d6b139b
39.458182
170
0.717034
5.03166
false
false
false
false
zdary/intellij-community
platform/built-in-server/src/org/jetbrains/ide/ToolboxUpdateNotificationHandler.kt
1
4491
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.ide import com.google.gson.JsonElement import com.google.gson.JsonObject import com.intellij.ide.IdeBundle import com.intellij.ide.actions.SettingsEntryPointAction import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeLater import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.Disposer import com.intellij.util.Consumer import com.intellij.util.concurrency.AppExecutorUtil import java.util.concurrent.TimeUnit internal data class UpdateNotification(val version: String, val build: String) private fun parseUpdateNotificationRequest(request: JsonElement): UpdateNotification { require(request.isJsonObject) { "JSON Object was expected" } val obj = request.asJsonObject val build = obj["build"]?.asString val version = obj["version"]?.asString require(!build.isNullOrBlank()) { "the `build` attribute must not be blank" } require(!version.isNullOrBlank()) { "the `version` attribute must not be blank" } return UpdateNotification(version = version, build = build) } internal class ToolboxUpdateNotificationHandler : ToolboxServiceHandler<UpdateNotification> { override val requestName: String = "update-notification" override fun parseRequest(request: JsonElement) = parseUpdateNotificationRequest(request) override fun handleToolboxRequest(lifetime: Disposable, request: UpdateNotification, onResult: (JsonElement) -> Unit) { val actionHandler = Consumer<AnActionEvent> { onResult(JsonObject().apply { addProperty("status", "accepted") }) } val title = IdeBundle.message("toolbox.updates.download.update.action.text", request.build, request.version) val description = IdeBundle.message("toolbox.updates.download.update.action.description", request.build, request.version) val action = DumbAwareAction.create(title, actionHandler) action.templatePresentation.description = description action.templatePresentation.putClientProperty(SettingsEntryPointAction.ActionProvider.ICON_KEY, SettingsEntryPointAction.IconState.ApplicationUpdate) service<ToolboxSettingsActionRegistry>().registerUpdateAction(lifetime, "toolbox-02-update-${request.build}", action) } } internal class ToolboxRestartNotificationHandler : ToolboxServiceHandler<UpdateNotification> { override val requestName: String = "restart-notification" override fun parseRequest(request: JsonElement) = parseUpdateNotificationRequest(request) override fun handleToolboxRequest(lifetime: Disposable, request: UpdateNotification, onResult: (JsonElement) -> Unit) { val actionHandler = Consumer<AnActionEvent> { //at the normal scenario, the lifetime is disposed after the connection is closed //so Toolbox should get everything needed to handle the restart //otherwise an exception is thrown here, so it's OK Disposer.register(lifetime) { AppExecutorUtil.getAppScheduledExecutorService().schedule(Runnable { invokeLater { val app = ApplicationManager.getApplication() if (app?.isUnitTestMode == false) { app.exit(false, true, false) } else { System.setProperty("toolbox-service-test-restart", "1") } } }, 300, TimeUnit.MICROSECONDS) } onResult(JsonObject().apply { addProperty("status", "accepted") addProperty("pid", ProcessHandle.current().pid()) }) } val title = IdeBundle.message("toolbox.updates.download.ready.action.text", request.build, request.version) val description = IdeBundle.message("toolbox.updates.download.ready.action.description", request.build, request.version) val action = DumbAwareAction.create(title, actionHandler) action.templatePresentation.description = description action.templatePresentation.putClientProperty(SettingsEntryPointAction.ActionProvider.ICON_KEY, SettingsEntryPointAction.IconState.ApplicationUpdate) service<ToolboxSettingsActionRegistry>().registerUpdateAction(lifetime, "toolbox-01-restart-${request.build}", action) } }
apache-2.0
b1b722d70840835db9c18f3102be1810
49.460674
140
0.751503
4.918949
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveMethod/MoveKotlinMethodProcessor.kt
1
18545
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.moveMethod import com.intellij.ide.util.EditorHelper import com.intellij.openapi.util.Ref import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethodCallExpression import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor import com.intellij.refactoring.util.MoveRenameUsageInfo import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewBundle import com.intellij.usageView.UsageViewDescriptor import com.intellij.util.IncorrectOperationException import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.* import org.jetbrains.kotlin.idea.core.setVisibility import org.jetbrains.kotlin.idea.refactoring.move.* import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinMoveTargetForExistingElement import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveConflictChecker import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.Mover import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.search.projectScope import org.jetbrains.kotlin.idea.util.getFactoryForImplicitReceiverWithSubtypeOf import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.tail import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.isAncestorOf import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly import org.jetbrains.kotlin.util.containingNonLocalDeclaration class MoveKotlinMethodProcessor( private val method: KtNamedFunction, private val targetVariable: KtNamedDeclaration, private val oldClassParameterNames: Map<KtClass, String>, private val openInEditor: Boolean = false ) : BaseRefactoringProcessor(method.project) { private val targetClassOrObject: KtClassOrObject = if (targetVariable is KtObjectDeclaration) targetVariable else (targetVariable.resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType?.constructor?.declarationDescriptor?.findPsi() as KtClass private val factory = KtPsiFactory(myProject) private val conflicts = MultiMap<PsiElement, String>() override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor { return MoveMultipleElementsViewDescriptor( arrayOf(method), (targetClassOrObject.fqName ?: UsageViewBundle.message("default.package.presentable.name")).toString() ) } override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean { return showConflicts(conflicts, refUsages.get()) } override fun findUsages(): Array<UsageInfo> { val changeInfo = ContainerChangeInfo( ContainerInfo.Class(method.containingClassOrObject!!.fqName!!), ContainerInfo.Class(targetClassOrObject.fqName!!) ) val conflictChecker = MoveConflictChecker(myProject, listOf(method), KotlinMoveTargetForExistingElement(targetClassOrObject), method) val searchScope = myProject.projectScope() val internalUsages = mutableSetOf<UsageInfo>() val methodCallUsages = mutableSetOf<UsageInfo>() methodCallUsages += ReferencesSearch.search(method, searchScope).mapNotNull { ref -> createMoveUsageInfoIfPossible(ref, method, addImportToOriginalFile = true, isInternal = method.isAncestor(ref.element)) } if (targetVariableIsMethodParameter()) { internalUsages += ReferencesSearch.search(targetVariable, searchScope).mapNotNull { ref -> createMoveUsageInfoIfPossible(ref, targetVariable, addImportToOriginalFile = false, isInternal = true) } } internalUsages += method.getInternalReferencesToUpdateOnPackageNameChange(changeInfo) traverseOuterInstanceReferences(method) { internalUsages += it } conflictChecker.checkAllConflicts( methodCallUsages.filter { it is KotlinMoveUsage && !it.isInternal }.toMutableSet(), internalUsages, conflicts ) if (oldClassParameterNames.size > 1) { for (usage in methodCallUsages.filter { it.element is KtNameReferenceExpression || it.element is PsiReferenceExpression }) { conflicts.putValue(usage.element, KotlinBundle.message("text.references.to.outer.classes.have.to.be.added.manually")) } } return (internalUsages + methodCallUsages).toTypedArray() } override fun performRefactoring(usages: Array<out UsageInfo>) { val usagesToProcess = mutableListOf<UsageInfo>() fun changeMethodSignature() { if (targetVariableIsMethodParameter()) { val parameterIndex = method.valueParameters.indexOf(targetVariable as KtParameter) method.valueParameterList?.removeParameter(parameterIndex) } for ((ktClass, parameterName) in oldClassParameterNames) { method.valueParameterList?.addParameterBefore( factory.createParameter("$parameterName: ${ktClass.nameAsSafeName.identifier}"), method.valueParameters.firstOrNull() ) } } fun KtNameReferenceExpression.getImplicitReceiver(): KtExpression? { val scope = getResolutionScope(this.analyze()) ?: return null val descriptor = this.resolveToCall()?.resultingDescriptor ?: return null val receiverDescriptor = descriptor.extensionReceiverParameter ?: descriptor.dispatchReceiverParameter ?: return null val expressionFactory = scope.getFactoryForImplicitReceiverWithSubtypeOf(receiverDescriptor.type) ?: return null val receiverText = if (expressionFactory.isImmediate) "this" else expressionFactory.expressionText return factory.createExpression(receiverText) } fun escalateTargetVariableVisibilityIfNeeded(where: DeclarationDescriptor?) { if (where == null || targetVariableIsMethodParameter()) return val targetDescriptor = targetVariable.resolveToDescriptorIfAny() as? DeclarationDescriptorWithVisibility ?: return if (!DescriptorVisibilities.isVisibleIgnoringReceiver(targetDescriptor, where) && method.manager.isInProject(targetVariable)) { targetVariable.setVisibility(KtTokens.PUBLIC_KEYWORD) } } fun correctMethodCall(expression: PsiElement) { when (expression) { is KtNameReferenceExpression -> { val callExpression = expression.parent as? KtCallExpression ?: return escalateTargetVariableVisibilityIfNeeded(callExpression.containingNonLocalDeclaration()?.resolveToDescriptorIfAny()) val oldReceiver = callExpression.getQualifiedExpressionForSelector()?.receiverExpression ?: expression.getImplicitReceiver() ?: return val newReceiver = if (targetVariable is KtObjectDeclaration) { factory.createExpression(targetVariable.nameAsSafeName.identifier) } else if (targetVariableIsMethodParameter()) { val parameterIndex = method.valueParameters.indexOf(targetVariable as KtParameter) if (parameterIndex in callExpression.valueArguments.indices) { val argumentExpression = callExpression.valueArguments[parameterIndex].getArgumentExpression() ?: return callExpression.valueArgumentList?.removeArgument(parameterIndex) argumentExpression } else targetVariable.defaultValue } else { factory.createExpression("${oldReceiver.text}.${targetVariable.nameAsSafeName.identifier}") } ?: return if (method.containingClassOrObject in oldClassParameterNames) { callExpression.valueArgumentList?.addArgumentBefore( factory.createArgument(oldReceiver), callExpression.valueArguments.firstOrNull() ) } val resultingExpression = callExpression.getQualifiedExpressionForSelectorOrThis() .replace(factory.createExpressionByPattern("$0.$1", newReceiver.text, callExpression)) if (targetVariable is KtObjectDeclaration) { val ref = (resultingExpression as? KtQualifiedExpression)?.receiverExpression?.mainReference ?: return createMoveUsageInfoIfPossible( ref, targetClassOrObject, addImportToOriginalFile = true, isInternal = targetClassOrObject.isAncestor(ref.element) )?.let { usagesToProcess += it } } } is PsiReferenceExpression -> { val callExpression = expression.parent as? PsiMethodCallExpression ?: return val oldReceiver = callExpression.methodExpression.qualifierExpression ?: return val newReceiver = if (targetVariable is KtObjectDeclaration) { // todo: fix usage of target object (import might be needed) val targetObjectName = targetVariable.fqName?.tail(targetVariable.containingKtFile.packageFqName)?.toString() ?: targetVariable.nameAsSafeName.identifier JavaPsiFacade.getElementFactory(myProject).createExpressionFromText("$targetObjectName.INSTANCE", null) } else if (targetVariableIsMethodParameter()) { val parameterIndex = method.valueParameters.indexOf(targetVariable as KtParameter) val arguments = callExpression.argumentList.expressions if (parameterIndex in arguments.indices) { val argumentExpression = arguments[parameterIndex].copy() ?: return arguments[parameterIndex].delete() argumentExpression } else return } else { val getterName = "get${targetVariable.nameAsSafeName.identifier.capitalizeAsciiOnly()}" JavaPsiFacade.getElementFactory(myProject).createExpressionFromText("${oldReceiver.text}.$getterName()", null) } if (method.containingClassOrObject in oldClassParameterNames) { callExpression.argumentList.addBefore(oldReceiver, callExpression.argumentList.expressions.firstOrNull()) } oldReceiver.replace(newReceiver) } } } fun replaceReferenceToTargetWithThis(element: KtExpression) { val scope = element.getResolutionScope(element.analyze()) ?: return val receivers = scope.getImplicitReceiversHierarchy() val receiverText = if (receivers.isEmpty() || receivers[0].containingDeclaration == method.containingClassOrObject?.resolveToDescriptorIfAny()) "this" else "this@${targetClassOrObject.nameAsSafeName.identifier}" element.replace(factory.createExpression(receiverText)) } val (methodCallUsages, internalUsages) = usages.partition { it is MoveRenameUsageInfo && it.referencedElement == method } val newInternalUsages = mutableListOf<UsageInfo>() val oldInternalUsages = mutableListOf<UsageInfo>() try { for (usage in methodCallUsages) { usage.element?.let { element -> correctMethodCall(element) } } for (usage in internalUsages) { val element = usage.element ?: continue if (usage is MoveRenameUsageInfo) { if (usage.referencedElement == targetVariable && element is KtNameReferenceExpression) { replaceReferenceToTargetWithThis(element) } else { oldInternalUsages += usage } } if (usage is SourceInstanceReferenceUsageInfo) { if (usage.member == targetVariable && element is KtNameReferenceExpression) { replaceReferenceToTargetWithThis( (element as? KtThisExpression)?.getQualifiedExpressionForReceiver() ?: element ) } else { val receiverText = oldClassParameterNames[usage.sourceOrOuter] ?: continue when (element) { is KtThisExpression -> element.replace(factory.createExpression(receiverText)) is KtNameReferenceExpression -> { val elementToReplace = (element.parent as? KtCallExpression) ?: element elementToReplace.replace(factory.createExpressionByPattern("$0.$1", receiverText, elementToReplace)) } } } } } changeMethodSignature() markInternalUsages(oldInternalUsages) val movedMethod = Mover.Default(method, targetClassOrObject) val oldToNewMethodMap = mapOf<PsiElement, PsiElement>(method to movedMethod) newInternalUsages += restoreInternalUsages(movedMethod, oldToNewMethodMap) usagesToProcess += newInternalUsages postProcessMoveUsages(usagesToProcess, oldToNewMethodMap) if (openInEditor) EditorHelper.openInEditor(movedMethod) } catch (e: IncorrectOperationException) { } finally { cleanUpInternalUsages(oldInternalUsages + newInternalUsages) } } private fun targetVariableIsMethodParameter(): Boolean = targetVariable is KtParameter && !targetVariable.hasValOrVar() override fun getCommandName(): String = KotlinBundle.message("text.move.method") } internal fun getThisClassesToMembers(method: KtNamedFunction) = traverseOuterInstanceReferences(method) internal fun KtNamedDeclaration.type() = (resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType internal fun KtClass.defaultType() = resolveToDescriptorIfAny()?.defaultType private fun traverseOuterInstanceReferences( method: KtNamedFunction, body: (SourceInstanceReferenceUsageInfo) -> Unit = {} ): Map<KtClass, MutableSet<KtNamedDeclaration>> { val context = method.analyzeWithContent() val containingClassOrObject = method.containingClassOrObject ?: return emptyMap() val descriptor = containingClassOrObject.unsafeResolveToDescriptor() fun getClassOrObjectAndMemberReferencedBy(reference: KtExpression): Pair<DeclarationDescriptor?, CallableDescriptor?> { var classOrObjectDescriptor: DeclarationDescriptor? = null var memberDescriptor: CallableDescriptor? = null if (reference is KtThisExpression) { classOrObjectDescriptor = context[BindingContext.REFERENCE_TARGET, reference.instanceReference] if (classOrObjectDescriptor?.isAncestorOf(descriptor, false) == true) { memberDescriptor = reference.getQualifiedExpressionForReceiver()?.selectorExpression?.getResolvedCall(context)?.resultingDescriptor } } if (reference is KtNameReferenceExpression) { val dispatchReceiver = reference.getResolvedCall(context)?.dispatchReceiver as? ImplicitReceiver classOrObjectDescriptor = dispatchReceiver?.declarationDescriptor if (classOrObjectDescriptor?.isAncestorOf(descriptor, false) == true) { memberDescriptor = reference.getResolvedCall(context)?.resultingDescriptor } } return classOrObjectDescriptor to memberDescriptor } val thisClassesToMembers = mutableMapOf<KtClass, MutableSet<KtNamedDeclaration>>() method.bodyExpression?.forEachDescendantOfType<KtExpression> { reference -> val (classOrObjectDescriptor, memberDescriptor) = getClassOrObjectAndMemberReferencedBy(reference) (classOrObjectDescriptor?.findPsi() as? KtClassOrObject)?.let { resolvedClassOrObject -> val resolvedMember = memberDescriptor?.findPsi() as? KtNamedDeclaration if (resolvedClassOrObject is KtClass) { if (resolvedClassOrObject in thisClassesToMembers) thisClassesToMembers[resolvedClassOrObject]?.add( resolvedMember ?: resolvedClassOrObject ) else thisClassesToMembers[resolvedClassOrObject] = mutableSetOf(resolvedMember ?: resolvedClassOrObject) } body(SourceInstanceReferenceUsageInfo(reference, resolvedClassOrObject, resolvedMember)) } } return thisClassesToMembers } internal class SourceInstanceReferenceUsageInfo( reference: KtExpression, val sourceOrOuter: KtClassOrObject, val member: KtNamedDeclaration? ) : UsageInfo(reference)
apache-2.0
6161ef845f7a7d5dc5722f325ebae312
53.544118
158
0.677972
6.256748
false
false
false
false
itachi1706/DroidEggs
app/src/main/java/com/itachi1706/droideggs/compat/ScreenMetricsCompat.kt
1
2468
package com.itachi1706.droideggs.compat import android.content.Context import android.content.res.Resources import android.os.Build import android.util.DisplayMetrics import android.util.Size import android.view.WindowInsets import android.view.WindowManager import android.view.WindowMetrics import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat @RequiresApi(Build.VERSION_CODES.LOLLIPOP) object ScreenMetricsCompat { private val api: Api = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ApiLevel30() else Api() /** * Returns screen size in pixels. */ fun getScreenSize(context: Context): Size = api.getScreenSize(context) fun getInsetsMetric(insets: WindowInsets): InsetsCompat = api.getInsetsMetric(insets); @Suppress("DEPRECATION") private open class Api { open fun getScreenSize(context: Context): Size { val wm = ContextCompat.getSystemService(context, WindowManager::class.java) val display = wm?.defaultDisplay val metrics = if (display != null) { DisplayMetrics().also { display.getRealMetrics(it) } } else { Resources.getSystem().displayMetrics } return Size(metrics.widthPixels, metrics.heightPixels) } open fun getInsetsMetric(insets: WindowInsets): InsetsCompat { return if (insets.hasStableInsets()) { InsetsCompat(insets.stableInsetTop, insets.stableInsetBottom, insets.stableInsetLeft, insets.stableInsetRight) } else { InsetsCompat(insets.systemWindowInsetTop, insets.systemWindowInsetBottom, insets.systemWindowInsetLeft, insets.systemWindowInsetRight) } } } @RequiresApi(Build.VERSION_CODES.R) private class ApiLevel30 : Api() { override fun getScreenSize(context: Context): Size { val metrics: WindowMetrics = context.getSystemService(WindowManager::class.java).currentWindowMetrics return Size(metrics.bounds.width(), metrics.bounds.height()) } override fun getInsetsMetric(insets: WindowInsets): InsetsCompat { val inset = insets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars()) return InsetsCompat(inset.top, inset.bottom, inset.left, inset.right) } } data class InsetsCompat(val top: Int, val bottom: Int, val left: Int, val right: Int) }
apache-2.0
a0d3c5c6f79a547e01f9d2d1d09cfa73
38.822581
150
0.690438
4.700952
false
false
false
false
JetBrains/kotlin-native
endorsedLibraries/kotlinx.cli/src/tests/HelpTests.kt
3
8579
/* * Copyright 2010-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. */ @file:OptIn(ExperimentalCli::class) @file:Suppress("UNUSED_VARIABLE") package kotlinx.cli import kotlin.test.* class HelpTests { enum class Renders { TEXT, HTML, TEAMCITY, STATISTICS, METRICS } @Test fun testHelpMessage() { val argParser = ArgParser("test") val mainReport by argParser.argument(ArgType.String, description = "Main report for analysis") val compareToReport by argParser.argument(ArgType.String, description = "Report to compare to").optional() val output by argParser.option(ArgType.String, shortName = "o", description = "Output file") val epsValue by argParser.option(ArgType.Double, "eps", "e", "Meaningful performance changes").default(1.0) val useShortForm by argParser.option(ArgType.Boolean, "short", "s", "Show short version of report").default(false) val renders by argParser.option(ArgType.Choice(listOf("text", "html", "teamcity", "statistics", "metrics"), { it }), shortName = "r", description = "Renders for showing information").multiple().default(listOf("text")) val sources by argParser.option(ArgType.Choice<DataSourceEnum>(), "sources", "ds", "Data sources").multiple().default(listOf(DataSourceEnum.PRODUCTION)) val user by argParser.option(ArgType.String, shortName = "u", description = "User access information for authorization") argParser.parse(arrayOf("main.txt")) val helpOutput = argParser.makeUsage().trimIndent() @Suppress("CanBeVal") // can't be val in order to build expectedOutput only in run time. var epsDefault = 1.0 val expectedOutput = """ Usage: test options_list Arguments: mainReport -> Main report for analysis { String } compareToReport -> Report to compare to (optional) { String } Options: --output, -o -> Output file { String } --eps, -e [$epsDefault] -> Meaningful performance changes { Double } --short, -s [false] -> Show short version of report --renders, -r [text] -> Renders for showing information { Value should be one of [text, html, teamcity, statistics, metrics] } --sources, -ds [production] -> Data sources { Value should be one of [local, staging, production] } --user, -u -> User access information for authorization { String } --help, -h -> Usage info """.trimIndent() assertEquals(expectedOutput, helpOutput) } enum class MetricType { SAMPLES, GEOMEAN; override fun toString() = name.toLowerCase() } @Test fun testHelpForSubcommands() { class Summary: Subcommand("summary", "Get summary information") { val exec by option(ArgType.Choice<MetricType>(), description = "Execution time way of calculation").default(MetricType.GEOMEAN) val execSamples by option(ArgType.String, "exec-samples", description = "Samples used for execution time metric (value 'all' allows use all samples)").delimiter(",") val execNormalize by option(ArgType.String, "exec-normalize", description = "File with golden results which should be used for normalization") val compile by option(ArgType.Choice<MetricType>(), description = "Compile time way of calculation").default(MetricType.GEOMEAN) val compileSamples by option(ArgType.String, "compile-samples", description = "Samples used for compile time metric (value 'all' allows use all samples)").delimiter(",") val compileNormalize by option(ArgType.String, "compile-normalize", description = "File with golden results which should be used for normalization") val codesize by option(ArgType.Choice<MetricType>(), description = "Code size way of calculation").default(MetricType.GEOMEAN) val codesizeSamples by option(ArgType.String, "codesize-samples", description = "Samples used for code size metric (value 'all' allows use all samples)").delimiter(",") val codesizeNormalize by option(ArgType.String, "codesize-normalize", description = "File with golden results which should be used for normalization") val source by option(ArgType.Choice<DataSourceEnum>(), description = "Data source").default(DataSourceEnum.PRODUCTION) val sourceSamples by option(ArgType.String, "source-samples", description = "Samples used for code size metric (value 'all' allows use all samples)").delimiter(",") val sourceNormalize by option(ArgType.String, "source-normalize", description = "File with golden results which should be used for normalization") val user by option(ArgType.String, shortName = "u", description = "User access information for authorization") val mainReport by argument(ArgType.String, description = "Main report for analysis") override fun execute() { println("Do some important things!") } } val action = Summary() // Parse args. val argParser = ArgParser("test") argParser.subcommands(action) argParser.parse(arrayOf("summary", "out.txt")) val helpOutput = action.makeUsage().trimIndent() val expectedOutput = """ Usage: test summary options_list Arguments: mainReport -> Main report for analysis { String } Options: --exec [geomean] -> Execution time way of calculation { Value should be one of [samples, geomean] } --exec-samples -> Samples used for execution time metric (value 'all' allows use all samples) { String } --exec-normalize -> File with golden results which should be used for normalization { String } --compile [geomean] -> Compile time way of calculation { Value should be one of [samples, geomean] } --compile-samples -> Samples used for compile time metric (value 'all' allows use all samples) { String } --compile-normalize -> File with golden results which should be used for normalization { String } --codesize [geomean] -> Code size way of calculation { Value should be one of [samples, geomean] } --codesize-samples -> Samples used for code size metric (value 'all' allows use all samples) { String } --codesize-normalize -> File with golden results which should be used for normalization { String } --source [production] -> Data source { Value should be one of [local, staging, production] } --source-samples -> Samples used for code size metric (value 'all' allows use all samples) { String } --source-normalize -> File with golden results which should be used for normalization { String } --user, -u -> User access information for authorization { String } --help, -h -> Usage info """.trimIndent() assertEquals(expectedOutput, helpOutput) } @Test fun testHelpMessageWithSubcommands() { abstract class CommonOptions(name: String, actionDescription: String): Subcommand(name, actionDescription) { val numbers by argument(ArgType.Int, "numbers", description = "Numbers").vararg() } class Summary: CommonOptions("summary", "Calculate summary") { val invert by option(ArgType.Boolean, "invert", "i", "Invert results") var result: Int = 0 override fun execute() { result = numbers.sum() result = invert?.let { -1 * result } ?: result } } class Subtraction : CommonOptions("sub", "Calculate subtraction") { var result: Int = 0 override fun execute() { result = numbers.map { -it }.sum() } } val summaryAction = Summary() val subtractionAction = Subtraction() val argParser = ArgParser("testParser") argParser.subcommands(summaryAction, subtractionAction) argParser.parse(emptyArray()) val helpOutput = argParser.makeUsage().trimIndent() println(helpOutput) val expectedOutput = """ Usage: testParser options_list Subcommands: summary - Calculate summary sub - Calculate subtraction Options: --help, -h -> Usage info """.trimIndent() assertEquals(expectedOutput, helpOutput) } }
apache-2.0
ff4daf1be8041b5f2261316a9e47d58f
50.371257
130
0.648794
4.721519
false
true
false
false
jwren/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspectionTest.kt
4
2447
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.analysis.AnalysisScope import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.ex.GlobalInspectionContextBase import com.intellij.profile.codeInspection.InspectionProjectProfileManager import com.intellij.testFramework.LightProjectDescriptor import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.test.TestMetadata import org.jetbrains.kotlin.idea.test.TestRoot import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @TestRoot("idea/tests") @TestMetadata("testData/inspections/cleanup") @RunWith(JUnit38ClassRunner::class) class KotlinCleanupInspectionTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE private fun doTest(dir: String, result: String, vararg files: String) { myFixture.enableInspections(KotlinCleanupInspection::class.java) myFixture.enableInspections(SortModifiersInspection::class.java) myFixture.enableInspections(RedundantModalityModifierInspection::class.java) myFixture.configureByFiles(*files.map { "$dir/$it" }.toTypedArray()) val project = myFixture.project val managerEx = InspectionManager.getInstance(project) val globalContext = managerEx.createNewGlobalContext(false) as GlobalInspectionContextBase val analysisScope = AnalysisScope(myFixture.file) val profile = InspectionProjectProfileManager.getInstance(project).currentProfile globalContext.codeCleanup(analysisScope, profile, "Cleanup", null, true) myFixture.checkResultByFile("$dir/$result") } fun testBasic() { doTest("basic", "basic.kt.after", "basic.kt", "JavaAnn.java", "deprecatedSymbols.kt") } fun testFileWithAnnotationToSuppressDeprecation() { doTest( "fileWithAnnotationToSuppressDeprecation", "fileWithAnnotationToSuppressDeprecation.kt.after", "fileWithAnnotationToSuppressDeprecation.kt", "deprecatedSymbols.kt" ) } }
apache-2.0
dc859820d38a6837497c2fb8b36046e5
46.980392
158
0.781365
5.195329
false
true
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/idea/CommandLineArgs.kt
1
1167
// 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.idea object CommandLineArgs { private const val SPLASH = "splash" private const val NO_SPLASH = "nosplash" fun isKnownArgument(arg: String): Boolean { return SPLASH == arg || NO_SPLASH == arg || AppMode.DISABLE_NON_BUNDLED_PLUGINS.equals(arg, ignoreCase = true) || AppMode.DONT_REOPEN_PROJECTS.equals(arg, ignoreCase = true) } fun isSplashNeeded(args: List<String>): Boolean { for (arg in args) { if (SPLASH == arg) { return true } else if (NO_SPLASH == arg) { return false } } // products may specify `splash` VM property; `nosplash` is deprecated and should be checked first // BOTH properties maybe specified - so, we must check NO_SPLASH first, it allows user to disable splash even product specifies SPLASH, // as user cannot override SPLASH property if it is set by launcher return when { java.lang.Boolean.getBoolean(NO_SPLASH) -> false java.lang.Boolean.getBoolean(SPLASH) -> true else -> false } } }
apache-2.0
7c35a6ab1f60007fb81d4fdedab3360d
35.5
140
0.671808
4.038062
false
false
false
false
androidx/androidx
collection/collection-benchmark/src/commonMain/kotlin/androidx/collection/SimpleArrayMapBenchmarks.kt
3
3406
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.collection import kotlin.random.Random internal class SimpleArrayMapCreateBenchmark( private val sourceMap: Map<Int, String>, ) : CollectionBenchmark { override fun measuredBlock() { val map = SimpleArrayMap<Int, String>() for ((key, value) in sourceMap) { map.put(key, value) } } } internal class SimpleArrayMapContainsKeyBenchmark( sourceMap: Map<Int, String>, ) : CollectionBenchmark { // Split the source map into two lists, one with elements in the created map, one not. val src = sourceMap.toList() val inList = src.slice(0 until src.size / 2) val inListKeys = inList.map { it.first } val outListKeys = src.slice(src.size / 2 until src.size).map { it.first } val map = SimpleArrayMap<Int, String>() init { for ((key, value) in inList) { map.put(key, value) } } override fun measuredBlock() { for (key in inListKeys) { if (!map.containsKey(key)) { throw AssertionError("Should never get here") } } for (key in outListKeys) { if (map.containsKey(key)) { throw AssertionError("Should never get here") } } } } internal class SimpleArrayMapAddAllThenRemoveIndividuallyBenchmark( private val sourceMap: Map<Int, String> ) : CollectionBenchmark { val sourceSimpleArrayMap = SimpleArrayMap<Int, String>(sourceMap.size) init { for ((key, value) in sourceMap) { sourceSimpleArrayMap.put(key, value) } } var map = SimpleArrayMap<Int, String>(sourceSimpleArrayMap.size()) override fun measuredBlock() { map.putAll(sourceSimpleArrayMap) for (key in sourceMap.keys) { map.remove(key) } } } internal fun createSourceMap(size: Int, sparse: Boolean): Map<Int, String> { return mutableMapOf<Int, String>().apply { val keyFactory: () -> Int = if (sparse) { // Despite the fixed seed, the algorithm which produces random values may vary across // OS versions. Since we're not doing cross-device comparison this is acceptable. val random = Random(0); { val value: Int while (true) { val candidate = random.nextInt() if (candidate !in this) { value = candidate break } } value } } else { var value = 0 { value++ } } repeat(size) { val key = keyFactory() this.put(key, "value of $key") } check(size == this.size) } }
apache-2.0
f9ed0892d354e0df671bac5a172a3547
29.410714
97
0.589841
4.481579
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithArrayOfWithSpreadOperatorInFunctionFix.kt
1
2637
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.ArrayFqNames class SurroundWithArrayOfWithSpreadOperatorInFunctionFix( val wrapper: Name, argument: KtExpression ) : KotlinQuickFixAction<KtExpression>(argument) { override fun getText() = KotlinBundle.message("surround.with.star.0", wrapper) override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val argument = element?.getParentOfType<KtValueArgument>(false) ?: return val argumentName = argument.getArgumentName()?.asName ?: return val argumentExpression = argument.getArgumentExpression() ?: return val factory = KtPsiFactory(argumentExpression) val surroundedWithArrayOf = factory.createExpressionByPattern("$wrapper($0)", argumentExpression) val newArgument = factory.createArgument(surroundedWithArrayOf, argumentName, isSpread = true) argument.replace(newArgument) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtExpression>? { val actualDiagnostic = when (diagnostic.factory) { Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION.warningFactory -> Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION.warningFactory.cast(diagnostic) Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION.errorFactory -> Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION.errorFactory.cast(diagnostic) else -> error("Non expected diagnostic: $diagnostic") } val parameterType = actualDiagnostic.a val wrapper = ArrayFqNames.PRIMITIVE_TYPE_TO_ARRAY[KotlinBuiltIns.getPrimitiveArrayElementType(parameterType)] ?: ArrayFqNames.ARRAY_OF_FUNCTION return SurroundWithArrayOfWithSpreadOperatorInFunctionFix(wrapper, actualDiagnostic.psiElement) } } }
apache-2.0
72c8024e5c5eae7016ef22f4e569b02c
46.945455
158
0.74744
4.838532
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/swapBinaryExpression/multipleOperandsWithDifferentPrecedence.kt
9
105
// AFTER-WARNING: Variable 'rabbit' is never used fun main() { val rabbit = 1 == 2 <caret>|| 3 == 5 }
apache-2.0
1a17e83faf8d4b9f1d204551b4b55b44
25.5
49
0.590476
3.181818
false
false
false
false
80998062/Fank
domain/src/main/java/com/sinyuk/fanfou/domain/repo/timeline/tiled/TiledStatusDataSourceFactory.kt
1
1602
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.domain.repo.timeline.tiled import android.arch.lifecycle.MutableLiveData import android.arch.paging.DataSource import com.sinyuk.fanfou.domain.AppExecutors import com.sinyuk.fanfou.domain.DO.Status import com.sinyuk.fanfou.domain.api.RestAPI /** * Created by sinyuk on 2017/12/29. * */ class TiledStatusDataSourceFactory(private val restAPI: RestAPI, private val path: String, private val uniqueId: String, private val appExecutors: AppExecutors) : DataSource.Factory<Int, Status>() { val sourceLiveData = MutableLiveData<TiledStatusDataSource>() override fun create(): DataSource<Int, Status> { val source = TiledStatusDataSource(restAPI = restAPI, path = path, uniqueId = uniqueId, appExecutors = appExecutors) sourceLiveData.postValue(source) return source } }
mit
2029f82769c63593142db185c71859d2
35.409091
124
0.677903
4.118252
false
false
false
false
gatling/gatling
src/docs/content/tutorials/quickstart/code/BasicSimulationKotlin.kt
1
1535
/* * Copyright 2011-2021 GatlingCorp (https://gatling.io) * * 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. */ //#quickstart-recorder-output package computerdatabase // 1 // 2 import io.gatling.javaapi.core.* import io.gatling.javaapi.http.* import io.gatling.javaapi.core.CoreDsl.* import io.gatling.javaapi.http.HttpDsl.* class BasicSimulationKotlin: Simulation() { // 3 val httpProtocol = http // 4 .baseUrl("http://computer-database.gatling.io") // 5 .acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") // 6 .doNotTrackHeader("1") .acceptLanguageHeader("en-US,en;q=0.5") .acceptEncodingHeader("gzip, deflate") .userAgentHeader("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0") val scn = scenario("BasicSimulation") // 7 .exec(http("request_1") // 8 .get("/")) // 9 .pause(5) // 10 init { setUp( // 11 scn.injectOpen(atOnceUsers(1)) // 12 ).protocols(httpProtocol) // 13 } } //#quickstart-recorder-output
apache-2.0
15eb03096eca76d1c0824936139baad8
31.659574
89
0.692508
3.496583
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/platform/util/AppReviewPromptManager.kt
1
3122
/** * BreadWallet * <p/> * Created by Pablo Budelli <[email protected]> on 6/18/19. * Copyright (c) 2019 breadwallet LLC * <p/> * 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: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * 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.platform.util import android.app.Activity import android.content.Intent import android.net.Uri import com.breadwallet.R import com.breadwallet.tools.manager.BRSharedPrefs /** * Responsible of handling the rules for showing the dialog to request to user to submit */ object AppReviewPromptManager { private const val GOOGLE_PLAY_APP_URI = "market://details?id=com.breadwallet" private const val GOOGLE_PLAY_URI = "https://play.google.com/store/apps/details?id=com.breadwallet" private const val GOOGLE_PLAY_PACKAGE = "com.android.vending" /** * Open Google Play from [activity] for the user to submit a review of the app. */ fun openGooglePlay(activity: Activity) { BRSharedPrefs.appRatePromptHasRated = true // Try to send an intent to google play and if that fails open google play in the browser. try { val googlePlayIntent = Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_APP_URI)) .setPackage(GOOGLE_PLAY_PACKAGE) activity.startActivity(googlePlayIntent) } catch (exception: android.content.ActivityNotFoundException) { activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_URI))) } activity.overridePendingTransition(R.anim.enter_from_right, R.anim.exit_to_left) } fun shouldPrompt(): Boolean = BRSharedPrefs.appRatePromptShouldPrompt && !BRSharedPrefs.appRatePromptDontAskAgain && !BRSharedPrefs.appRatePromptHasRated fun shouldTrackConversions(): Boolean = !BRSharedPrefs.appRatePromptHasRated && !BRSharedPrefs.appRatePromptDontAskAgain fun dismissPrompt() { BRSharedPrefs.appRatePromptShouldPrompt = false BRSharedPrefs.appRatePromptShouldPromptDebug = false } fun neverAskAgain() { BRSharedPrefs.appRatePromptDontAskAgain = true } }
mit
8d86b9d586ac3082b1da862e5723a7f0
41.767123
131
0.730942
4.366434
false
false
false
false
softappeal/yass
kotlin/yass/main/ch/softappeal/yass/remote/session/Reconnector.kt
1
2420
package ch.softappeal.yass.remote.session import ch.softappeal.yass.* import java.lang.reflect.* import java.util.concurrent.* private fun isConnected(session: Session?): Boolean = (session != null) && !session.isClosed abstract class ProxyDelegate<S : Session> { @Volatile private var _session: S? = null val session: S get() { if (!isConnected) throw SessionClosedException() return _session!! } protected fun setSession(session: S?) { _session = session } val isConnected get() = isConnected(_session) @OnlyNeededForJava fun <C : Any> proxy(contract: Class<C>, proxyGetter: (session: S) -> C): C = proxy( contract, InvocationHandler { _, method, arguments -> invoke(method, proxyGetter(session), args(arguments)) } ) inline fun <reified C : Any> proxy(noinline proxyGetter: (session: S) -> C): C = proxy(C::class.java, proxyGetter) } /** Provides proxies surviving reconnects. */ open class Reconnector<S : Session> : ProxyDelegate<S>() { /** * [executor] is called once; must interrupt it's threads to terminate reconnects. * Thrown exceptions of [connector] will be ignored. */ @JvmOverloads fun start( executor: Executor, intervalSeconds: Long, sessionFactory: SessionFactory, delaySeconds: Long = 0, connector: (sessionFactory: SessionFactory) -> Unit ) { require(intervalSeconds >= 1) require(delaySeconds >= 0) val reconnectorSessionFactory = { val session = sessionFactory() @Suppress("UNCHECKED_CAST") setSession(session as S) session } executor.execute { try { TimeUnit.SECONDS.sleep(delaySeconds) } catch (e: InterruptedException) { return@execute } while (!Thread.interrupted()) { if (!isConnected) { setSession(null) try { connector(reconnectorSessionFactory) } catch (ignore: Exception) { } } try { TimeUnit.SECONDS.sleep(intervalSeconds) } catch (e: InterruptedException) { return@execute } } } } }
bsd-3-clause
573488b594391aa3990827bf2f521ab2
30.025641
111
0.557438
4.792079
false
false
false
false
koma-im/koma
src/main/kotlin/link/continuum/desktop/gui/list/distinct.kt
1
2210
package link.continuum.desktop.gui.list import javafx.collections.FXCollections import javafx.collections.ObservableList import link.continuum.desktop.util.debugAssertUiThread import mu.KotlinLogging private val logger = KotlinLogging.logger {} /** * not synchronized, use on the UI thread */ class DedupList<T, U>(private val identify: (T)->U) { private val rwList = FXCollections.observableArrayList<T>() private val elementSet = mutableSetOf<U>() val list: ObservableList<T> = FXCollections.unmodifiableObservableList(rwList) fun getIds(): List<U> { return elementSet.toList() } init { } fun add(element: T) { debugAssertUiThread() if (elementSet.add(identify(element))) { rwList.add(element) } } fun addIfAbsent(id: U, compute: (U)->T) { debugAssertUiThread() if (!elementSet.add(id)) { return } rwList.add(compute(id)) } fun size() = rwList.size fun addAll(elements: Collection<T>) { debugAssertUiThread() rwList.addAll(elements.filter { elementSet.add(identify(it)) }) } fun addAll(index: Int, elements: List<T>) { debugAssertUiThread() rwList.addAll(index, elements.filter { elementSet.add(identify(it)) }) } fun remove(element: T) { debugAssertUiThread() logger.debug { "remove $element"} if (elementSet.remove(identify(element))) { rwList.remove(element) } } fun removeById(id: U) { debugAssertUiThread() if (elementSet.remove(id)) { rwList.removeIf { identify(it) == id } } } fun removeAll(elements: Collection<T>) { debugAssertUiThread() rwList.removeAll(elements.filter { elementSet.remove(identify(it)) }) } fun removeAllById(ids: Collection<U>) { debugAssertUiThread() val rm = ids.toSet() val oldSize = elementSet.size elementSet.minusAssign(rm) val newSize = elementSet.size if (newSize == oldSize) { return } rwList.removeAll { rm.contains(identify(it)) } } }
gpl-3.0
32fbf5cd31216e5820083c61ebd2bde3
28.078947
82
0.604977
4.055046
false
false
false
false
aosp-mirror/platform_frameworks_support
jetifier/jetifier/processor/src/main/kotlin/com/android/tools/build/jetifier/processor/transform/proguard/patterns/PatternHelper.kt
1
1870
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.processor.transform.proguard.patterns import java.util.regex.Pattern /** * Helps to build regular expression [Pattern]s defined with less verbose syntax. * * You can use following shortcuts: * '⦅⦆' - denotes a capturing group (normally '()' is capturing group) * '()' - denotes non-capturing group (normally (?:) is non-capturing group) * ' ' - denotes a whitespace characters (at least one) * ' *' - denotes a whitespace characters (any) * ';' - denotes ' *;' */ object PatternHelper { private val rewrites = listOf( " *" to "[\\s]*", // Optional space " " to "[\\s]+", // Space "⦅" to "(", // Capturing group start "⦆" to ")", // Capturing group end ";" to "[\\s]*;" // Allow spaces in front of ';' ) /** * Transforms the given [toReplace] according to the rules defined in documentation of this * class and compiles it to a [Pattern]. */ fun build(toReplace: String, flags: Int = 0): Pattern { var result = toReplace result = result.replace("(?<!\\\\)\\(".toRegex(), "(?:") rewrites.forEach { result = result.replace(it.first, it.second) } return Pattern.compile(result, flags) } }
apache-2.0
6d50aa93f374a76f18d39b5ec0dea0d5
35.529412
95
0.650376
4.021598
false
false
false
false
daverix/ajvm
core/src/commonMain/kotlin/net/daverix/ajvm/io/AttributeInfo.kt
1
1497
/* Java Virtual Machine for Android Copyright (C) 2017 David Laurell 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 */ package net.daverix.ajvm.io data class AttributeInfo(val nameIndex: Int, val info: ByteArray) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as AttributeInfo if (nameIndex != other.nameIndex) return false if (!info.contentEquals(other.info)) return false return true } override fun hashCode(): Int { var result = nameIndex result = 31 * result + info.contentHashCode() return result } } fun DataInputStream.readAttributes(): Array<AttributeInfo> { return Array(readUnsignedShort()) { val nameIndex = readUnsignedShort() val info = ByteArray(readInt()) readFully(info) AttributeInfo(nameIndex, info) } }
gpl-3.0
fab4ec419f0ccdb325f67099de178931
31.543478
72
0.681363
4.752381
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/query/user/DottedQueryBuilder.kt
1
4635
package com.orgzly.android.query.user import com.orgzly.android.query.* open class DottedQueryBuilder { fun build(query: Query): String { val list = mutableListOf<String>() query.condition?.let { append(list, it) } append(list, query.sortOrders) append(list, query.options) return list.joinToString(" ") } private fun append(list: MutableList<String>, condition: Condition) { val str = toString(condition, true) if (str.isNotEmpty()) { list.add(str) } } private fun toString(expr: Condition, isOuter: Boolean = false): String { fun dot(not: Boolean): String = if (not) "." else "" return when (expr) { is Condition.InBook -> "${dot(expr.not)}b.${quote(expr.name)}" is Condition.HasState -> "${dot(expr.not)}i.${expr.state}" is Condition.HasStateType -> { when (expr.type) { StateType.DONE -> "${dot(expr.not)}it.done" StateType.TODO -> "${dot(expr.not)}it.todo" StateType.NONE -> "${dot(expr.not)}it.none" } } is Condition.HasPriority -> "${dot(expr.not)}p.${expr.priority}" is Condition.HasSetPriority -> "${dot(expr.not)}ps.${expr.priority}" is Condition.HasTag -> "${dot(expr.not)}t.${expr.tag}" is Condition.HasOwnTag -> "${dot(expr.not)}tn.${expr.tag}" is Condition.Event -> { val rel = expr.relation.toString().lowercase() val relString = if (rel == "eq") "" else ".$rel" "e$relString.${expr.interval}" } is Condition.Scheduled -> { val rel = expr.relation.toString().lowercase() val relString = if (rel == "le") "" else ".$rel" "s$relString.${expr.interval}" } is Condition.Deadline -> { val rel = expr.relation.toString().lowercase() val relString = if (rel == "le") "" else ".$rel" "d$relString.${expr.interval}" } is Condition.Closed -> { val rel = expr.relation.toString().lowercase() val relString = if (rel == "eq") "" else ".$rel" "c$relString.${expr.interval}" } is Condition.Created -> { val rel = expr.relation.toString().lowercase() val relString = if (rel == "le") "" else ".$rel" "cr$relString.${expr.interval}" } is Condition.HasText -> if (expr.isQuoted) { quote(expr.text, true) } else { expr.text } is Condition.Or -> expr.operands.joinToString(prefix = if (isOuter) "" else "(", separator = " or ", postfix = if (isOuter) "" else ")") { toString(it) } is Condition.And -> expr.operands.joinToString(separator = " ") { toString(it) } } } private fun append(list: MutableList<String>, orders: List<SortOrder>) { if (orders.isNotEmpty()) { orders.forEach { order -> list.add(when (order) { is SortOrder.Book -> dot(order) + "o.b" is SortOrder.Title -> dot(order) + "o.t" is SortOrder.Scheduled -> dot(order) + "o.s" is SortOrder.Deadline -> dot(order) + "o.d" is SortOrder.Event -> dot(order) + "o.e" is SortOrder.Closed -> dot(order) + "o.c" is SortOrder.Priority -> dot(order) + "o.p" is SortOrder.State -> dot(order) + "o.state" is SortOrder.Created -> dot(order) + "o.cr" is SortOrder.Position -> dot(order) + "o.pos" }) } } } private fun append(list: MutableList<String>, options: Options) { val default = Options() if (options != default) { if (default.agendaDays != options.agendaDays) { list.add("ad.${options.agendaDays}") } } } private fun quote(s: String, unconditionally: Boolean = false): String { return if (unconditionally) { QueryTokenizer.quoteUnconditionally(s) } else { QueryTokenizer.quote(s, " ") } } private fun dot(order: SortOrder) = if (order.desc) "." else "" }
gpl-3.0
919bfb4efd56621f8d3f566e64e9f60f
33.340741
135
0.485005
4.339888
false
false
false
false
square/sqldelight
sqldelight-compiler/src/main/kotlin/com/squareup/sqldelight/core/compiler/QueriesTypeGenerator.kt
1
4609
package com.squareup.sqldelight.core.compiler import com.intellij.openapi.module.Module import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier.ABSTRACT import com.squareup.kotlinpoet.KModifier.PRIVATE import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeSpec import com.squareup.sqldelight.core.SqlDelightFileIndex import com.squareup.sqldelight.core.compiler.model.NamedExecute import com.squareup.sqldelight.core.compiler.model.NamedMutator import com.squareup.sqldelight.core.lang.CUSTOM_DATABASE_NAME import com.squareup.sqldelight.core.lang.DRIVER_NAME import com.squareup.sqldelight.core.lang.DRIVER_TYPE import com.squareup.sqldelight.core.lang.SqlDelightQueriesFile import com.squareup.sqldelight.core.lang.TRANSACTER_IMPL_TYPE import com.squareup.sqldelight.core.lang.TRANSACTER_TYPE import com.squareup.sqldelight.core.lang.queriesImplType import com.squareup.sqldelight.core.lang.queriesType class QueriesTypeGenerator( private val module: Module, private val file: SqlDelightQueriesFile ) { fun interfaceType(): TypeSpec { val type = TypeSpec.interfaceBuilder(file.queriesType.simpleName) .addSuperinterface(TRANSACTER_TYPE) file.namedQueries.forEach { query -> tryWithElement(query.select) { val generator = SelectQueryGenerator(query) type.addFunction( generator.customResultTypeFunctionInterface() .addModifiers(ABSTRACT) .build() ) if (query.needsWrapper()) { type.addFunction( generator.defaultResultTypeFunctionInterface() .addModifiers(ABSTRACT) .build() ) } } } file.namedMutators.forEach { mutator -> type.addExecute(mutator, true) } file.namedExecutes.forEach { execute -> type.addExecute(execute, true) } return type.build() } /** * Generate the full queries object - done once per file, containing all labeled select and * mutator queries. * * eg: class DataQueries( * private val queryWrapper: QueryWrapper, * private val driver: SqlDriver, * transactions: ThreadLocal<Transacter.Transaction> * ) : TransacterImpl(driver, transactions) */ fun generateType(packageName: String): TypeSpec { val type = TypeSpec.classBuilder(file.queriesImplType(packageName).simpleName) .addModifiers(PRIVATE) .superclass(TRANSACTER_IMPL_TYPE) .addSuperinterface(file.queriesType) val constructor = FunSpec.constructorBuilder() // Add the query wrapper as a constructor property: // private val queryWrapper: QueryWrapper val databaseType = ClassName(packageName, "${SqlDelightFileIndex.getInstance(module).className}Impl") type.addProperty( PropertySpec.builder(CUSTOM_DATABASE_NAME, databaseType, PRIVATE) .initializer(CUSTOM_DATABASE_NAME) .build() ) constructor.addParameter(CUSTOM_DATABASE_NAME, databaseType) // Add the database as a constructor property and superclass parameter: // private val driver: SqlDriver type.addProperty( PropertySpec.builder(DRIVER_NAME, DRIVER_TYPE, PRIVATE) .initializer(DRIVER_NAME) .build() ) constructor.addParameter(DRIVER_NAME, DRIVER_TYPE) type.addSuperclassConstructorParameter(DRIVER_NAME) file.namedQueries.forEach { query -> tryWithElement(query.select) { val generator = SelectQueryGenerator(query) type.addProperty(generator.queryCollectionProperty()) type.addFunction(generator.customResultTypeFunction()) if (query.needsWrapper()) { type.addFunction(generator.defaultResultTypeFunction()) } if (query.arguments.isNotEmpty()) { type.addType(generator.querySubtype()) } } } file.namedMutators.forEach { mutator -> type.addExecute(mutator, false) } file.namedExecutes.forEach { execute -> type.addExecute(execute, false) } return type.primaryConstructor(constructor.build()) .build() } private fun TypeSpec.Builder.addExecute(execute: NamedExecute, forInterface: Boolean) { tryWithElement(execute.statement) { val generator = if (execute is NamedMutator) { MutatorQueryGenerator(execute) } else { ExecuteQueryGenerator(execute) } addFunction( if (forInterface) generator.interfaceFunction().addModifiers(ABSTRACT).build() else generator.function() ) } } }
apache-2.0
c10e759f3e9df2a5551031e19263157b
31.006944
105
0.709264
4.540887
false
false
false
false
Jire/Acelta
src/main/kotlin/com/acelta/world/mob/player/Player.kt
1
640
package com.acelta.world.mob.player import com.acelta.world.mob.Mob import com.acelta.world.Position import com.acelta.net.game.Session import com.acelta.packet.outgoing.player.PlayerSend import com.acelta.packet.outgoing.player.sync import it.unimi.dsi.fastutil.objects.ObjectArrayList class Player(id: Int, position: Position, val session: Session, val username: String) : Mob(id, position) { val send = PlayerSend(this) var updateRequired = false val screen = ObjectArrayList<Player>(255) override fun tick() { movement.tick() send.sync() updateRequired = false movement.regionChanging = false session.flush() } }
gpl-3.0
99b2344734d48f38995420bec5bc7bda
21.892857
107
0.767188
3.404255
false
false
false
false
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/network/NewsProvider.kt
1
4490
package com.github.premnirmal.ticker.network import com.github.premnirmal.ticker.model.FetchException import com.github.premnirmal.ticker.model.FetchResult import com.github.premnirmal.ticker.network.data.NewsArticle import com.github.premnirmal.ticker.network.data.Quote import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton @Singleton class NewsProvider @Inject constructor( private val coroutineScope: CoroutineScope, private val googleNewsApi: GoogleNewsApi, private val yahooNewsApi: YahooFinanceNewsApi, private val apeWisdom: ApeWisdom, private val yahooFinanceMostActive: YahooFinanceMostActive, private val stocksApi: StocksApi ) { private var cachedBusinessArticles: List<NewsArticle> = emptyList() private var cachedTrendingStocks: List<Quote> = emptyList() fun initCache() { coroutineScope.launch { fetchMarketNews() fetchTrendingStocks() } } suspend fun fetchNewsForQuery(query: String): FetchResult<List<NewsArticle>> = withContext(Dispatchers.IO) { try { val newsFeed = googleNewsApi.getNewsFeed(query = query) val articles = newsFeed.articleList?.sorted() ?: emptyList() return@withContext FetchResult.success(articles) } catch (ex: Exception) { Timber.w(ex) return@withContext FetchResult.failure<List<NewsArticle>>( FetchException("Error fetching news", ex)) } } suspend fun fetchMarketNews(useCache: Boolean = false): FetchResult<List<NewsArticle>> = withContext(Dispatchers.IO) { try { if (useCache && cachedBusinessArticles.isNotEmpty()) { return@withContext FetchResult.success(cachedBusinessArticles) } val marketNewsArticles = yahooNewsApi.getNewsFeed().articleList.orEmpty() val businessNewsArticles = googleNewsApi.getBusinessNews().articleList.orEmpty() val articles: Set<NewsArticle> = HashSet<NewsArticle>().apply { addAll(marketNewsArticles) addAll(businessNewsArticles) } val newsArticleList = articles.toList().sorted() cachedBusinessArticles = newsArticleList return@withContext FetchResult.success(newsArticleList) } catch (ex: Exception) { Timber.w(ex) return@withContext FetchResult.failure<List<NewsArticle>>( FetchException("Error fetching news", ex)) } } suspend fun fetchTrendingStocks(useCache: Boolean = false): FetchResult<List<Quote>> = withContext(Dispatchers.IO) { try { if (useCache && cachedTrendingStocks.isNotEmpty()) { return@withContext FetchResult.success(cachedTrendingStocks) } // adding this extra try/catch because html format can change and parsing will fail try { val mostActiveHtml = yahooFinanceMostActive.getMostActive() if (mostActiveHtml.isSuccessful) { val doc = mostActiveHtml.body()!! val elements = doc.select("fin-streamer") val symbols = ArrayList<String>() for (element in elements) { if (element.hasAttr("data-symbol") && element.attr("class").equals("fw(600)", ignoreCase = true)) { val symbol = element.attr("data-symbol") if (!symbols.contains(symbol)) symbols.add(symbol) } } if (symbols.isNotEmpty()) { Timber.d("symbols: ${symbols.joinToString(",")}") val mostActiveStocks = stocksApi.getStocks(symbols.toList()) if (mostActiveStocks.wasSuccessful) { cachedTrendingStocks = mostActiveStocks.data } return@withContext mostActiveStocks } } } catch (e: Exception) { Timber.w(e) } // fallback to apewisdom api val result = apeWisdom.getTrendingStocks().results val data = result.map { it.ticker } val trendingResult = stocksApi.getStocks(data) if (trendingResult.wasSuccessful) { cachedTrendingStocks = trendingResult.data } return@withContext trendingResult } catch (ex: Exception) { Timber.w(ex) return@withContext FetchResult.failure<List<Quote>>( FetchException("Error fetching trending", ex)) } } }
gpl-3.0
7826c3cd6dcea5d2c24e851f515a7a25
37.384615
113
0.669488
4.572301
false
false
false
false
kishmakov/Kitchen
protocol/src/io/magnaura/protocol/v1/command.kt
1
802
package io.magnaura.protocol.v1 import com.fasterxml.jackson.annotation.JsonIgnoreProperties import io.magnaura.protocol.Handle import io.magnaura.protocol.Path object CommandHandle : Handle(Path.Subpath(V1RootPath, "command")) { @JsonIgnoreProperties(ignoreUnknown = true) data class Request(val commandId: String) @JsonIgnoreProperties(ignoreUnknown = true) data class Success( val info: String // val commandType: String, // val declarations: List<String> = emptyList() ) @JsonIgnoreProperties(ignoreUnknown = true) data class Failure( val errors: List<String> = emptyList() ) @JsonIgnoreProperties(ignoreUnknown = true) data class Response( val success: Success? = null, val failure: Failure? = null ) }
gpl-3.0
e54b3ad90a240976aa70e18d37dc3a04
27.678571
68
0.699501
4.480447
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-core-bukkit/src/main/kotlin/com/rpkit/core/bukkit/RPKCoreBukkit.kt
1
1719
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.core.bukkit import com.rpkit.core.bukkit.command.sender.resolver.RPKBukkitCommandSenderResolutionService import com.rpkit.core.bukkit.messages.CoreMessages import com.rpkit.core.bukkit.service.BukkitServicesDelegate import com.rpkit.core.database.Database import com.rpkit.core.expression.RPKExpressionService import com.rpkit.core.expression.RPKExpressionServiceImpl import com.rpkit.core.plugin.RPKPlugin import com.rpkit.core.service.Services import org.bstats.bukkit.Metrics import org.bukkit.plugin.java.JavaPlugin /** * RPK's core, Bukkit implementation. * Allows RPK to function on Bukkit. */ class RPKCoreBukkit : JavaPlugin(), RPKPlugin { lateinit var messages: CoreMessages override fun onEnable() { Metrics(this, 4371) Services.delegate = BukkitServicesDelegate() Database.hikariClassLoader = classLoader messages = CoreMessages(this) Services[RPKBukkitCommandSenderResolutionService::class.java] = RPKBukkitCommandSenderResolutionService(this) Services[RPKExpressionService::class.java] = RPKExpressionServiceImpl(this) } }
apache-2.0
8a601ea25c18bdcca61a22bdf86af71c
34.081633
117
0.771379
4.319095
false
false
false
false
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/extensions/lib/FastBlur.kt
1
7959
package tech.summerly.quiet.extensions.lib import android.graphics.Bitmap /** * come from : * https://github.com/paveldudka/blurring */ object FastBlur { fun doBlur(sentBitmap: Bitmap, radius: Int, canReuseInBitmap: Boolean): Bitmap { // Stack Blur v1.0 from // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html // // Java Author: Mario Klingemann <mario at quasimondo.com> // http://incubator.quasimondo.com // created Feburary 29, 2004 // Android port : Yahel Bouaziz <yahel at kayenko.com> // http://www.kayenko.com // ported april 5th, 2012 // This is a compromise between Gaussian Blur and Box blur // It creates much better looking blurs than Box Blur, but is // 7x faster than my Gaussian Blur implementation. // // I called it Stack Blur because this describes best how this // filter works internally: it creates a kind of moving stack // of colors whilst scanning through the image. Thereby it // just has to add one new block of color to the right side // of the stack and remove the leftmost color. The remaining // colors on the topmost layer of the stack are either added on // or reduced by one, depending on if they are on the right or // on the left side of the stack. // // If you are using this algorithm in your code please add // the following line: // // Stack Blur Algorithm by Mario Klingemann <[email protected]> val bitmap: Bitmap if (canReuseInBitmap) { bitmap = sentBitmap } else { bitmap = sentBitmap.copy(sentBitmap.config, true) } if (radius < 1) { return bitmap } val w = bitmap.width val h = bitmap.height val pix = IntArray(w * h) bitmap.getPixels(pix, 0, w, 0, 0, w, h) val wm = w - 1 val hm = h - 1 val wh = w * h val div = radius + radius + 1 val r = IntArray(wh) val g = IntArray(wh) val b = IntArray(wh) var rsum: Int var gsum: Int var bsum: Int var x: Int var y: Int var i: Int var p: Int var yp: Int var yi: Int var yw: Int val vmin = IntArray(Math.max(w, h)) var divsum = div + 1 shr 1 divsum *= divsum val dv = IntArray(256 * divsum) i = 0 while (i < 256 * divsum) { dv[i] = i / divsum i++ } yi = 0 yw = yi val stack = Array(div) { IntArray(3) } var stackpointer: Int var stackstart: Int var sir: IntArray var rbs: Int val r1 = radius + 1 var routsum: Int var goutsum: Int var boutsum: Int var rinsum: Int var ginsum: Int var binsum: Int y = 0 while (y < h) { bsum = 0 gsum = bsum rsum = gsum boutsum = rsum goutsum = boutsum routsum = goutsum binsum = routsum ginsum = binsum rinsum = ginsum i = -radius while (i <= radius) { p = pix[yi + Math.min(wm, Math.max(i, 0))] sir = stack[i + radius] sir[0] = p and 0xff0000 shr 16 sir[1] = p and 0x00ff00 shr 8 sir[2] = p and 0x0000ff rbs = r1 - Math.abs(i) rsum += sir[0] * rbs gsum += sir[1] * rbs bsum += sir[2] * rbs if (i > 0) { rinsum += sir[0] ginsum += sir[1] binsum += sir[2] } else { routsum += sir[0] goutsum += sir[1] boutsum += sir[2] } i++ } stackpointer = radius x = 0 while (x < w) { r[yi] = dv[rsum] g[yi] = dv[gsum] b[yi] = dv[bsum] rsum -= routsum gsum -= goutsum bsum -= boutsum stackstart = stackpointer - radius + div sir = stack[stackstart % div] routsum -= sir[0] goutsum -= sir[1] boutsum -= sir[2] if (y == 0) { vmin[x] = Math.min(x + radius + 1, wm) } p = pix[yw + vmin[x]] sir[0] = p and 0xff0000 shr 16 sir[1] = p and 0x00ff00 shr 8 sir[2] = p and 0x0000ff rinsum += sir[0] ginsum += sir[1] binsum += sir[2] rsum += rinsum gsum += ginsum bsum += binsum stackpointer = (stackpointer + 1) % div sir = stack[stackpointer % div] routsum += sir[0] goutsum += sir[1] boutsum += sir[2] rinsum -= sir[0] ginsum -= sir[1] binsum -= sir[2] yi++ x++ } yw += w y++ } x = 0 while (x < w) { bsum = 0 gsum = bsum rsum = gsum boutsum = rsum goutsum = boutsum routsum = goutsum binsum = routsum ginsum = binsum rinsum = ginsum yp = -radius * w i = -radius while (i <= radius) { yi = Math.max(0, yp) + x sir = stack[i + radius] sir[0] = r[yi] sir[1] = g[yi] sir[2] = b[yi] rbs = r1 - Math.abs(i) rsum += r[yi] * rbs gsum += g[yi] * rbs bsum += b[yi] * rbs if (i > 0) { rinsum += sir[0] ginsum += sir[1] binsum += sir[2] } else { routsum += sir[0] goutsum += sir[1] boutsum += sir[2] } if (i < hm) { yp += w } i++ } yi = x stackpointer = radius y = 0 while (y < h) { // Preserve alpha channel: ( 0xff000000 & pix[yi] ) pix[yi] = 0xff000000.toInt() and pix[yi] or (dv[rsum] shl 16) or (dv[gsum] shl 8) or dv[bsum] rsum -= routsum gsum -= goutsum bsum -= boutsum stackstart = stackpointer - radius + div sir = stack[stackstart % div] routsum -= sir[0] goutsum -= sir[1] boutsum -= sir[2] if (x == 0) { vmin[y] = Math.min(y + r1, hm) * w } p = x + vmin[y] sir[0] = r[p] sir[1] = g[p] sir[2] = b[p] rinsum += sir[0] ginsum += sir[1] binsum += sir[2] rsum += rinsum gsum += ginsum bsum += binsum stackpointer = (stackpointer + 1) % div sir = stack[stackpointer] routsum += sir[0] goutsum += sir[1] boutsum += sir[2] rinsum -= sir[0] ginsum -= sir[1] binsum -= sir[2] yi += w y++ } x++ } bitmap.setPixels(pix, 0, w, 0, 0, w, h) return bitmap } }
gpl-2.0
d4434bd5d905c441a1b3b9a45ac25fa1
26.543253
109
0.407212
4.394809
false
false
false
false
arcao/Geocaching4Locus
geocaching-api/src/main/java/com/arcao/geocaching4locus/data/Main.kt
1
2360
@file:Suppress("BlockingMethodInNonBlockingContext") package com.arcao.geocaching4locus.data import com.arcao.geocaching4locus.data.account.FileAccountManager import com.arcao.geocaching4locus.data.account.oauth.GeocachingOAuthServiceFactory import com.arcao.geocaching4locus.data.api.GeocachingApiRepository import com.arcao.geocaching4locus.data.api.endpoint.GeocachingApiEndpointFactory import com.arcao.geocaching4locus.data.api.internal.moshi.MoshiFactory import com.arcao.geocaching4locus.data.api.internal.okhttp.OkHttpClientFactory import kotlinx.coroutines.runBlocking import timber.log.Timber fun main() { println("Hello") // Init timber Timber.plant(object : Timber.Tree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { println(message + (if (t != null) " $t" else "")) } }) val okHttpClient = OkHttpClientFactory(true).create() val moshi = MoshiFactory.create() println("World!") val oAuthService = GeocachingOAuthServiceFactory(okHttpClient).create() val manager = FileAccountManager(oAuthService) val endpoint = GeocachingApiEndpointFactory(manager, okHttpClient, moshi).create() val api = GeocachingApiRepository(endpoint) if (manager.account == null) { print("Authorization url: ") println(manager.authorizationUrl) print("Enter code: ") val code = readLine() runBlocking { val account = manager.createAccount(code!!) account.updateUserInfo(api.user()) } } runBlocking { // println(api.user()) // println(api.search( // listOf(LocationFilter(50.0, 14.0), GeocacheTypeFilter(GeocacheType.TRADITIONAL)), // lite = false, // take = 30, // logsCount = 10 // )) // // println(api.geocacheLogs("GC12345")) // println(api.geocacheImages("GC12345")) // println(api.userLists()) // api.geocaches( lite = false, referenceCodes = arrayOf( "GCGH8J" ) ).forEach { println("${it.referenceCode}: ${it.lastVisitedDate}") } // api.geocacheLogs("GC7E3EA", take = 50) // api.geocache("GC7E3EA", logsCount = 0, imageCount = 0, lite = false) } }
gpl-3.0
dee87d09c43f660c064c47a361dc20d8
31.777778
99
0.644068
4.118674
false
false
false
false
shchurov/gitter-kotlin-client
app/src/main/kotlin/com/github/shchurov/gitterclient/presentation/ui/activities/LogInActivity.kt
1
2287
package com.github.shchurov.gitterclient.presentation.ui.activities import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.KeyEvent import android.webkit.WebView import android.webkit.WebViewClient import com.github.shchurov.gitterclient.App import com.github.shchurov.gitterclient.dagger.modules.GeneralScreenModule import com.github.shchurov.gitterclient.presentation.presenters.LogInPresenter import com.github.shchurov.gitterclient.presentation.ui.LogInView import com.github.shchurov.gitterclient.utils.showToast import javax.inject.Inject class LogInActivity : AppCompatActivity(), LogInView { @Inject lateinit var presenter: LogInPresenter private lateinit var webView: WebView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initDependencies() setupUi() presenter.attach(this) } private fun initDependencies() { App.component.createGeneralScreenComponent(GeneralScreenModule(this)) .inject(this) } private fun setupUi() { webView = WebView(this) webView.setWebViewClient(webViewClient) setContentView(webView) } private val webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(webView: WebView?, url: String?): Boolean { return presenter.onWebViewOverrideLoading(url) } @Suppress("OverridingDeprecatedMember") override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) { return presenter.onWebViewError() } } override fun onDestroy() { presenter.detach() super.onDestroy() } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { if (event!!.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) { webView.goBack() return true } return super.onKeyDown(keyCode, event) } override fun loadUrl(url: String) { webView.loadUrl(url) } override fun clearWebViewHistory() { webView.clearHistory() } override fun showError(stringId: Int) { showToast(stringId) } }
apache-2.0
926cb99a9a896a147d93ec1e90d533ef
29.918919
113
0.698295
4.876333
false
false
false
false
wakim/esl-pod-client
app/src/main/java/br/com/wakim/eslpodclient/ui/podcastlist/downloaded/presenter/DownloadedListPresenter.kt
2
2695
package br.com.wakim.eslpodclient.ui.podcastlist.downloaded.presenter import br.com.wakim.eslpodclient.Application import br.com.wakim.eslpodclient.android.service.PlaylistManager import br.com.wakim.eslpodclient.android.service.StorageService import br.com.wakim.eslpodclient.data.interactor.DownloadedPodcastItemInteractor import br.com.wakim.eslpodclient.data.interactor.FavoritedPodcastItemInteractor import br.com.wakim.eslpodclient.data.interactor.StorageInteractor import br.com.wakim.eslpodclient.data.model.PodcastItem import br.com.wakim.eslpodclient.data.model.PublishSubjectItem import br.com.wakim.eslpodclient.ui.podcastlist.downloaded.view.DownloadedListView import br.com.wakim.eslpodclient.ui.podcastlist.presenter.PodcastListPresenter import br.com.wakim.eslpodclient.ui.view.PermissionRequester import br.com.wakim.eslpodclient.util.extensions.ofIOToMainThread import rx.subjects.PublishSubject class DownloadedListPresenter: PodcastListPresenter { constructor(app: Application, publishSubject: PublishSubject<PublishSubjectItem<Any>>, downloadedPodcastItemInteractor: DownloadedPodcastItemInteractor, permissionRequester: PermissionRequester, playlistManager: PlaylistManager, storageInteractor: StorageInteractor, favoritedPodcastItemInteractor: FavoritedPodcastItemInteractor) : super(app, publishSubject, downloadedPodcastItemInteractor, permissionRequester, playlistManager, storageInteractor, favoritedPodcastItemInteractor) var storageService: StorageService? = null set(value) { setSynchronizing(value?.synchronizing ?: false) field = value } override fun onStart() { super.onStart() addSubscription { publishSubject .ofIOToMainThread() .filter { it.type == PublishSubjectItem.PODCAST_SYNC_TYPE || it.type == PublishSubjectItem.PODCAST_SYNC_ENDED_TYPE } .subscribe { item -> if (item.type == PublishSubjectItem.PODCAST_SYNC_TYPE) { view?.addItem(item.t as PodcastItem) } else { setSynchronizing(false) } } } } override fun onRefresh() { items.clear() nextPageToken = null loadNextPage() } fun synchronize() { setSynchronizing(true) storageService?.synchronize() } fun setSynchronizing(synchronizing: Boolean) { (view as DownloadedListView).setSynchronizeMenuVisible(!synchronizing) } }
apache-2.0
4f46a6a416995c8b2e57c8d2238b51d5
39.238806
152
0.693506
5.347222
false
false
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/tabs/CostumeTab.kt
1
30320
/* Tickle Copyright (C) 2017 Nick Robinson 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 uk.co.nickthecoder.tickle.editor.tabs import javafx.event.EventHandler import javafx.geometry.Side import javafx.scene.control.MenuButton import javafx.scene.control.MenuItem import javafx.scene.control.TabPane import javafx.stage.Modality import javafx.stage.Stage import org.jbox2d.dynamics.BodyType import org.joml.Vector2d import uk.co.nickthecoder.paratask.AbstractTask import uk.co.nickthecoder.paratask.ParameterException import uk.co.nickthecoder.paratask.TaskDescription import uk.co.nickthecoder.paratask.gui.MyTab import uk.co.nickthecoder.paratask.gui.MyTabPane import uk.co.nickthecoder.paratask.gui.TaskPrompter import uk.co.nickthecoder.paratask.parameters.* import uk.co.nickthecoder.paratask.parameters.fields.TaskForm import uk.co.nickthecoder.paratask.util.FileLister import uk.co.nickthecoder.tickle.* import uk.co.nickthecoder.tickle.editor.MainWindow import uk.co.nickthecoder.tickle.editor.resources.DesignJsonScene import uk.co.nickthecoder.tickle.editor.resources.ResourceType import uk.co.nickthecoder.tickle.editor.util.* import uk.co.nickthecoder.tickle.graphics.TextStyle import uk.co.nickthecoder.tickle.physics.* import uk.co.nickthecoder.tickle.resources.Resources import uk.co.nickthecoder.tickle.scripts.ScriptManager import uk.co.nickthecoder.tickle.sound.Sound class CostumeTab(val name: String, val costume: Costume) : EditTab(name, costume, graphicName = "costume.png") { val detailsTask = CostumeDetailsTask() val detailsForm = TaskForm(detailsTask) val eventsTask = CostumeEventsTask() val eventsForm = TaskForm(eventsTask) val physicsTask = PhysicsTask() val physicsForm = TaskForm(physicsTask) val minorTabs = MyTabPane<MyTab>() val detailsTab = MyTab("Details", detailsForm.build()) val eventsTab = MyTab("Events", eventsForm.build()) val physicsTab = MyTab("Physics", physicsForm.build()) val posesButton = MenuButton("Poses") init { minorTabs.side = Side.BOTTOM minorTabs.tabClosingPolicy = TabPane.TabClosingPolicy.UNAVAILABLE minorTabs.add(detailsTab) minorTabs.add(eventsTab) if (Resources.instance.gameInfo.physicsEngine) { minorTabs.add(physicsTab) } borderPane.center = minorTabs addCopyButton(costume, ResourceType.COSTUME) { newName, newCostume -> Resources.instance.costumes.add(newName, newCostume) newCostume.costumeGroup?.add(newName, newCostume) } buildPosesButton() detailsTask.taskD.root.listen { needsSaving = true } eventsTask.taskD.root.listen { needsSaving = true } physicsTask.taskD.root.listen { needsSaving = true } } private fun buildPosesButton() { val poses = mutableSetOf<Pose>() costume.events.values.forEach { event -> poses.addAll(event.poses) poses.addAll(event.ninePatches.map { it.pose }) } if (poses.isEmpty()) { leftButtons.children.remove(posesButton) } else { posesButton.items.clear() poses.forEach { pose -> Resources.instance.poses.findName(pose)?.let { name -> val menuItem = MenuItem(name) posesButton.items.add(menuItem) menuItem.onAction = EventHandler { MainWindow.instance.openTab(name, pose) } } } if (!leftButtons.children.contains(posesButton)) { leftButtons.children.add(posesButton) } } } override fun justSave(): Boolean { if (detailsForm.check()) { if (eventsForm.check()) { if (physicsForm.check()) { detailsTask.run() eventsTask.run() physicsTask.run() return true } else { physicsTab.isSelected = true } } else { eventsTab.isSelected = true } } else { detailsTab.isSelected = true } return false } inner class CostumeDetailsTask : AbstractTask() { private val nameP = StringParameter("name", value = name) private val roleClassP = ClassParameter("role", Role::class.java) private val canRotateP = BooleanParameter("canRotate") private val canScaleP = BooleanParameter("canScale") private val zOrderP = DoubleParameter("zOrder") private val costumeGroupP = CostumeGroupParameter { chooseCostumeGroup(it) } private val showInSceneEditorP = BooleanParameter("showInSceneEditor", value = costume.showInSceneEditor) private val infoP = InformationParameter("info", information = "The role has no fields with the '@CostumeAttribute' annotation, and therefore, this costume has no attributes.") private val attributesP = SimpleGroupParameter("attributes") override val taskD = TaskDescription("costumeDetails") .addParameters(nameP, roleClassP, canRotateP, canScaleP, zOrderP, costumeGroupP, showInSceneEditorP, attributesP) init { nameP.value = name roleClassP.classValue = costume.roleClass() canRotateP.value = costume.canRotate canScaleP.value = costume.canScale zOrderP.value = costume.zOrder costumeGroupP.costumeP.value = costume.costumeGroup updateAttributes() roleClassP.listen { updateAttributes() } } override fun run() { costume.roleString = if (roleClassP.classValue == null) "" else ScriptManager.nameForClass(roleClassP.classValue!!) costume.canRotate = canRotateP.value == true costume.canScale = canScaleP.value == true costume.zOrder = zOrderP.value!! costume.showInSceneEditor = showInSceneEditorP.value == true if (costume.costumeGroup != costumeGroupP.costumeP.value) { costume.costumeGroup?.remove(name) costume.costumeGroup = costumeGroupP.costumeP.value costume.costumeGroup?.add(nameP.value, costume) if (costume.costumeGroup == null) { Resources.instance.fireAdded(costume, name) } } if (nameP.value != name) { Resources.instance.costumes.rename(name, nameP.value) TaskPrompter(RenameCostumeTask(name, nameP.value)).placeOnStage(Stage()) } } fun chooseCostumeGroup(groupName: String) { costumeGroupP.costumeP.value = Resources.instance.costumeGroups.find(groupName) } fun updateAttributes() { roleClassP.classValue?.let { costume.attributes.updateAttributesMetaData(it) } attributesP.children.toList().forEach { attributesP.remove(it) } attributesP.hidden = roleClassP.classValue == null costume.attributes.data().sortedBy { it.order }.forEach { data -> data as DesignAttributeData data.costumeParameter?.let { it -> val parameter = it.copyBounded() attributesP.add(parameter) try { parameter.stringValue = data.value ?: "" } catch (e: Exception) { // Do nothing } } } if (attributesP.children.size == 0) { attributesP.add(infoP) } } } inner class CostumeEventsTask : AbstractTask() { val initialEventP = StringParameter("initialEvent", value = costume.initialEventName) val inheritEventsFromP = createCostumeParameter("inheritEventsFrom", required = false, value = costume.inheritEventsFrom) val eventsP = MultipleParameter("events") { EventParameter() }.asListDetail(isBoxed = true, allowReordering = false) { it.toString() } override val taskD = TaskDescription("costumeEvents") .addParameters(initialEventP, inheritEventsFromP, eventsP) init { costume.events.forEach { eventName, event -> event.poses.forEach { pose -> val inner = eventsP.newValue() inner.eventNameP.value = eventName inner.poseP.value = pose inner.typeP.value = inner.poseP } event.costumes.forEach { costume -> val inner = eventsP.newValue() inner.eventNameP.value = eventName inner.costumeP.value = costume inner.typeP.value = inner.costumeP } event.textStyles.forEach { textStyle -> val inner = eventsP.newValue() inner.eventNameP.value = eventName inner.textStyleP.from(textStyle) inner.typeP.value = inner.textStyleP } event.strings.forEach { str -> val inner = eventsP.newValue() inner.eventNameP.value = eventName inner.stringP.value = str inner.typeP.value = inner.stringP } event.sounds.forEach { sound -> val inner = eventsP.newValue() inner.eventNameP.value = eventName inner.soundP.value = sound inner.typeP.value = inner.soundP } event.ninePatches.forEach { ninePatch -> val inner = eventsP.newValue() inner.eventNameP.value = eventName inner.ninePatchP.from(ninePatch) inner.typeP.value = inner.ninePatchP } } } override fun run() { costume.initialEventName = initialEventP.value costume.inheritEventsFrom = inheritEventsFromP.value costume.events.clear() eventsP.innerParameters.forEach { inner -> when (inner.typeP.value) { inner.poseP -> addPose(inner.eventNameP.value, inner.poseP.value!!) inner.costumeP -> addCostume(inner.eventNameP.value, inner.costumeP.value!!) inner.textStyleP -> addTextStyle(inner.eventNameP.value, inner.textStyleP.createTextStyle()) inner.stringP -> addString(inner.eventNameP.value, inner.stringP.value) inner.soundP -> addSound(inner.eventNameP.value, inner.soundP.value!!) inner.ninePatchP -> addNinePatch(inner.eventNameP.value, inner.ninePatchP.createNinePatch()) } } } fun addPose(eventName: String, pose: Pose) { var event = costume.events[eventName] if (event == null) { event = CostumeEvent() costume.events[eventName] = event } event.poses.add(pose) } fun addCostume(eventName: String, cos: Costume) { var event = costume.events[eventName] if (event == null) { event = CostumeEvent() costume.events[eventName] = event } event.costumes.add(cos) } fun addTextStyle(eventName: String, textStyle: TextStyle) { var event = costume.events[eventName] if (event == null) { event = CostumeEvent() costume.events[eventName] = event } event.textStyles.add(textStyle) } fun addString(eventName: String, str: String) { var event = costume.events[eventName] if (event == null) { event = CostumeEvent() costume.events[eventName] = event } event.strings.add(str) } fun addSound(eventName: String, sound: Sound) { var event = costume.events[eventName] if (event == null) { event = CostumeEvent() costume.events[eventName] = event } event.sounds.add(sound) } fun addNinePatch(eventName: String, ninePatch: NinePatch) { var event = costume.events[eventName] if (event == null) { event = CostumeEvent() costume.events[eventName] = event } event.ninePatches.add(ninePatch) } } inner class EventParameter : MultipleGroupParameter("event") { val eventNameP = StringParameter("eventName") val poseP = createPoseParameter() val textStyleP = TextStyleParameter("style") val costumeP = createCostumeParameter() val stringP = StringParameter("string") val soundP = createSoundParameter() val ninePatchP = createNinePatchParameter() val typeP = OneOfParameter("type", value = null, choiceLabel = "Type") .addChoices(poseP, costumeP, textStyleP, stringP, soundP, ninePatchP) init { addParameters(eventNameP, typeP, poseP, ninePatchP, costumeP, textStyleP, stringP, soundP) } override fun toString(): String { val eventName = if (eventNameP.value.isBlank()) "<no name>" else eventNameP.value val type = typeP.value?.label ?: "" val dataName = when (typeP.value) { poseP -> Resources.instance.poses.findName(poseP.value) costumeP -> Resources.instance.costumes.findName(costumeP.value) textStyleP -> Resources.instance.fontResources.findName(textStyleP.fontP.value) stringP -> stringP.value soundP -> Resources.instance.sounds.findName(soundP.value) ninePatchP -> "Nine Patch (${Resources.instance.poses.findName(ninePatchP.poseP.value)})" else -> "" } return "$eventName ($type) $dataName" } } inner class PhysicsTask : AbstractTask() { val bodyTypeP = ChoiceParameter<BodyType?>("bodyType", required = false, value = costume.bodyDef?.type) .nullableEnumChoices(mixCase = true, nullLabel = "None") val linearDampingP = DoubleParameter("linearDamping", value = costume.bodyDef?.linearDamping ?: 0.0, minValue = 0.0, maxValue = 10.0) val angularDampingP = DoubleParameter("angularDamping", value = costume.bodyDef?.angularDamping ?: 0.0, minValue = 0.0, maxValue = 10.0) val fixedRotationP = BooleanParameter("fixedRotation", value = costume.bodyDef?.fixedRotation ?: false) val bulletP = BooleanParameter("bullet", value = costume.bodyDef?.bullet ?: false) val fixturesP = MultipleParameter("fixtures", minItems = 1) { FixtureParameter() }.asListDetail(isBoxed = true) { param -> param.toString() } override val taskD = TaskDescription("physics") .addParameters(bodyTypeP, linearDampingP, angularDampingP, fixedRotationP, bulletP, fixturesP) init { costume.bodyDef?.fixtureDefs?.forEach { fixtureDef -> val fixtureParameter = fixturesP.newValue() fixtureParameter.initParameters(fixtureDef) } updateHiddenFields() bodyTypeP.listen { updateHiddenFields() } } fun updateHiddenFields() { val static = bodyTypeP.value == BodyType.STATIC || bodyTypeP.value == null linearDampingP.hidden = static angularDampingP.hidden = static fixedRotationP.hidden = static bulletP.hidden = static fixturesP.hidden = !(bodyTypeP.value?.hasFixtures() ?: false) } override fun run() { if (bodyTypeP.value == null) { costume.bodyDef = null } else { val bodyDef = costume.bodyDef ?: TickleBodyDef() costume.bodyDef = bodyDef with(bodyDef) { type = bodyTypeP.value!! linearDamping = linearDampingP.value!! angularDamping = angularDampingP.value!! bullet = bulletP.value == true fixedRotation = fixedRotationP.value!! } bodyDef.fixtureDefs.clear() fixturesP.innerParameters.forEach { fixtureParameter -> bodyDef.fixtureDefs.add(fixtureParameter.createCostumeFixtureDef()) } } } inner class FixtureParameter() : MultipleGroupParameter("fixture") { val densityP = FloatParameter("density", minValue = 0f, value = 1f) val frictionP = FloatParameter("friction", minValue = 0f, maxValue = 1f, value = 0f) val restitutionP = FloatParameter("restitution", minValue = 0f, maxValue = 1f, value = 1f) val isSensorP = BooleanParameter("isSensor", value = false) val circleCenterP = Vector2dParameter("circleCenter", label = "Center", showXY = false).asHorizontal() val circleRadiusP = DoubleParameter("circleRadius", label = "Radius") val circleP = SimpleGroupParameter("circle") .addParameters(circleCenterP, circleRadiusP) val boxSizeP = Vector2dParameter("boxSize", showXY = false).asHorizontal() val boxCenterP = Vector2dParameter("boxCenter", label = "Center", showXY = false).asHorizontal() val boxAngleP = AngleParameter("boxAngle", label = "Angle") val boxP = SimpleGroupParameter("box") .addParameters(boxSizeP, boxCenterP, boxAngleP) val polygonInfo = InformationParameter("polygonInfo", information = "Note. The polygon must be convex. Create more than one fixture to build concave objects.") val polygonPointsP = MultipleParameter("polygonPoints", minItems = 2) { Vector2dParameter("point").asHorizontal() } val polygonP = SimpleGroupParameter("polygon") .addParameters(polygonInfo, polygonPointsP) val shapeP = OneOfParameter("shape", choiceLabel = "Type") .addChoices( "Circle" to circleP, "Box" to boxP, "Polygon" to polygonP) val shapeEditorButtonP = ButtonParameter("editShape", label = "", buttonText = "Edit Shape") { onEditShape() } val filterGroupP = createFilterGroupParameter() val filterCategoriesP = createFilterBitsParameter("categories", "I Am") val filterMaskP = createFilterBitsParameter("mask", "I Collide With") init { addParameters(densityP, frictionP, restitutionP, isSensorP, shapeP) (costume.pose() ?: costume.chooseNinePatch("default")?.pose)?.let { addParameters(shapeEditorButtonP) circleRadiusP.value = 15.0 boxSizeP.xP.value = 15.0 boxSizeP.yP.value = 15.0 } addParameters(circleP, boxP, polygonP, filterGroupP, filterCategoriesP, filterMaskP) bodyTypeP.listen { densityP.hidden = bodyTypeP.value != BodyType.DYNAMIC && bodyTypeP.value != BodyType.STATIC frictionP.hidden = bodyTypeP.value != BodyType.DYNAMIC && bodyTypeP.value != BodyType.STATIC } // TODO Why are we firing a change event? bodyTypeP.parameterListeners.fireValueChanged(bodyTypeP, bodyTypeP.value) } fun initParameters(fixtureDef: TickleFixtureDef) { with(fixtureDef) { densityP.value = density frictionP.value = friction restitutionP.value = restitution isSensorP.value = isSensor filterGroupP.value = filter.groupIndex filterCategoriesP.value = filter.categoryBits filterMaskP.value = filter.maskBits } with(fixtureDef.shapeDef) { when (this) { is CircleDef -> { shapeP.value = circleP circleCenterP.x = center.x circleCenterP.y = center.y circleRadiusP.value = radius } is BoxDef -> { shapeP.value = boxP boxSizeP.xP.value = width boxSizeP.yP.value = height boxCenterP.value = center boxAngleP.value = angle } is PolygonDef -> { shapeP.value = polygonP polygonPointsP.clear() points.forEach { point -> polygonPointsP.addValue(point) } } } } } override fun check() { super.check() // Check if the shape is concave. // Compute the dot product of the each line with the previous line's normal. For a convex shape // the dot products should all be positive or all be negative. // BTW, despite what people think, maths isn't my strong suit, so there may be a more efficient method. // Note. this doesn't detect "star" shapes, such as a witches pentagram, but it is unlikely somebody // would create such a shape! Summing the interior angles, and test if it is significantly over 2 PI // would fix that, but I can't be bothered. Sorry. var negativeCount = 0 val points = polygonPointsP.innerParameters if (shapeP.value == polygonP) { points.forEachIndexed { index, pointP -> val point = pointP.value val prev = points[if (index == 0) points.size - 1 else index - 1].value val next = points[if (index == points.size - 1) 0 else index + 1].value val line1 = Vector2d() val line2 = Vector2d() prev.sub(point, line1) next.sub(point, line2) val normal1 = Vector2d(line1.y, -line1.x) val dotProduct = normal1.dot(line2) if (dotProduct < 0.0) { negativeCount++ } // If any lines are straight the dot product will be zero. That is redundant point and will just a waste of CPU! if (dotProduct == 0.0) { throw ParameterException(shapeP, "Contains a redundant point #$index") } } } if (negativeCount > 0 && negativeCount != points.size) { throw ParameterException(shapeP, "The shape is concave. Create 2 (or more) fixtures which are all convex.") } } fun createShapeDef(): ShapeDef? { try { when (shapeP.value) { circleP -> { return CircleDef(Vector2d(circleCenterP.x!!, circleCenterP.y!!), circleRadiusP.value!!) } boxP -> { return BoxDef(boxSizeP.xP.value!!, boxSizeP.yP.value!!, boxCenterP.value, boxAngleP.value) } polygonP -> { return PolygonDef(polygonPointsP.value) } else -> { return null } } } catch (e: KotlinNullPointerException) { return null } } fun createCostumeFixtureDef(): TickleFixtureDef { val shapeDef = createShapeDef() ?: throw IllegalStateException("Not a valid shape") val fixtureDef = TickleFixtureDef(shapeDef) with(fixtureDef) { density = densityP.value!! friction = frictionP.value!! restitution = restitutionP.value!! isSensor = isSensorP.value == true filter.groupIndex = filterGroupP.value!! filter.categoryBits = filterCategoriesP.value filter.maskBits = filterMaskP.value } return fixtureDef } fun onEditShape() { (costume.pose() ?: costume.chooseNinePatch("default")?.pose)?.let { pose -> val task = ShapeEditorTask(pose, this) val stage = Stage() // always on top didn't work for me (on linux using open jdk and the open javafx. // stage.isAlwaysOnTop = true // So using a modal dialog instead (not what I wanted. grrr). stage.initModality(Modality.APPLICATION_MODAL) TaskPrompter(task, showCancel = false).placeOnStage(stage) task.shapeEditorP.update(createShapeDef()) listen { task.shapeEditorP.update(createShapeDef()) } } } override fun toString(): String { return when (shapeP.value) { circleP -> { "Circle @ ${circleCenterP.x} , ${circleCenterP.y}" } boxP -> { "Box @ ${boxCenterP.value.x} , ${boxCenterP.value.y}" } polygonP -> { "Polygon (${polygonPointsP.value.size} points)" } else -> { "Unknown" } } } } } } fun createFilterGroupParameter(): ChoiceParameter<Int> { val choiceP = ChoiceParameter("collisionFilterGroup", value = 0) val filterGroup = Class.forName(Resources.instance.gameInfo.physicsInfo.filterGroupsString).newInstance() as FilterGroups filterGroup.values().forEach { name, value -> choiceP.addChoice(name, value, name) } if (filterGroup.values().size <= 1) { choiceP.hidden = true } return choiceP } fun createFilterBitsParameter(name: String, label: String) = FilterBitsParameter(name, label) class FilterBitsParameter( name: String, label: String) : SimpleGroupParameter(name, label) { val filterMasks = Class.forName(Resources.instance.gameInfo.physicsInfo.filterBitsString).newInstance() as FilterBits init { filterMasks.values().forEach { maskName, _ -> val param = BooleanParameter("${name}_$maskName", label = maskName, value = false) addParameters(param) } asGrid(labelPosition = LabelPosition.LEFT, columns = filterMasks.columns(), isBoxed = true) if (filterMasks.values().isEmpty()) { hidden = true } } var value: Int get() { if (hidden) return 0xFFFF var value = 0 filterMasks.values().forEach { maskName, bit -> val param = find("${name}_$maskName") as BooleanParameter if (param.value == true) { value += bit } } return value } set(v) { filterMasks.values().forEach { maskName, bit -> val param = find("${name}_$maskName") as BooleanParameter param.value = (v and bit) != 0 } } } class RenameCostumeTask(val oldCostumeName: String, val newCostumeName: String) : AbstractTask() { val informationP = InformationParameter("infoP", information = "To rename a costume requires loading and saving all scene.\nThis may take a few seconds.") override val taskD = TaskDescription("renameCostume") .addParameters(informationP) override fun run() { val fileLister = FileLister(extensions = listOf("scene")) fileLister.listFiles(Resources.instance.sceneDirectory).forEach { file -> val json = DesignJsonScene(file) val sceneResource = json.sceneResource var changed = false sceneResource.stageResources.forEach { _, stageResource -> stageResource.actorResources.forEach { actorResource -> if (actorResource.costumeName == oldCostumeName) { actorResource.costumeName = newCostumeName changed = true } } } if (changed) { json.save(file) } } } }
gpl-3.0
727bea8fce1bae7c32278ecba310decf
39.054161
171
0.559004
4.881662
false
false
false
false
itachi1706/CheesecakeUtilities
app/src/main/java/com/itachi1706/cheesecakeutilities/modules/gpaCalculator/objects/GpaScoring.kt
1
756
package com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects /** * Created by Kenneth on 24/6/2019. * for com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects in CheesecakeUtilities */ data class GpaScoring(val name: String = "Some name", val shortname: String = "Some shortname", val description: String = "No description available", val passtier: List<GpaTier>? = null, val gradetier: List<GpaTier> = ArrayList(), val type: String = "gpa", val finalGradeColor: List<GpaColor>? = null) { data class GpaTier(val name: String = "Grade Tier", val desc: String = "No description", val value: Double = 0.0) data class GpaColor(val from: Double = 0.0, val to: Double = 0.0, val color: String = "None") }
mit
c75fdab150b51774e798b61cc725ed0e
67.818182
186
0.71164
3.566038
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/lang/core/types/util/RustPsiExtensions.kt
1
2342
package org.rust.lang.core.types.util import com.intellij.openapi.util.Computable import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import org.rust.ide.utils.recursionGuard import org.rust.lang.core.psi.* import org.rust.lang.core.types.RustType import org.rust.lang.core.types.RustUnknownType import org.rust.lang.core.types.unresolved.RustUnresolvedType import org.rust.lang.core.types.visitors.impl.RustTypeResolvingVisitor import org.rust.lang.core.types.visitors.impl.RustTypificationEngine val RustExprElement.resolvedType: RustType get() = CachedValuesManager.getCachedValue(this, CachedValueProvider { CachedValueProvider.Result.create(RustTypificationEngine.typifyExpr(this), PsiModificationTracker.MODIFICATION_COUNT) } ) val RustTypeElement.type: RustUnresolvedType get() = CachedValuesManager.getCachedValue(this, CachedValueProvider { CachedValueProvider.Result.create( RustTypificationEngine.typifyType(this), PsiModificationTracker.MODIFICATION_COUNT ) } ) val RustTypeElement.resolvedType: RustType get() = recursionGuard(this, Computable { type.accept(RustTypeResolvingVisitor(this)) }) ?: RustUnknownType val RustTypeBearingItemElement.resolvedType: RustType get() = CachedValuesManager.getCachedValue(this, CachedValueProvider { CachedValueProvider.Result.create(RustTypificationEngine.typify(this), PsiModificationTracker.MODIFICATION_COUNT) }) /** * Helper property to extract (type-)bounds imposed onto this particular type-parameter */ val RustTypeParamElement.bounds: Sequence<RustPolyboundElement> get() { val owner = parent?.parent as? RustGenericDeclaration val whereBounds = owner?.whereClause?.wherePredList.orEmpty() .asSequence() .filter { (it.type as? RustPathTypeElement)?.path?.reference?.resolve() == this } .flatMap { it.typeParamBounds?.polyboundList.orEmpty().asSequence() } return typeParamBounds?.polyboundList.orEmpty().asSequence() + whereBounds }
mit
19f825d99229ad6c24c2eb0ac0e3ddcb
38.694915
133
0.708369
4.750507
false
false
false
false
doompickaxe/MineTime
src/main/kotlin/minetime/BootApplication.kt
1
953
package minetime import minetime.model.Person import minetime.persistence.PersonRepository import org.slf4j.LoggerFactory import org.springframework.boot.CommandLineRunner import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.context.annotation.Bean import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder @SpringBootApplication class BootApplication { private val log = LoggerFactory.getLogger(BootApplication::class.java) @Bean fun init(userRepo: PersonRepository) = CommandLineRunner { log.info("_______init________") val passwordEncoder = BCryptPasswordEncoder() println(userRepo.findAll()) println(userRepo.save(Person(firstName = "abc", lastName = "def", email="user", password = passwordEncoder.encode("pass")))) } } fun main(args: Array<String>) { SpringApplication.run(BootApplication::class.java, *args) }
mit
eca97f11f6c239a849b1e44d2b6239ed
34.296296
128
0.791186
4.453271
false
false
false
false
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/utils/ClickableArrowKeyMovementMethod.kt
1
1963
package be.digitalia.fosdem.utils import android.graphics.RectF import android.text.Spannable import android.text.method.ArrowKeyMovementMethod import android.text.style.ClickableSpan import android.view.MotionEvent import android.widget.TextView import androidx.core.text.getSpans /** * An extension of ArrowKeyMovementMethod supporting clickable spans as well. */ object ClickableArrowKeyMovementMethod : ArrowKeyMovementMethod() { private val touchedLineBounds = RectF() override fun onTouchEvent(widget: TextView, buffer: Spannable, event: MotionEvent): Boolean { // If action has finished if (event.action == MotionEvent.ACTION_UP) { // Locate the area that was pressed var x = event.x.toInt() var y = event.y.toInt() x -= widget.totalPaddingLeft y -= widget.totalPaddingTop x += widget.scrollX y += widget.scrollY // Locate the text line val layout = widget.layout val line = layout.getLineForVertical(y) // Check that the touch actually happened within the line bounds with(touchedLineBounds) { left = layout.getLineLeft(line) top = layout.getLineTop(line).toFloat() right = layout.getLineWidth(line) + left bottom = layout.getLineBottom(line).toFloat() } if (touchedLineBounds.contains(x.toFloat(), y.toFloat())) { val offset = layout.getOffsetForHorizontal(line, x.toFloat()) // Find a clickable span at that text offset, if any val clickableSpans = buffer.getSpans<ClickableSpan>(offset, offset) if (clickableSpans.isNotEmpty()) { clickableSpans[0].onClick(widget) return true } } } return super.onTouchEvent(widget, buffer, event) } }
apache-2.0
8314cd768ba966c4f9c5def95715420f
35.37037
97
0.618441
4.932161
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/libraries/GivenANullLibrary/WhenRetrievingTheLibraryConnection.kt
2
3079
package com.lasthopesoftware.bluewater.client.connection.libraries.GivenANullLibrary import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.connection.BuildingConnectionStatus import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider import com.lasthopesoftware.bluewater.client.connection.builder.live.ProvideLiveUrl import com.lasthopesoftware.bluewater.client.connection.libraries.LibraryConnectionProvider import com.lasthopesoftware.bluewater.client.connection.okhttp.OkHttpFactory import com.lasthopesoftware.bluewater.client.connection.settings.ConnectionSettings import com.lasthopesoftware.bluewater.client.connection.settings.LookupConnectionSettings import com.lasthopesoftware.bluewater.client.connection.settings.ValidateConnectionSettings import com.lasthopesoftware.bluewater.client.connection.url.IUrlProvider import com.lasthopesoftware.bluewater.client.connection.waking.NoopServerAlarm import com.lasthopesoftware.bluewater.shared.promises.extensions.DeferredPromise import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.junit.BeforeClass import org.junit.Test import java.util.* class WhenRetrievingTheLibraryConnection { companion object Setup { private val statuses: MutableList<BuildingConnectionStatus> = ArrayList() private val urlProvider = mockk<IUrlProvider>() private var connectionProvider: IConnectionProvider? = null @BeforeClass @JvmStatic fun before() { val validateConnectionSettings = mockk<ValidateConnectionSettings>() every { validateConnectionSettings.isValid(any()) } returns true val deferredConnectionSettings = DeferredPromise(null as ConnectionSettings?) val lookupConnection = mockk<LookupConnectionSettings>() every { lookupConnection.lookupConnectionSettings(LibraryId(2)) } returns deferredConnectionSettings val liveUrlProvider = mockk<ProvideLiveUrl>() every { liveUrlProvider.promiseLiveUrl(LibraryId(2)) } returns urlProvider.toPromise() val libraryConnectionProvider = LibraryConnectionProvider( validateConnectionSettings, lookupConnection, NoopServerAlarm(), liveUrlProvider, OkHttpFactory ) val futureConnectionProvider = libraryConnectionProvider .promiseLibraryConnection(LibraryId(2)) .apply { progress.then(statuses::add) updates(statuses::add) } .toFuture() deferredConnectionSettings.resolve() connectionProvider = futureConnectionProvider.get() } } @Test fun thenGettingLibraryFailedIsBroadcast() { assertThat(statuses) .containsExactly( BuildingConnectionStatus.GettingLibrary, BuildingConnectionStatus.GettingLibraryFailed ) } @Test fun thenTheConnectionIsNull() { assertThat(connectionProvider).isNull() } }
lgpl-3.0
4c262040672b12193b0515d957ac81fb
37.4875
103
0.806106
5.114618
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/location/LocationPermission.kt
1
2191
package mil.nga.giat.mage.location import android.Manifest import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import androidx.activity.result.contract.ActivityResultContract import androidx.activity.result.contract.ActivityResultContracts data class LocationContractResult( val coarseGranted: Boolean, val preciseGranted: Boolean ) class LocationPermission : ActivityResultContract<Void?, LocationContractResult>() { private val permissions = arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) override fun createIntent(context: Context, input: Void?): Intent { return Intent(ActivityResultContracts.RequestMultiplePermissions.ACTION_REQUEST_PERMISSIONS) .putExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSIONS, permissions) } override fun parseResult(resultCode: Int, intent: Intent?): LocationContractResult { if (resultCode != Activity.RESULT_OK) return LocationContractResult( preciseGranted = false, coarseGranted = false ) if (intent == null) return LocationContractResult( preciseGranted = false, coarseGranted = false ) val permissions = intent.getStringArrayExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSIONS) val grantResults = intent.getIntArrayExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSION_GRANT_RESULTS) if (grantResults == null || permissions == null) return LocationContractResult( preciseGranted = false, coarseGranted = false ) val coarseIndex = permissions.indexOf(Manifest.permission.ACCESS_COARSE_LOCATION) val coarseGranted = grantResults[coarseIndex] == PackageManager.PERMISSION_GRANTED val preciseIndex = permissions.indexOf(Manifest.permission.ACCESS_FINE_LOCATION) val preciseGranted = grantResults[preciseIndex] == PackageManager.PERMISSION_GRANTED return LocationContractResult( preciseGranted = preciseGranted, coarseGranted = coarseGranted ) } }
apache-2.0
6faca0cf70e70ed37e5a4145d7d87660
38.142857
131
0.761753
5.216667
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/stats/EndpointConnectionStatsTest.kt
1
6083
/* * Copyright @ 2018 - present 8x8, 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 org.jitsi.nlj.stats import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.doubles.plusOrMinus import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import org.jitsi.nlj.resources.logging.StdoutLogger import org.jitsi.nlj.test_utils.timeline import org.jitsi.rtp.rtcp.RtcpReportBlock import org.jitsi.rtp.rtcp.RtcpRrPacket import org.jitsi.rtp.rtcp.RtcpSrPacket import org.jitsi.utils.ms import org.jitsi.utils.time.FakeClock import java.time.Duration class EndpointConnectionStatsTest : ShouldSpec() { override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf private val clock: FakeClock = FakeClock() private var mostRecentPublishedRtt: Double = -1.0 private var numRttUpdates: Int = 0 private val stats = EndpointConnectionStats(StdoutLogger(), clock).also { it.addListener(object : EndpointConnectionStats.EndpointConnectionStatsListener { override fun onRttUpdate(newRttMs: Double) { mostRecentPublishedRtt = newRttMs numRttUpdates++ } }) } init { context("after an SR is sent") { context("with a non-zero timestamp") { val srPacket = createSrPacket(senderInfoTs = 100) stats.rtcpPacketSent(srPacket) context("and an RR is received which refers to it") { clock.elapse(60.ms) val rrPacket = createRrPacket(lastSrTimestamp = 100, delaySinceLastSr = 50.ms) stats.rtcpPacketReceived(rrPacket, clock.instant()) context("the rtt") { should("be updated correctly") { mostRecentPublishedRtt shouldBe(10.0 plusOrMinus .1) } } } } context("with a timestamp of 0") { val srPacket = createSrPacket(senderInfoTs = 0) stats.rtcpPacketSent(srPacket) context("and an RR is received which refers to it") { context("with a non-zero delaySinceLastSr") { val rrPacket = createRrPacket(lastSrTimestamp = 0, delaySinceLastSr = 50.ms) clock.elapse(60.ms) stats.rtcpPacketReceived(rrPacket, clock.instant()) context("the rtt") { should("be updated correctly") { mostRecentPublishedRtt shouldBe(10.0.plusOrMinus(.1)) } } } context("with a delaySinceLastSr value of 0") { val rrPacket = createRrPacket(lastSrTimestamp = 0, delaySinceLastSr = 0.ms) clock.elapse(60.ms) stats.rtcpPacketReceived(rrPacket, clock.instant()) // This case is indistinguishable from no SR being received context("the rtt") { should("not have been updated") { numRttUpdates shouldBe 0 } } } } } } context("when a report block is received for which we can't find an SR") { val rrPacket = createRrPacket(lastSrTimestamp = 100, delaySinceLastSr = 50.ms) stats.rtcpPacketReceived(rrPacket, clock.instant()) context("the rtt") { should("not have been updated") { numRttUpdates shouldBe 0 } } } context("when a report block is received with a lastSrTimestamp of 0 but a non-zero delaySinceLastSr") { timeline(clock) { run { stats.rtcpPacketSent(createSrPacket(senderInfoTs = 0)) } elapse(60.ms) run { stats.rtcpPacketReceived( createRrPacket(lastSrTimestamp = 0, delaySinceLastSr = 50.ms), clock.instant() ) } }.run() context("the rtt") { should("be updated correctly") { mostRecentPublishedRtt shouldBe(10.0.plusOrMinus(.1)) } } } } // Takes a Duration and converts it to 1/65536ths of a second private fun Duration.toDelaySinceLastSrFraction(): Long = (toNanos() * .000065536).toLong() private fun createSrPacket(senderInfoTs: Long): RtcpSrPacket { val mockSenderInfo = mockk<RtcpSrPacket.SenderInfo> { every { compactedNtpTimestamp } returns senderInfoTs } return mockk { every { senderSsrc } returns 1234L every { senderInfo } returns mockSenderInfo } } private fun createRrPacket(lastSrTimestamp: Long, delaySinceLastSr: Duration): RtcpRrPacket { val reportBlock = mockk<RtcpReportBlock> { every { ssrc } returns 1234L every { [email protected] } returns lastSrTimestamp every { [email protected] } returns delaySinceLastSr.toDelaySinceLastSrFraction() } return mockk { every { reportBlocks } returns listOf(reportBlock) } } }
apache-2.0
a5ef6413d03db41f7b81800f4114a8a0
37.5
112
0.575538
4.704563
false
false
false
false
google-developer-training/android-basics-kotlin-sql-basics-app
app/src/main/java/com/example/sqlbasics/AppDatabase.kt
1
1529
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.sqlbasics import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = arrayOf(CaliforniaPark::class), version = 1) abstract class AppDatabase: RoomDatabase() { abstract fun californiaParkDao(): CaliforniaParkDao companion object { @Volatile private var INSTANCE: AppDatabase? = null fun getDatabase( context: Context ): AppDatabase { return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context, AppDatabase::class.java, "app_database" ) .createFromAsset("database/sql_basics.db") .build() INSTANCE = instance instance } } } }
apache-2.0
686ab367b8b89520487056fb46bee803
30.875
75
0.637672
4.838608
false
false
false
false
robinverduijn/gradle
buildSrc/subprojects/binary-compatibility/src/main/kotlin/org/gradle/binarycompatibility/sources/SourcesRepository.kt
1
4088
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.binarycompatibility.sources import com.github.javaparser.JavaParser import com.github.javaparser.ast.CompilationUnit import com.github.javaparser.ast.visitor.GenericVisitor import org.jetbrains.kotlin.psi.KtFile import parser.KotlinSourceParser import org.gradle.util.TextUtil.normaliseFileSeparators import java.io.File internal sealed class ApiSourceFile { internal abstract val currentFile: File internal abstract val currentSourceRoot: File data class Java internal constructor( override val currentFile: File, override val currentSourceRoot: File ) : ApiSourceFile() data class Kotlin internal constructor( override val currentFile: File, override val currentSourceRoot: File ) : ApiSourceFile() } internal data class JavaSourceQuery<T : Any?>( val defaultValue: T, val visitor: GenericVisitor<T, Unit?> ) internal class SourcesRepository( private val sourceRoots: List<File>, private val compilationClasspath: List<File> ) : AutoCloseable { private val openJavaCompilationUnitsByFile = mutableMapOf<File, CompilationUnit>() private val openKotlinCompilationUnitsByRoot = mutableMapOf<File, KotlinSourceParser.ParsedKotlinFiles>() fun <T : Any?> executeQuery(apiSourceFile: ApiSourceFile.Java, query: JavaSourceQuery<T>): T = openJavaCompilationUnitsByFile .computeIfAbsent(apiSourceFile.currentFile) { JavaParser.parse(it) } .accept(query.visitor, null) ?: query.defaultValue fun <T : Any?> executeQuery(apiSourceFile: ApiSourceFile.Kotlin, transform: (KtFile) -> T): T = apiSourceFile.normalizedPath.let { sourceNormalizedPath -> openKotlinCompilationUnitsByRoot .computeIfAbsent(apiSourceFile.currentSourceRoot) { KotlinSourceParser().parseSourceRoots( listOf(apiSourceFile.currentSourceRoot), compilationClasspath ) } .ktFiles .first { it.normalizedPath == sourceNormalizedPath } .let(transform) } override fun close() { val errors = mutableListOf<Exception>() openKotlinCompilationUnitsByRoot.values.forEach { unit -> try { unit.close() } catch (ex: Exception) { errors.add(ex) } } openJavaCompilationUnitsByFile.clear() openKotlinCompilationUnitsByRoot.clear() if (errors.isNotEmpty()) { throw Exception("Sources repository did not close cleanly").apply { errors.forEach(this::addSuppressed) } } } /** * @return the source file and it's source root */ fun sourceFileAndSourceRootFor(sourceFilePath: String): Pair<File, File> = sourceRoots.asSequence() .map { it.resolve(sourceFilePath) to it } .firstOrNull { it.first.isFile } ?: throw IllegalStateException("Source file '$sourceFilePath' not found, searched in source roots:\n${sourceRoots.joinToString("\n - ")}") private val KtFile.normalizedPath: String? get() = virtualFile.canonicalPath?.let { normaliseFileSeparators(it) } private val ApiSourceFile.normalizedPath: String get() = normaliseFileSeparators(currentFile.canonicalPath) }
apache-2.0
fef9c01fcb33a2868b1244b76645b3a6
28.839416
151
0.668053
4.849348
false
false
false
false
robinverduijn/gradle
subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/codecs/BuildOperationListenersCodec.kt
1
3092
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.instantexecution.serialization.codecs import org.gradle.instantexecution.extensions.uncheckedCast import org.gradle.instantexecution.serialization.ReadContext import org.gradle.instantexecution.serialization.WriteContext import org.gradle.instantexecution.serialization.beans.makeAccessible import org.gradle.instantexecution.serialization.readList import org.gradle.instantexecution.serialization.writeCollection import org.gradle.internal.operations.BuildOperationListener import org.gradle.internal.operations.BuildOperationListenerManager import org.gradle.internal.operations.DefaultBuildOperationListenerManager import java.lang.reflect.Field /** * Captures a white list of listeners. * * Only for gradle-profiler --benchmark-config-time for now. * * Makes assumptions on the manager implementation. */ internal class BuildOperationListenersCodec { companion object { private val classNameWhitelist = setOf( // Remove whitelisting this listener class when https://github.com/gradle/gradle-profiler/pull/140 has been merged "org.gradle.trace.buildops.BuildOperationTrace${'$'}RecordingListener", "org.gradle.trace.buildops.BuildOperationTrace${'$'}TimeToFirstTaskRecordingListener" ) } suspend fun WriteContext.writeBuildOperationListeners(manager: BuildOperationListenerManager) { writeCollection(manager.listeners) { listener -> write(listener) } } suspend fun ReadContext.readBuildOperationListeners(): List<BuildOperationListener> = readList().uncheckedCast() private val BuildOperationListenerManager.listeners: List<BuildOperationListener> get() = getListenersField().unwrapped().whiteListed() private fun BuildOperationListenerManager.getListenersField(): List<BuildOperationListener> = DefaultBuildOperationListenerManager::class.java .getDeclaredField("listeners") .also(Field::makeAccessible) .get(this) .uncheckedCast() private fun List<BuildOperationListener>.unwrapped() = map { listener -> listener.javaClass.getDeclaredField("delegate") .also(Field::makeAccessible) .get(listener) as BuildOperationListener } private fun List<BuildOperationListener>.whiteListed() = filter { it.javaClass.name in classNameWhitelist } }
apache-2.0
893165e43321964391bfad8fc00846cc
35.376471
126
0.734799
4.987097
false
false
false
false
mplatvoet/kovenant
projects/core/src/main/kotlin/bulk-jvm.kt
1
5376
/* * Copyright (c) 2015 Mark Platvoet<[email protected]> * * 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, * THE SOFTWARE. */ package nl.komponents.kovenant import java.util.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReferenceArray internal fun <V> concreteAll(vararg promises: Promise<V, Exception>, context: Context, cancelOthersOnError: Boolean): Promise<List<V>, Exception> { return concreteAll(promises.asSequence(), promises.size, context, cancelOthersOnError) } internal fun <V> concreteAll(promises: List<Promise<V, Exception>>, context: Context, cancelOthersOnError: Boolean): Promise<List<V>, Exception> { // this might fail with concurrent mutating list, revisit in the future // not really a Kovenant issue but can prevent this from ever completing return concreteAll(promises.asSequence(), promises.size, context, cancelOthersOnError) } internal fun <V> concreteAll(promises: Sequence<Promise<V, Exception>>, sequenceSize: Int, context: Context, cancelOthersOnError: Boolean): Promise<List<V>, Exception> { if (sequenceSize == 0) throw IllegalArgumentException("no promises provided") val deferred = deferred<List<V>, Exception>(context) val results = AtomicReferenceArray<V>(sequenceSize) val successCount = AtomicInteger(sequenceSize) val failCount = AtomicInteger(0) promises.forEachIndexed { i, promise -> promise.success { v -> results.set(i, v) if (successCount.decrementAndGet() == 0) { deferred.resolve(results.asList()) } } promise.fail { e -> if (failCount.incrementAndGet() == 1) { deferred.reject(e) if (cancelOthersOnError) { promises.forEach { if (it != promise && it is CancelablePromise) { it.cancel(CancelException()) } } } } } } return deferred.promise } internal fun <V> concreteAny(vararg promises: Promise<V, Exception>, context: Context, cancelOthersOnSuccess: Boolean): Promise<V, List<Exception>> { return concreteAny(promises.asSequence(), promises.size, context, cancelOthersOnSuccess) } internal fun <V> concreteAny(promises: List<Promise<V, Exception>>, context: Context, cancelOthersOnSuccess: Boolean): Promise<V, List<Exception>> { // this might fail with concurrent mutating list, revisit in the future // not really a Kovenant issue but can prevent this from ever completing return concreteAny(promises.asSequence(), promises.size, context, cancelOthersOnSuccess) } internal fun <V> concreteAny(promises: Sequence<Promise<V, Exception>>, sequenceSize: Int, context: Context, cancelOthersOnSuccess: Boolean): Promise<V, List<Exception>> { if (sequenceSize == 0) throw IllegalArgumentException("no promises provided") val deferred = deferred<V, List<Exception>>(context) val errors = AtomicReferenceArray<Exception>(sequenceSize) val successCount = AtomicInteger(0) val failCount = AtomicInteger(sequenceSize) promises.forEachIndexed { i, promise -> promise.success { v -> if (successCount.incrementAndGet() == 1) { deferred.resolve(v) if (cancelOthersOnSuccess) { promises.forEach { if (it != promise && it is CancelablePromise) { it.cancel(CancelException()) } } } } } promise.fail { e -> errors.set(i, e) if (failCount.decrementAndGet() == 0) { deferred.reject(errors.asList()) } } } return deferred.promise } private fun <V> AtomicReferenceArray<V>.asList(): List<V> { val list = ArrayList<V>() for (i in 0..this.length() - 1) { list.add(this.get(i)) } return list }
mit
65ed8dc1da693b229adff5a30d630699
38.240876
92
0.611979
4.963989
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/lang/refactoring/RsNamesValidator.kt
2
1218
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.refactoring import com.intellij.lang.refactoring.NamesValidator import com.intellij.openapi.project.Project import com.intellij.psi.tree.IElementType import org.rust.lang.core.lexer.RsLexer import org.rust.lang.core.psi.RS_KEYWORDS import org.rust.lang.core.psi.RsElementTypes.IDENTIFIER import org.rust.lang.core.psi.RsElementTypes.QUOTE_IDENTIFIER class RsNamesValidator : NamesValidator { override fun isKeyword(name: String, project: Project?): Boolean { return getLexerType(name) in RS_KEYWORDS } override fun isIdentifier(name: String, project: Project?): Boolean { return when (getLexerType(name)) { IDENTIFIER, QUOTE_IDENTIFIER -> true else -> false } } companion object { val PredefinedLifetimes = arrayOf("'static") } } fun isValidRustVariableIdentifier(name: String): Boolean = getLexerType(name) == IDENTIFIER private fun getLexerType(text: String): IElementType? { val lexer = RsLexer() lexer.start(text) return if (lexer.tokenEnd == text.length) lexer.tokenType else null }
mit
4dcdb3cb06c38d19481f905dacaa8dd0
28.707317
91
0.722496
4.033113
false
false
false
false
nestlabs/connectedhomeip
src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/util/DeviceIdUtil.kt
2
1097
package com.google.chip.chiptool.util import android.content.Context import android.content.SharedPreferences /** Utils for storing and accessing available device IDs using shared preferences. */ object DeviceIdUtil { private const val PREFERENCE_FILE_KEY = "com.google.chip.chiptool.PREFERENCE_FILE_KEY" private const val DEVICE_ID_PREFS_KEY = "device_id" private const val DEFAULT_DEVICE_ID = 1L fun getNextAvailableId(context: Context): Long { val prefs = getPrefs(context) return if (prefs.contains(DEVICE_ID_PREFS_KEY)) { prefs.getLong(DEVICE_ID_PREFS_KEY, DEFAULT_DEVICE_ID) } else { prefs.edit().putLong(DEVICE_ID_PREFS_KEY, DEFAULT_DEVICE_ID).apply() DEFAULT_DEVICE_ID } } fun setNextAvailableId(context: Context, newId: Long) { getPrefs(context).edit().putLong(DEVICE_ID_PREFS_KEY, newId).apply() } fun getLastDeviceId(context: Context): Long = getNextAvailableId(context) - 1 private fun getPrefs(context: Context): SharedPreferences { return context.getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE) } }
apache-2.0
0a7b921e7b56b14fef05b0b1836c4a00
34.387097
88
0.738377
3.849123
false
false
false
false
GyrosWorkshop/WukongAndroid
wukong/src/main/java/com/senorsen/wukong/network/message/Protocol.kt
1
985
package com.senorsen.wukong.network.message import com.senorsen.wukong.model.Song import com.senorsen.wukong.model.User data class WebSocketTransmitProtocol( val channelId: String, val eventName: String ) data class WebSocketReceiveProtocol( val channelId: String? = null, val eventName: String? = null, val song: Song? = null, val downvote: Boolean? = null, val elapsed: Float, val user: String? = null, val users: List<User>? = null, val notification: Notification? = null, val cause: String? = null ) object Protocol { val PLAY: String get() = "Play" val PRELOAD: String get() = "Preload" val USER_LIST_UPDATE: String get() = "UserListUpdated" val NOTIFICATION: String get() = "Notification" val DISCONNECT: String get() = "Disconnect" } data class Notification( var message: String?, var timeout: Int )
agpl-3.0
a84b7ac61f2e0d2c14d3d74514750a22
19.122449
47
0.615228
4.121339
false
false
false
false
tmarsteel/compiler-fiddle
src/compiler/lexer/lexer.kt
1
6502
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.lexer import compiler.transact.SourceFileReader import compiler.transact.TransactionalSequence import java.util.* class Lexer(code: String, private val sourceDescriptor: SourceDescriptor) { private val sourceTxSequence = SourceFileReader(code) /** * @return The nextToken token from the input or `null` if there are no more tokens. */ @Synchronized fun nextToken(): Token? { skipWhitespace() if (!hasNext) return null // try to match an operator val operator = tryMatchOperator() if (operator != null) return operator if (!hasNext) return null if (sourceTxSequence.peek()!!.isDigit()) { // NUMERIC_LITERAL var numericStr = collectUntilOperatorOrWhitespace() sourceTxSequence.mark() if (sourceTxSequence.peek() == DECIMAL_SEPARATOR) { // skip the dot sourceTxSequence.next() if (sourceTxSequence.peek()?.isDigit() ?: true) { // <DIGIT, ...> <DOT> <DIGIT, ...> => Floating point literal sourceTxSequence.commit() // floating point literal numericStr += DECIMAL_SEPARATOR + collectUntilOperatorOrWhitespace() // return numericStr later } else { // <DIGIT, ...> <DOT> <!DIGIT, ...> => member access on numeric literal // rollback before the ., so that the next invocation yields an OperatorToken sourceTxSequence.rollback() // return numericStr later } } return NumericLiteralToken(currentSL.minusChars(numericStr.length), numericStr) } else { // IDENTIFIER or KEYWORD val text = collectUntilOperatorOrWhitespace() // check against keywords val keyword = Keyword.values().firstOrNull { it.text.equals(text, true) } if (keyword != null) return KeywordToken(keyword, text, currentSL.minusChars(text.length)) return IdentifierToken(text, currentSL.minusChars(text.length)) } } private val hasNext: Boolean get() = sourceTxSequence.hasNext() private fun nextChar(): Char? = sourceTxSequence.next() private fun nextChars(n: Int): String? = sourceTxSequence.next(n) private fun <T> transact(txCode: TransactionalSequence<Char, SourceFileReader.SourceLocation>.TransactionReceiver.() -> T): T? = sourceTxSequence.transact(txCode) /** * Collects chars from the input as long as they fulfill [pred]. If a character is encountered that does not * fulfill the predicate, the collecting is stopped and the characters collected so far are returned. The character * causing the break can then be obtained using [nextChar]. */ private fun collectWhile(pred: (Char) -> Boolean): String? { var buf = StringBuilder() var char: Char? while (true) { sourceTxSequence.mark() char = sourceTxSequence.next() if (char != null && pred(char)) { buf.append(char) sourceTxSequence.commit() } else { sourceTxSequence.rollback() break } } return buf.toString() } private fun collectUntilOperatorOrWhitespace(): String { var buf = StringBuilder() while (sourceTxSequence.hasNext()) { val operator = tryMatchOperator(false) if (operator != null) break if (IsWhitespace(sourceTxSequence.peek()!!)) break buf.append(sourceTxSequence.next()!!) } return buf.toString() } private fun tryMatchOperator(doCommit: Boolean = true): OperatorToken? { for (operator in Operator.values()) { sourceTxSequence.mark() val nextText = nextChars(operator.text.length) if (nextText != null && nextText == operator.text) { if (doCommit) sourceTxSequence.commit() else sourceTxSequence.rollback() return OperatorToken(operator, currentSL.minusChars(nextText.length)) } sourceTxSequence.rollback() } return null } /** Skips whitespace according to [IsWhitespace]. Equals `collectWhile(IsWhitespace)` */ private fun skipWhitespace() { collectWhile(IsWhitespace) } private val currentSL: SourceLocation get() = sourceDescriptor.toLocation( sourceTxSequence.currentPosition.lineNumber, sourceTxSequence.currentPosition.columnNumber ) } /** * Lexes the given code. The resulting tokens use the given [SourceDescriptor] to refer to their location in the * source. */ public fun lex(code: String, sD: SourceDescriptor): Sequence<Token> { val lexer = Lexer(code, sD) return lexer.remainingTokens() } /** * Lexes the given code. */ public fun lex(source: SourceContentAwareSourceDescriptor): Sequence<Token> { val code = source.sourceLines.joinToString("\n") val lexer = Lexer(code, source) return lexer.remainingTokens() } /** * Collects all the remaining tokens of the compiler.lexer into a collection and returns it. */ public fun Lexer.remainingTokens(): Sequence<Token> { val tokens = LinkedList<Token>() while (true) { val token = nextToken() if (token != null) { tokens.add(token) } else { break } } return tokens.asSequence() }
lgpl-3.0
26eaa6d36e2594fc204df4ceb77c215f
30.721951
166
0.615811
4.732169
false
false
false
false
Ekito/koin
koin-projects/koin-core/src/main/kotlin/org/koin/core/parameter/DefinitionParameters.kt
1
3956
/* * Copyright 2017-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.core.parameter import org.koin.core.error.DefinitionParameterException import org.koin.core.error.NoParameterFoundException import org.koin.core.parameter.DefinitionParameters.Companion.MAX_PARAMS import org.koin.ext.getFullName import kotlin.reflect.KClass /** * DefinitionParameters - Parameter holder * Usable with exploded declaration * * @author - Arnaud GIULIANI */ @Suppress("UNCHECKED_CAST") open class DefinitionParameters(val values: List<Any?> = listOf()) { open fun <T> elementAt(i: Int, clazz: KClass<*>): T = if (values.size > i) values[i] as T else throw NoParameterFoundException( "Can't get injected parameter #$i from $this for type '${clazz.getFullName()}'") inline operator fun <reified T> component1(): T = elementAt(0, T::class) inline operator fun <reified T> component2(): T = elementAt(1, T::class) inline operator fun <reified T> component3(): T = elementAt(2, T::class) inline operator fun <reified T> component4(): T = elementAt(3, T::class) inline operator fun <reified T> component5(): T = elementAt(4, T::class) /** * get element at given index * return T */ operator fun <T> get(i: Int) = values[i] as T fun <T> set(i: Int, t: T) { values.toMutableList()[i] = t as Any } /** * Number of contained elements */ fun size() = values.size /** * Tells if it has no parameter */ fun isEmpty() = size() == 0 /** * Tells if it has parameters */ fun isNotEmpty() = !isEmpty() fun insert(index: Int, value: Any): DefinitionParameters { val (start, end) = values.partition { element -> values.indexOf(element) < index } return DefinitionParameters(start + value + end) } fun add(value: Any): DefinitionParameters { return insert(size(), value) } /** * Get first element of given type T * return T */ inline fun <reified T : Any> get(): T = getOrNull(T::class) ?: throw DefinitionParameterException("No value found for type '${T::class.getFullName()}'") /** * Get first element of given type T * return T */ open fun <T : Any> getOrNull(clazz: KClass<T>): T? { val values = values.filterNotNull().filter { it::class == clazz } return when (values.size) { 1 -> values.first() as T 0 -> null else -> throw DefinitionParameterException( "Ambiguous parameter injection: more than one value of type '${clazz.getFullName()}' to get from $this. Check your injection parameters") } } companion object { const val MAX_PARAMS = 5 } override fun toString(): String = "DefinitionParameters${values.toList()}" } /** * Build a DefinitionParameters * * @see parameters * return ParameterList */ fun parametersOf(vararg parameters: Any?) = if (parameters.size <= MAX_PARAMS) DefinitionParameters( parameters.toMutableList()) else throw DefinitionParameterException( "Can't build DefinitionParameters for more than $MAX_PARAMS arguments") /** * */ fun emptyParametersHolder() = DefinitionParameters() /** * Help define a DefinitionParameters */ typealias ParametersDefinition = () -> DefinitionParameters
apache-2.0
d077fe97fbf9c7f6ee9f3ea821eb7d51
30.91129
157
0.653185
4.240086
false
false
false
false
clhols/zapr
app/src/main/java/dk/youtec/zapr/util/ui.kt
1
956
package dk.youtec.zapr.util import android.graphics.PorterDuff import android.view.MenuItem /** * Sets the color filter and/or the alpha transparency on a [MenuItem]'s icon. * @param menuItem * * The [MenuItem] to theme. * * * @param color * * The color to set for the color filter or `null` for no changes. * * * @param alpha * * The alpha value (0...255) to set on the icon or `null` for no changes. */ fun colorMenuItem(menuItem: MenuItem, color: Int?, alpha: Int?) { if (color == null && alpha == null) { return // nothing to do. } val drawable = menuItem.icon if (drawable != null) { // If we don't mutate the drawable, then all drawables with this id will have the ColorFilter drawable.mutate() if (color != null) { drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP) } if (alpha != null) { drawable.alpha = alpha } } }
mit
367569063856cb1b267d970fec613ca4
28
101
0.609833
3.793651
false
false
false
false
denisrmp/hacker-rank
hacker-rank/hashmaps/SherlockAndAnagrams.kt
1
645
// https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem fun main() { val queries = readLine().orEmpty().trim().toInt() (0 until queries).forEach { val a = readLine().orEmpty().trim() println(countAnagrams(a)) } } fun countAnagrams(chars: String): Int { val map = HashMap<String, Int>() for (setSize in 1 until chars.length) { for (i in 0..chars.length - setSize) { val key = String(chars.substring(i, i + setSize).toCharArray().sortedArray()) map[key] = map.getOrDefault(key, 0) + 1 } } return map.values.map { (it * (it - 1))/2 }.sum() }
mit
2cb2d5456c7ccb4d69d098657dfa79f1
24.8
89
0.586047
3.486486
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/data/models/LiteTournament.kt
1
1028
package com.garpr.android.data.models import android.os.Parcelable import com.garpr.android.extensions.createParcel import com.garpr.android.extensions.requireParcelable import com.garpr.android.extensions.requireString import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class LiteTournament( @Json(name = "regions") regions: List<String>? = null, @Json(name = "date") date: SimpleDate, @Json(name = "id") id: String, @Json(name = "name") name: String ) : AbsTournament( regions, date, id, name ), Parcelable { override val kind: Kind get() = Kind.LITE companion object { @JvmField val CREATOR = createParcel { LiteTournament( it.createStringArrayList(), it.requireParcelable(SimpleDate::class.java.classLoader), it.requireString(), it.requireString() ) } } }
unlicense
d104d75e9e5d32f9986de3d53723dac7
26.052632
77
0.611868
4.431034
false
false
false
false
http4k/http4k
src/docs/guide/howto/use_multipart_forms/example_standard.kt
1
1560
package guide.howto.use_multipart_forms import org.http4k.client.ApacheClient import org.http4k.core.ContentType import org.http4k.core.Method.POST import org.http4k.core.MultipartFormBody import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.lens.MultipartFormField import org.http4k.lens.MultipartFormFile import org.http4k.server.SunHttp import org.http4k.server.asServer fun main() { // extract the body from the request and then the fields/files from it val server = { r: Request -> val receivedForm = MultipartFormBody.from(r) println(receivedForm.fieldValues("field")) println(receivedForm.field("field2")) println(receivedForm.files("file")) Response(OK) }.asServer(SunHttp(8000)).start() // add fields and files to the multipart form body val body = MultipartFormBody() .plus("field" to "my-value") .plus("field2" to MultipartFormField("my-value2", listOf("my-header" to "my-value"))) .plus( "file" to MultipartFormFile( "image.txt", ContentType.OCTET_STREAM, "somebinarycontent".byteInputStream() ) ) // we need to set both the body AND the correct content type header on the the request val request = Request(POST, "http://localhost:8000") .header("content-type", "multipart/form-data; boundary=${body.boundary}") .body(body) println(ApacheClient()(request)) server.stop() }
apache-2.0
8fe1604819fc4734f1620711c51f6a2f
32.191489
93
0.678205
3.890274
false
false
false
false
alashow/music-android
modules/data/src/main/java/tm/alashow/datmusic/data/db/AppTypeConverters.kt
1
3134
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.data.db import androidx.room.TypeConverter import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.Json import tm.alashow.datmusic.data.repos.album.DatmusicAlbumParams import tm.alashow.datmusic.data.repos.artist.DatmusicArtistParams import tm.alashow.datmusic.data.repos.search.DatmusicSearchParams import tm.alashow.datmusic.domain.entities.Album import tm.alashow.datmusic.domain.entities.Artist import tm.alashow.datmusic.domain.entities.Audio import tm.alashow.datmusic.domain.entities.DownloadRequest import tm.alashow.datmusic.domain.entities.Genre object AppTypeConverters { @TypeConverter @JvmStatic fun fromDatmusicSearchParams(params: DatmusicSearchParams) = params.toString() @TypeConverter @JvmStatic fun fromArtistSearchParams(params: DatmusicArtistParams) = params.toString() @TypeConverter @JvmStatic fun fromAlbumSearchParams(params: DatmusicAlbumParams) = params.toString() @TypeConverter @JvmStatic fun toAudioList(value: String): List<Audio> = Json.decodeFromString(ListSerializer(Audio.serializer()), value) @TypeConverter @JvmStatic fun fromAudioList(value: List<Audio>): String = Json.encodeToString(ListSerializer(Audio.serializer()), value) @TypeConverter @JvmStatic fun toArtistList(value: String): List<Artist> = Json.decodeFromString(ListSerializer(Artist.serializer()), value) @TypeConverter @JvmStatic fun fromArtistList(value: List<Artist>): String = Json.encodeToString(ListSerializer(Artist.serializer()), value) @TypeConverter @JvmStatic fun toAlbumList(value: String): List<Album> = Json.decodeFromString(ListSerializer(Album.serializer()), value) @TypeConverter @JvmStatic fun fromAlbumList(value: List<Album>): String = Json.encodeToString(ListSerializer(Album.serializer()), value) @TypeConverter @JvmStatic fun toAlbumPhoto(value: String): Album.Photo = Json.decodeFromString(Album.Photo.serializer(), value) @TypeConverter @JvmStatic fun fromAlbumPhoto(value: Album.Photo): String = Json.encodeToString(Album.Photo.serializer(), value) @TypeConverter @JvmStatic fun toArtistPhoto(value: String): List<Artist.Photo> = Json.decodeFromString(ListSerializer(Artist.Photo.serializer()), value) @TypeConverter @JvmStatic fun fromArtistPhoto(value: List<Artist.Photo>?): String = Json.encodeToString(ListSerializer(Artist.Photo.serializer()), value ?: emptyList()) @TypeConverter @JvmStatic fun toGenres(value: String): List<Genre> = Json.decodeFromString(ListSerializer(Genre.serializer()), value) @TypeConverter @JvmStatic fun fromGenres(value: List<Genre>): String = Json.encodeToString(ListSerializer(Genre.serializer()), value) @TypeConverter @JvmStatic fun toDownloadType(value: String): DownloadRequest.Type = DownloadRequest.Type.from(value) @TypeConverter @JvmStatic fun fromDownloadType(value: DownloadRequest.Type): String = value.name }
apache-2.0
184c5060c5689cb6e4dca75b9d93b19e
34.613636
146
0.761008
4.483548
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/extensions/Activity.kt
1
3458
package com.boardgamegeek.extensions import android.app.Activity import android.graphics.Insets import android.os.Build import android.util.DisplayMetrics import android.view.View import android.view.WindowInsets import androidx.annotation.StringRes import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.app.ShareCompat import com.boardgamegeek.R import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.logEvent fun Activity.shareGame(gameId: Int, gameName: String, method: String, firebaseAnalytics: FirebaseAnalytics? = null) { val subject = resources.getString(R.string.share_game_subject, gameName) val text = "${resources.getString(R.string.share_game_text)}\n\n${formatGameLink(gameId, gameName)}" share(subject, text, R.string.title_share_game) firebaseAnalytics?.logEvent(FirebaseAnalytics.Event.SHARE) { param(FirebaseAnalytics.Param.METHOD, method) param(FirebaseAnalytics.Param.ITEM_ID, gameId.toString()) param(FirebaseAnalytics.Param.ITEM_NAME, gameName) param(FirebaseAnalytics.Param.CONTENT_TYPE, "Game") } } fun Activity.shareGames(games: List<Pair<Int, String>>, method: String, firebaseAnalytics: FirebaseAnalytics? = null) { val text = StringBuilder(resources.getString(R.string.share_games_text)) text.append("\n\n") val gameNames = arrayListOf<String>() val gameIds = arrayListOf<Int>() for (game in games) { text.append(formatGameLink(game.first, game.second)) gameNames.add(game.second) gameIds.add(game.first) } share(resources.getString(R.string.share_games_subject), text.toString(), R.string.title_share_games) firebaseAnalytics?.logEvent(FirebaseAnalytics.Event.SHARE) { param(FirebaseAnalytics.Param.METHOD, method) param(FirebaseAnalytics.Param.ITEM_ID, gameIds.formatList()) param(FirebaseAnalytics.Param.ITEM_NAME, gameNames.formatList()) param(FirebaseAnalytics.Param.CONTENT_TYPE, "Games") } } fun Activity.share(subject: String, text: CharSequence, @StringRes titleResId: Int = R.string.title_share) { startActivity( ShareCompat.IntentBuilder(this) .setType("text/plain") .setSubject(subject.trim()) .setText(text) .setChooserTitle(titleResId) .createChooserIntent() ) } fun formatGameLink(id: Int, name: String) = "$name (${createBggUri(BOARDGAME_PATH, id)})\n" fun AppCompatActivity.setDoneCancelActionBarView(listener: View.OnClickListener?) { val toolbar = findViewById<Toolbar>(R.id.toolbar_done_cancel) ?: return toolbar.setContentInsetsAbsolute(0, 0) toolbar.findViewById<View>(R.id.menu_cancel).setOnClickListener(listener) toolbar.findViewById<View>(R.id.menu_done).setOnClickListener(listener) setSupportActionBar(toolbar) } @Suppress("DEPRECATION") fun Activity.calculateScreenWidth(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val windowMetrics = windowManager.currentWindowMetrics val insets: Insets = windowMetrics.windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars()) windowMetrics.bounds.width() - insets.left - insets.right } else { val displayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displayMetrics) displayMetrics.widthPixels } }
gpl-3.0
4a4a17d5aee17c0fa37db4762d6487a2
41.691358
119
0.73742
4.201701
false
false
false
false
Kotlin/kotlinx.serialization
core/commonMain/src/kotlinx/serialization/SerialFormat.kt
1
8802
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization import kotlinx.serialization.internal.* import kotlinx.serialization.encoding.* import kotlinx.serialization.modules.* /** * Represents an instance of a serialization format * that can interact with [KSerializer] and is a supertype of all entry points for a serialization. * It does not impose any restrictions on a serialized form or underlying storage, neither it exposes them. * * Concrete data types and API for user-interaction are responsibility of a concrete subclass or subinterface, * for example [StringFormat], [BinaryFormat] or `Json`. * * Typically, formats have their specific [Encoder] and [Decoder] implementations * as private classes and do not expose them. * * ### Exception types for `SerialFormat` implementation * * Methods responsible for format-specific encoding and decoding are allowed to throw * any subtype of [IllegalArgumentException] in order to indicate serialization * and deserialization errors. It is recommended to throw subtypes of [SerializationException] * for encoder and decoder specific errors and [IllegalArgumentException] for input * and output validation-specific errors. * * For formats * * ### Not stable for inheritance * * `SerialFormat` interface is not stable for inheritance in 3rd party libraries, as new methods * might be added to this interface or contracts of the existing methods can be changed. * * It is safe to operate with instances of `SerialFormat` and call its methods. */ public interface SerialFormat { /** * Contains all serializers registered by format user for [Contextual] and [Polymorphic] serialization. * * The same module should be exposed in the format's [Encoder] and [Decoder]. */ public val serializersModule: SerializersModule } /** * [SerialFormat] that allows conversions to and from [ByteArray] via [encodeToByteArray] and [decodeFromByteArray] methods. * * ### Not stable for inheritance * * `BinaryFormat` interface is not stable for inheritance in 3rd party libraries, as new methods * might be added to this interface or contracts of the existing methods can be changed. * * It is safe to operate with instances of `BinaryFormat` and call its methods. */ public interface BinaryFormat : SerialFormat { /** * Serializes and encodes the given [value] to byte array using the given [serializer]. * * @throws SerializationException in case of any encoding-specific error * @throws IllegalArgumentException if the encoded input does not comply format's specification */ public fun <T> encodeToByteArray(serializer: SerializationStrategy<T>, value: T): ByteArray /** * Decodes and deserializes the given [byte array][bytes] to the value of type [T] using the given [deserializer]. * * @throws SerializationException in case of any decoding-specific error * @throws IllegalArgumentException if the decoded input is not a valid instance of [T] */ public fun <T> decodeFromByteArray(deserializer: DeserializationStrategy<T>, bytes: ByteArray): T } /** * [SerialFormat] that allows conversions to and from [String] via [encodeToString] and [decodeFromString] methods. * * ### Not stable for inheritance * * `StringFormat` interface is not stable for inheritance in 3rd party libraries, as new methods * might be added to this interface or contracts of the existing methods can be changed. * * It is safe to operate with instances of `StringFormat` and call its methods. */ public interface StringFormat : SerialFormat { /** * Serializes and encodes the given [value] to string using the given [serializer]. * * @throws SerializationException in case of any encoding-specific error * @throws IllegalArgumentException if the encoded input does not comply format's specification */ public fun <T> encodeToString(serializer: SerializationStrategy<T>, value: T): String /** * Decodes and deserializes the given [string] to the value of type [T] using the given [deserializer]. * * @throws SerializationException in case of any decoding-specific error * @throws IllegalArgumentException if the decoded input is not a valid instance of [T] */ public fun <T> decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T } /** * Serializes and encodes the given [value] to string using serializer retrieved from the reified type parameter. * * @throws SerializationException in case of any encoding-specific error * @throws IllegalArgumentException if the encoded input does not comply format's specification */ public inline fun <reified T> StringFormat.encodeToString(value: T): String = encodeToString(serializersModule.serializer(), value) /** * Decodes and deserializes the given [string] to the value of type [T] using deserializer * retrieved from the reified type parameter. * * @throws SerializationException in case of any decoding-specific error * @throws IllegalArgumentException if the decoded input is not a valid instance of [T] */ public inline fun <reified T> StringFormat.decodeFromString(string: String): T = decodeFromString(serializersModule.serializer(), string) /** * Serializes and encodes the given [value] to byte array, delegating it to the [BinaryFormat], * and then encodes resulting bytes to hex string. * * Hex representation does not interfere with serialization and encoding process of the format and * only applies transformation to the resulting array. It is recommended to use for debugging and * testing purposes. * * @throws SerializationException in case of any encoding-specific error * @throws IllegalArgumentException if the encoded input does not comply format's specification */ public fun <T> BinaryFormat.encodeToHexString(serializer: SerializationStrategy<T>, value: T): String = InternalHexConverter.printHexBinary(encodeToByteArray(serializer, value), lowerCase = true) /** * Decodes byte array from the given [hex] string and the decodes and deserializes it * to the value of type [T], delegating it to the [BinaryFormat]. * * This method is a counterpart to [encodeToHexString]. * * @throws SerializationException in case of any decoding-specific error * @throws IllegalArgumentException if the decoded input is not a valid instance of [T] */ public fun <T> BinaryFormat.decodeFromHexString(deserializer: DeserializationStrategy<T>, hex: String): T = decodeFromByteArray(deserializer, InternalHexConverter.parseHexBinary(hex)) /** * Serializes and encodes the given [value] to byte array, delegating it to the [BinaryFormat], * and then encodes resulting bytes to hex string. * * Hex representation does not interfere with serialization and encoding process of the format and * only applies transformation to the resulting array. It is recommended to use for debugging and * testing purposes. * * @throws SerializationException in case of any encoding-specific error * @throws IllegalArgumentException if the encoded input does not comply format's specification */ public inline fun <reified T> BinaryFormat.encodeToHexString(value: T): String = encodeToHexString(serializersModule.serializer(), value) /** * Decodes byte array from the given [hex] string and the decodes and deserializes it * to the value of type [T], delegating it to the [BinaryFormat]. * * This method is a counterpart to [encodeToHexString]. * * @throws SerializationException in case of any decoding-specific error * @throws IllegalArgumentException if the decoded input is not a valid instance of [T] */ public inline fun <reified T> BinaryFormat.decodeFromHexString(hex: String): T = decodeFromHexString(serializersModule.serializer(), hex) /** * Serializes and encodes the given [value] to byte array using serializer * retrieved from the reified type parameter. * * @throws SerializationException in case of any encoding-specific error * @throws IllegalArgumentException if the encoded input does not comply format's specification */ public inline fun <reified T> BinaryFormat.encodeToByteArray(value: T): ByteArray = encodeToByteArray(serializersModule.serializer(), value) /** * Decodes and deserializes the given [byte array][bytes] to the value of type [T] using deserializer * retrieved from the reified type parameter. * * @throws SerializationException in case of any decoding-specific error * @throws IllegalArgumentException if the decoded input is not a valid instance of [T] */ public inline fun <reified T> BinaryFormat.decodeFromByteArray(bytes: ByteArray): T = decodeFromByteArray(serializersModule.serializer(), bytes)
apache-2.0
fae8a8553207560d1fcdabc7725c963c
43.908163
124
0.759486
4.747573
false
false
false
false
googlecodelabs/watchnext-for-movie-tv-episodes
step_4_completed/src/main/java/com/android/tv/reference/parser/VideoParser.kt
8
1443
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference.parser import com.android.tv.reference.shared.datamodel.ApiResponse import com.android.tv.reference.shared.datamodel.Video import com.squareup.moshi.Moshi import com.squareup.moshi.Types object VideoParser { fun loadVideosFromJson(jsonString: String): List<Video> { val moshi = Moshi.Builder().build() val type = Types.newParameterizedType(ApiResponse::class.java, Video::class.java) val adapter = moshi.adapter<ApiResponse<Video>>(type) return adapter.fromJson(jsonString)!!.content } fun findVideoFromJson(jsonString: String, videoId: String): Video? { val videosList = loadVideosFromJson(jsonString) for (video in videosList) { if (video.id == videoId) { return video } } return null } }
apache-2.0
e178b3a0ecff108f7f3f1c36de69bb60
34.195122
89
0.70201
4.269231
false
false
false
false
aucd29/common
library/src/main/java/net/sarangnamu/common/arch/viewmodel/DialogViewModel.kt
1
1482
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * 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 net.sarangnamu.common.arch.viewmodel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.databinding.ObservableField /** * Created by <a href="mailto:[email protected]">Burke Choi</a> on 2018. 5. 4.. <p/> * * 커스텀 다이얼로그를 이용할 때 사용 * * ```kotlin * YourViewBinding binding = inflateBinding(R.layout.your_view) * DialogViewModel model = ViewModelProviders.of(this).get(DialogViewModel.class) * * model.init() * model.title.set($title) * model.message.set($message) * model.dismiss.observe(this, result -> dialog.dismiss()); * * binding.setModel(model) * * ``` */ open class DialogViewModel : DismissViewModel() { protected var title = ObservableField<String>() protected var message = ObservableField<String>() }
apache-2.0
5e079cc8297cd20819ee99b94712b662
30.565217
83
0.72314
3.723077
false
false
false
false
FirebaseExtended/auth-without-play-services
app/src/main/java/com/google/firebase/nongmsauth/MainActivity.kt
1
3223
/** * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.nongmsauth import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.google.android.material.snackbar.Snackbar import com.google.firebase.FirebaseApp import com.google.firebase.firestore.FirebaseFirestore import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private lateinit var auth: FirebaseRestAuth private lateinit var refresher: FirebaseTokenRefresher override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val app = FirebaseApp.getInstance() auth = FirebaseRestAuth.getInstance(app) auth.tokenRefresher.bindTo(this) getDocButton.setOnClickListener { getDocument() } signInButton.setOnClickListener { signInAnonymously() } signOutButton.setOnClickListener { signOut() } updateUI() } private fun signInAnonymously() { auth.signInAnonymously() .addOnSuccessListener { res -> Log.d(TAG, "signInAnonymously: $res") updateUI() } .addOnFailureListener { err -> Log.w(TAG, "signInAnonymously: failure", err) updateUI() } } private fun signOut() { auth.signOut() updateUI() } private fun getDocument() { FirebaseFirestore.getInstance().collection("test").document("test").get() .addOnCompleteListener { it.exception?.let { e -> Log.e(TAG, "get failed", e) snackbar("Error retrieving document...") return@addOnCompleteListener } it.result?.let { res -> Log.d(TAG, "get success: $res") snackbar("Successfully retrieved document!") } } } private fun updateUI() { val user = auth.currentUser val signedIn = user != null signInButton.isEnabled = !signedIn signOutButton.isEnabled = signedIn if (user == null) { authStatus.text = "Signed out." } else { authStatus.text = "Signed in as ${user.userId}" } } private fun snackbar(msg: String) { Snackbar.make(findViewById(android.R.id.content), msg, Snackbar.LENGTH_SHORT).show() } companion object { private val TAG = MainActivity::class.java.simpleName } }
apache-2.0
ae28a1d33d184bad6809013350d17121
28.851852
92
0.618058
4.890744
false
false
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/ui/lists/FriendsAdapter.kt
1
2060
package com.duopoints.android.ui.lists import android.view.View import com.duopoints.android.MainAct import com.duopoints.android.R import com.duopoints.android.fragments.userprofile.UserProfileFrag import com.duopoints.android.rest.models.composites.CompositeFriendship import com.duopoints.android.rest.models.dbviews.UserData import com.duopoints.android.ui.lists.base.BaseAdapterDelegate import com.duopoints.android.ui.lists.base.BaseViewHolder import com.duopoints.android.ui.views.UserThinView import com.duopoints.android.utils.JavaUtils import com.duopoints.android.utils.logging.LogLevel import com.duopoints.android.utils.logging.log import java.util.* class FriendsAdapter(private val seeingAsUserID: UUID) : BaseAdapterDelegate<CompositeFriendship, FriendsAdapter.UserSearchHolder>(CompositeFriendship::class.java, R.layout.list_friend_item) { override fun bindViewHolder(friendship: CompositeFriendship, holder: UserSearchHolder) { val userData: UserData if (friendship.userOneUuid == seeingAsUserID) { userData = friendship.userTwo } else if (friendship.userTwoUuid == seeingAsUserID) { userData = friendship.userOne } else { javaClass.log(LogLevel.ERROR, "Perspective User not found in Friendships! Error!") return } holder.userThinView.setUserImage(userData.userUuid) holder.userThinView.setUserTitle(JavaUtils.getUserName(userData, true)) holder.userThinView.setUserSubtitle(userData.userTotalPoints.toString() + " Points") holder.userThinView.setUserSubSubtitle("Level " + userData.userLevelNumber) holder.root.setOnClickListener { v -> (holder.context as MainAct).addFragment(UserProfileFrag.newInstance(userData), true) } } override fun createViewHolder(view: View): UserSearchHolder { return UserSearchHolder(view) } class UserSearchHolder(itemView: View) : BaseViewHolder(itemView) { var userThinView: UserThinView = itemView.findViewById(R.id.friend_item) } }
gpl-3.0
f81106cf752968fca0eee20c82f00055
43.782609
192
0.762136
4.212679
false
false
false
false
t-ray/malbec
src/main/kotlin/malbec/core/api/InstallationController.kt
1
1620
package malbec.core.api import malbec.core.biz.InstallationsService import malbec.core.domain.FileInstallation import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/installations") open class InstallationController( val installationService: InstallationsService) { @GetMapping fun all() = installationService.selectAll() @GetMapping("/{id}") fun find(@PathVariable id: Int): FileInstallation { val r = installationService.find(id) return when { r.isRight() -> r.right().get() else -> throw r.left().get() } } //END find @PutMapping("/add") fun add(@Validated @RequestBody item: FileInstallation): FileInstallation { val added = installationService.insert(item) return added } //END add @PutMapping("/{id}") fun edit(@PathVariable id: Int, @RequestBody item: FileInstallation): FileInstallation { println("Editing item, id=$id, body=$item") val edited = installationService.update(item.copy(id = id)) return when { edited.isRight() -> edited.right().get() else -> throw edited.left().get() } } //END edit @DeleteMapping("/{id}") fun delete(@PathVariable id: Int): Int { println("deleting $id") val deleted = installationService.delete(id) return when { deleted.isRight() -> deleted.right().get() else -> throw deleted.left().get() } } //END delete } //END InstallationController
mit
acfa09a2e9ec2cbcbf1dcdea1dcec31e
29.566038
92
0.635185
4.438356
false
false
false
false
asamm/locus-api
locus-api-android/src/main/java/locus/api/android/utils/IntentHelper.kt
1
12951
/**************************************************************************** * * Created by menion on 07/02/2019. * Copyright (c) 2019. All rights reserved. * * This file is part of the Asamm team software. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * ***************************************************************************/ package locus.api.android.utils import android.app.Activity import android.content.Context import android.content.Intent import locus.api.android.ActionBasics import locus.api.android.objects.LocusVersion import locus.api.android.utils.exceptions.RequiredVersionMissingException import locus.api.objects.extra.Location import locus.api.objects.geoData.Point import locus.api.objects.geoData.Track import locus.api.utils.Logger /** * Methods useful for handling received results from Locus based app. */ @Suppress("unused", "MemberVisibilityCanBePrivate") object IntentHelper { // tag for logger private const val TAG = "ResponseHelper" //************************************************* // MAIN FUNCTIONS //************************************************* /** * Check if received intent is response on MAIN_FUNCTION intent. * * @param intent received intent * @return `true` if intent is base on MAIN_FUNCTION parameter */ fun isIntentMainFunction(intent: Intent): Boolean { return isAction(intent, LocusConst.INTENT_ITEM_MAIN_FUNCTION) } /** * Check if received intent is response on MAIN_FUNCTION_GC intent. * * @param intent received intent * @return `true` if intent is base on MAIN_FUNCTION_GC parameter */ fun isIntentMainFunctionGc(intent: Intent): Boolean { return isAction(intent, LocusConst.INTENT_ITEM_MAIN_FUNCTION_GC) } /** * Handle received intent from section MAIN_FUNCTION. * * @param intent received intent * @param handler handler for events * @throws NullPointerException exception if any required data are missing */ @Throws(NullPointerException::class) fun handleIntentMainFunction(ctx: Context, intent: Intent, handler: OnIntentReceived) { handleIntentGeneral(ctx, intent, LocusConst.INTENT_ITEM_MAIN_FUNCTION, handler) } /** * Handle received intent from section MAIN_FUNCTION_GC. * * @param intent received intent * @param handler handler for events * @throws NullPointerException exception if any required data are missing */ @Throws(NullPointerException::class) fun handleIntentMainFunctionGc(ctx: Context, intent: Intent, handler: OnIntentReceived) { handleIntentGeneral(ctx, intent, LocusConst.INTENT_ITEM_MAIN_FUNCTION_GC, handler) } //************************************************* // GET LOCATION INTENT //************************************************* // more info // https://github.com/asamm/locus-api/wiki/App-as-location-source /** * Check if received intent is "Get location" request. * * In case of positive result, it is necessary to return result with valid location object. * Received intent also contains user GPS and Map center location bundled. * * @param intent received intent. */ fun isIntentGetLocation(intent: Intent): Boolean { return isAction(intent, LocusConst.INTENT_ITEM_GET_LOCATION) } /** * Handle received intent from section SEARCH_LIST. * * @param intent received intent * @param handler handler for events * @throws NullPointerException exception if any required data are missing */ @Throws(NullPointerException::class) fun handleIntentGetLocation(ctx: Context, intent: Intent, handler: OnIntentReceived) { handleIntentGeneral(ctx, intent, LocusConst.INTENT_ITEM_GET_LOCATION, handler) } /** * Return generated location "get location" request. * * @param act current activity * @param name optional name of received location * @param loc location object */ fun sendGetLocationData(act: Activity, name: String? = null, loc: Location) { act.setResult(Activity.RESULT_OK, Intent().apply { if (name?.isNotBlank() == true) { putExtra(LocusConst.INTENT_EXTRA_NAME, name) } putExtra(LocusConst.INTENT_EXTRA_LOCATION, loc.asBytes) }) act.finish() } //************************************************* // POINT TOOLS //************************************************* // more info // https://github.com/asamm/locus-api/wiki/Own-function-in-Point-screen /** * Check if received intent is result of "Point tools" click. * * @param intent received intent */ fun isIntentPointTools(intent: Intent): Boolean { return isAction(intent, LocusConst.INTENT_ITEM_POINT_TOOLS) } //************************************************* // POINTS TOOLS //************************************************* // more info // https://github.com/asamm/locus-api/wiki/Own-function-in-Points-screen /** * Check if received intent is result of "Points tools" click. * * @param intent received intent */ fun isIntentPointsTools(intent: Intent): Boolean { return isAction(intent, LocusConst.INTENT_ITEM_POINTS_SCREEN_TOOLS) } //************************************************* // TRACK TOOLS //************************************************* // more info // https://github.com/asamm/locus-api/wiki/Own-function-in-Track-screen /** * Check if received intent is result of "Track tools" click. * * @param intent received intent */ fun isIntentTrackTools(intent: Intent): Boolean { return isAction(intent, LocusConst.INTENT_ITEM_TRACK_TOOLS) } //************************************************* // SEARCH SCREEN //************************************************* // more info // https://github.com/asamm/locus-api/wiki/App-as-Search-source /** * Check if received intent is response on SEARCH_LIST intent. * * @param intent received intent * @return `true` if intent is base on SEARCH_LIST parameter */ fun isIntentSearchList(intent: Intent): Boolean { return isAction(intent, LocusConst.INTENT_ITEM_SEARCH_LIST) } /** * Handle received intent from section SEARCH_LIST. * * @param intent received intent * @param handler handler for events * @throws NullPointerException exception if any required data are missing */ @Throws(NullPointerException::class) fun handleIntentSearchList(ctx: Context, intent: Intent, handler: OnIntentReceived) { handleIntentGeneral(ctx, intent, LocusConst.INTENT_ITEM_SEARCH_LIST, handler) } //************************************************* // PICK LOCATION //************************************************* /** * Check if received intent is result of "Get location" request. * * @param intent received intent * @return `true· if this is expected result */ fun isIntentReceiveLocation(intent: Intent): Boolean { return isAction(intent, LocusConst.ACTION_RECEIVE_LOCATION) } //************************************************* // GENERAL INTENT HANDLER //************************************************* @Throws(NullPointerException::class) private fun handleIntentGeneral(ctx: Context, intent: Intent, action: String, handler: OnIntentReceived) { // check intent itself if (!isAction(intent, action)) { handler.onFailed() return } // get version and handle received data LocusUtils.createLocusVersion(ctx, intent)?.let { handler.onReceived(it, getLocationFromIntent(intent, LocusConst.INTENT_EXTRA_LOCATION_GPS), getLocationFromIntent(intent, LocusConst.INTENT_EXTRA_LOCATION_MAP_CENTER)) } ?: { handler.onFailed() }() } /** * Receiver for basic intents. */ interface OnIntentReceived { /** * When intent really contain location, result is returned by this function * * @param lv version of Locus * @param locGps if gpsEnabled is true, variable contain location, otherwise `null` * @param locMapCenter contain current map center location */ fun onReceived(lv: LocusVersion, locGps: Location?, locMapCenter: Location?) fun onFailed() } //************************************************* // HANDY FUNCTIONS //************************************************* /** * Check if received intent contains required action. * * @param intent received intent * @param action action that we expect * @return `true` if intent is valid and contains required action */ fun isAction(intent: Intent, action: String): Boolean { return intent.action?.equals(action) == true } /** * Get ID of item send over intent container. * * @param intent received intent * @return ID of item or `-1` if no ID is defined */ fun getItemId(intent: Intent): Long { return intent.getLongExtra(LocusConst.INTENT_EXTRA_ITEM_ID, -1L) } /** * Get list of IDs registered in intent container. * * @param intent received intent * @return ID of items or `null` if no IDs are defined */ fun getItemsId(intent: Intent): LongArray? { if (intent.hasExtra(LocusConst.INTENT_EXTRA_ITEMS_ID)) { return intent.getLongArrayExtra(LocusConst.INTENT_EXTRA_ITEMS_ID) } return null } /** * Get location object from received intent. * * @param intent received intent * @param key name of 'extra' under which should be location stored in intent * @return location from intent or 'null' if intent has no location attached */ fun getLocationFromIntent(intent: Intent, key: String): Location? { // check if intent has required extra parameter if (!intent.hasExtra(key)) { return null } // convert data to valid Location object return Location().apply { read(intent.getByteArrayExtra(key)!!) } } /** * Attach point into intent, that may be send to Locus application. * * @param intent created intent container * @param pt point to attach */ fun addPointToIntent(intent: Intent, pt: Point) { intent.putExtra(LocusConst.INTENT_EXTRA_POINT, pt.asBytes) } /** * Load full point from received "Point intent" > intent that contains pointId or full point. * * @param ctx current context * @param intent received intent * @return loaded point object or `null` in case of any problem */ @Throws(RequiredVersionMissingException::class) fun getPointFromIntent(ctx: Context, intent: Intent): Point? { try { // try to load point based on it's ID val ptId = getItemId(intent) if (ptId >= 0) { LocusUtils.createLocusVersion(ctx, intent)?.let { return ActionBasics.getPoint(ctx, it, ptId) } } // try load full included point if (intent.hasExtra(LocusConst.INTENT_EXTRA_POINT)) { return Point().apply { read(intent.getByteArrayExtra(LocusConst.INTENT_EXTRA_POINT)!!) } } } catch (e: Exception) { Logger.logE(TAG, "getPointFromIntent($intent)", e) } return null } /** * Get ID of points defined in intent. * * @param intent received intent * @return list of points ID or null if no IDs are defined */ fun getPointsFromIntent(intent: Intent): LongArray? { return getItemsId(intent) } /** * Load full track from received "Track intent" > intent that contains trackId. * * @param ctx current context * @param intent received intent * @return loaded track object or `null` in case of any problem */ @Throws(RequiredVersionMissingException::class) fun getTrackFromIntent(ctx: Context, intent: Intent): Track? { val trackId = getItemId(intent) if (trackId >= 0) { LocusUtils.createLocusVersion(ctx, intent)?.let { return ActionBasics.getTrack(ctx, it, trackId) } } Logger.logD(TAG, "handleIntentTrackTools($ctx, $intent), " + "unable to obtain track $trackId") return null } }
mit
9609a5f1705d625bc964a162bb498ba7
32.638961
104
0.583861
4.75055
false
false
false
false
PaulWoitaschek/AndroidPlayer
app/src/main/java/de/paul_woitaschek/mediaplayer/AndroidPlayer.kt
1
2054
package de.paul_woitaschek.mediaplayer import android.content.Context import android.net.Uri import android.media.MediaPlayer as AndroidMediaPlayer /** * Delegates to [android.media.MediaPlayer]. Playback speed is not available as * [android.media.PlaybackParams] is not reliable. (Still crashes in N_MR1). * * @author Paul Woitaschek */ @Suppress("unused") class AndroidPlayer(private val context: Context) : MediaPlayer { private var onError: (() -> Unit)? = null private var onCompletion: (() -> Unit)? = null private var onPrepared: (() -> Unit)? = null private val player = AndroidMediaPlayer() init { player.setOnErrorListener { _, _, _ -> onError?.invoke() false } player.setOnCompletionListener { onCompletion?.invoke() } player.setOnPreparedListener { onPrepared?.invoke() } } override fun seekTo(to: Int) = player.seekTo(to) override fun isPlaying() = player.isPlaying override fun start() { player.start() } override fun pause() = player.pause() override fun setWakeMode(mode: Int) = player.setWakeMode(context, mode) override val duration: Int get() = player.duration override var playbackSpeed: Float = 1F get() = 1F override fun release() = player.release() override fun audioSessionId() = player.audioSessionId override fun onError(action: (() -> Unit)?) { onError = action } override fun onCompletion(action: (() -> Unit)?) { onCompletion = action } override fun onPrepared(action: (() -> Unit)?) { onPrepared = action } override fun setAudioStreamType(streamType: Int) = player.setAudioStreamType(streamType) override fun setVolume(volume: Float) { player.setVolume(volume, volume) } override fun prepare(uri: Uri) { player.setDataSource(context, uri) player.prepare() } override fun prepareAsync(uri: Uri) { player.setDataSource(context, uri) player.prepareAsync() } override fun reset() = player.reset() override val currentPosition: Int get() = player.currentPosition }
apache-2.0
743aa1965e299483fa4079f7cb50aabe
23.464286
90
0.689873
4.141129
false
false
false
false
hartwigmedical/hmftools
paddle/src/main/kotlin/com/hartwig/hmftools/paddle/cohort/CohortLoad.kt
1
674
package com.hartwig.hmftools.paddle.cohort import com.hartwig.hmftools.common.drivercatalog.dnds.DndsMutationalLoadFile data class CohortLoad(val cohortSize: Int, val indel: Int, val snv: Int) { companion object { fun fromFile(file: String): CohortLoad { val dndsSampleLoad = DndsMutationalLoadFile.read(file) var indelLoad = 0 var snvLoad = 0 for (dndsMutationalLoad in dndsSampleLoad) { indelLoad += dndsMutationalLoad.indelTotal() snvLoad += dndsMutationalLoad.snvTotal() } return CohortLoad(dndsSampleLoad.size, indelLoad, snvLoad) } } }
gpl-3.0
a8218db2edb342d8f5a2805d977c3a59
32.7
76
0.645401
3.528796
false
false
false
false
hartwigmedical/hmftools
cider/src/main/java/com/hartwig/hmftools/cider/ReadSlice.kt
1
2971
package com.hartwig.hmftools.cider import com.hartwig.hmftools.common.codon.Nucleotides import com.hartwig.hmftools.common.utils.IntPair import htsjdk.samtools.SAMRecord import htsjdk.samtools.util.SequenceUtil // slice view of a read, we want to use this to help // us manage times when we need to trim some poly G etc // we do reverse complement first before slice if // it is used class ReadSlice( private val read: SAMRecord, val reverseComplement: Boolean, val sliceStart: Int, val sliceEnd: Int) { init { require(sliceEnd > sliceStart, { "slice End <= sliceStart" }) } val readName: String get() { return read.readName } val firstOfPairFlag: Boolean get() { return read.firstOfPairFlag } // just the data we want from here val readLength: Int get() { return sliceEnd - sliceStart } val readString: String get() { var readStr = read.readString if (reverseComplement) readStr = SequenceUtil.reverseComplement(readStr) return readStr.substring(sliceStart, sliceEnd) } val baseQualities: ByteArray get() { var bq = read.baseQualities if (reverseComplement) bq = bq.reversedArray() return bq.sliceArray(sliceStart until sliceEnd) } val baseQualityString: String get() { var bq = read.baseQualityString if (reverseComplement) bq = bq.reversed() return bq.substring(sliceStart, sliceEnd) } fun baseAt(slicePos: Int): Char { val b = read.readString[slicePositionToReadPosition(slicePos)] return if (reverseComplement) Nucleotides.complement(b) else b } fun baseQualityAt(slicePos: Int): Byte { return read.baseQualities[slicePositionToReadPosition(slicePos)] } fun readPositionToSlicePosition(readPos: Int): Int { val pos = if (reverseComplement) read.readLength - readPos - 1 else readPos return pos - sliceStart } fun slicePositionToReadPosition(slicePos: Int): Int { val pos = slicePos + sliceStart return if (reverseComplement) read.readLength - pos - 1 else pos } fun readRangeToSliceRange(readRangeStart: Int, readRangeEndExclusive: Int): IntPair { val start = if (reverseComplement) read.readLength - readRangeEndExclusive else readRangeStart val end = if (reverseComplement) read.readLength - readRangeStart else readRangeEndExclusive return IntPair(start - sliceStart, end - sliceStart) } fun sliceRangeToReadRange(sliceRangeStart: Int, sliceRangeEndExclusive: Int): IntPair { var start = sliceRangeStart + sliceStart var end = sliceRangeEndExclusive + sliceStart if (reverseComplement) { start = read.readLength - end end = read.readLength - start } return IntPair(start, end) } }
gpl-3.0
7ffc7fa6147d2aeb92466acfe6e4739c
27.567308
102
0.659711
4.232194
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/providers/FilePickerProvider.kt
1
2344
/***************************************************************************** * FilePickerProvider.kt ***************************************************************************** * Copyright © 2018 VLC authors and VideoLAN * * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ package org.videolan.vlc.providers import android.content.Context import org.videolan.libvlc.interfaces.IMedia import org.videolan.libvlc.util.MediaBrowser import org.videolan.medialibrary.MLServiceLocator import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.tools.livedata.LiveDataset class FilePickerProvider(context: Context, dataset: LiveDataset<MediaLibraryItem>, url: String?, showDummyCategory: Boolean = false) : FileBrowserProvider(context, dataset, url, true, false, showDummyCategory) { override fun getFlags(interact : Boolean) = if (interact) MediaBrowser.Flag.NoSlavesAutodetect else MediaBrowser.Flag.Interact or MediaBrowser.Flag.NoSlavesAutodetect override fun initBrowser() { super.initBrowser() mediabrowser?.setIgnoreFileTypes("db,nfo,ini,jpg,jpeg,ljpg,gif,png,pgm,pgmyuv,pbm,pam,tga,bmp,pnm,xpm,xcf,pcx,tif,tiff,lbm,sfv") } override suspend fun findMedia(media: IMedia) = MLServiceLocator.getAbstractMediaWrapper(media)?.takeIf { mw -> mw.type == MediaWrapper.TYPE_DIR || mw.type == MediaWrapper.TYPE_SUBTITLE } override fun computeHeaders(value: List<MediaLibraryItem>) {} override fun parseSubDirectories(list : List<MediaLibraryItem>?) {} }
gpl-2.0
7e209f8220b7ffef96ebe97e40c69718
47.8125
211
0.693555
4.585127
false
false
false
false
KlubJagiellonski/poznaj-app-android
app/src/main/java/pl/poznajapp/view/PointDetailsActivity.kt
1
2889
package pl.poznajapp.view import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_point_details.* import kotlinx.android.synthetic.main.toolbar.* import pl.poznajapp.R import pl.poznajapp.view.base.BaseAppCompatActivity /** * Created by Rafał Gawlik on 08.09.17. */ class PointDetailsActivity : BaseAppCompatActivity() { private var latitude: Double = 0.toDouble() private var longitude: Double = 0.toDouble() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_point_details) if (this.intent.extras != null) { val image = intent.getStringExtra(EXTRAS_POINT_IMAGE) val title = intent.getStringExtra(EXTRAS_POINT_TITLE) val description = intent.getStringExtra(EXTRAS_POINT_DESCRIPTION) this.latitude = intent.getDoubleExtra(EXTRAS_POINT_LATITUDE, 0.0) this.longitude = intent.getDoubleExtra(EXTRAS_POINT_LONGITUDE, 0.0) setupView(image, title, description) } else { finish() } } private fun setupView(image: String, title: String, description: String) { point_details_text_tv.text = description Picasso.with(applicationContext) .load(image) .into(point_details_back_iv) mainToolbarBack.visibility = View.VISIBLE mainToolbarTitle.text = title mainToolbarBack.setOnClickListener { finish() } pointDetailsWalk.setOnClickListener { onShowGoogleMapsClick() } } fun onShowGoogleMapsClick() { val uri = "https://www.google.com/maps/search/?api=1&query=$latitude,$longitude" val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri)) startActivity(intent) } companion object { const val EXTRAS_POINT_IMAGE = "EXTRAS_POINT_IMAGE" const val EXTRAS_POINT_TITLE = "EXTRAS_POINT_TITLE" const val EXTRAS_POINT_DESCRIPTION = "EXTRAS_POINT_DESCRIPTION" const val EXTRAS_POINT_LATITUDE = "EXTRAS_POINT_LATITUDE" const val EXTRAS_POINT_LONGITUDE = "EXTRAS_POINT_LONGITUDE" fun getConfigureIntent(context: Context, image: String, title: String, latitude: Double?, longitude: Double?, details: String): Intent { val intent = Intent(context, PointDetailsActivity::class.java) intent.putExtra(EXTRAS_POINT_IMAGE, image) intent.putExtra(EXTRAS_POINT_TITLE, title) intent.putExtra(EXTRAS_POINT_LATITUDE, latitude) intent.putExtra(EXTRAS_POINT_LONGITUDE, longitude) intent.putExtra(EXTRAS_POINT_DESCRIPTION, details) return intent } } }
apache-2.0
4e29a70a859d34f73e62ef776d3ebf01
32.976471
144
0.675208
4.284866
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/compose/FlowHelpers.kt
1
1420
package org.tasks.compose import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.collectAsState import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.flowWithLifecycle import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext // https://proandroiddev.com/how-to-collect-flows-lifecycle-aware-in-jetpack-compose-babd53582d0b @Composable fun <T> rememberFlow( flow: Flow<T>, lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current ): Flow<T> { return remember(key1 = flow, key2 = lifecycleOwner) { flow.flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED) } } @Composable fun <T : R, R> Flow<T>.collectAsStateLifecycleAware( initial: R, context: CoroutineContext = EmptyCoroutineContext ): State<R> { val lifecycleAwareFlow = rememberFlow(flow = this) return lifecycleAwareFlow.collectAsState(initial = initial, context = context) } @Suppress("StateFlowValueCalledInComposition") @Composable fun <T> StateFlow<T>.collectAsStateLifecycleAware( context: CoroutineContext = EmptyCoroutineContext ): State<T> = collectAsStateLifecycleAware(value, context)
gpl-3.0
bc8e81a4be5e8fcbba8d7b1876fae33e
35.410256
133
0.812676
4.382716
false
false
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/session/ui/SessionsSheetFragment.kt
1
4728
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.session.ui import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewAnimationUtils import android.view.ViewGroup import android.view.animation.AccelerateInterpolator import org.mozilla.focus.R import org.mozilla.focus.activity.MainActivity import org.mozilla.focus.ext.requireComponents import org.mozilla.focus.locale.LocaleAwareFragment import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.OneShotOnPreDrawListener class SessionsSheetFragment : LocaleAwareFragment(), View.OnClickListener { private lateinit var backgroundView: View private lateinit var cardView: View private var isAnimating: Boolean = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_sessionssheet, container, false) backgroundView = view.findViewById(R.id.background) backgroundView.setOnClickListener(this) cardView = view.findViewById(R.id.card) OneShotOnPreDrawListener(cardView) { playAnimation(false) true } val sessionManager = requireComponents.sessionManager val sessionsAdapter = SessionsAdapter(this, sessionManager.sessions) sessionManager.register(sessionsAdapter, owner = this) view.findViewById<RecyclerView>(R.id.sessions).let { it.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) it.adapter = sessionsAdapter } return view } @Suppress("ComplexMethod") private fun playAnimation(reverse: Boolean): Animator { isAnimating = true val offset = resources.getDimensionPixelSize(R.dimen.floating_action_button_size) / 2 val cx = cardView.measuredWidth - offset val cy = cardView.measuredHeight - offset // The final radius is the diagonal of the card view -> sqrt(w^2 + h^2) val fullRadius = Math.sqrt( Math.pow(cardView.width.toDouble(), 2.0) + Math.pow(cardView.height.toDouble(), 2.0) ).toFloat() val sheetAnimator = ViewAnimationUtils.createCircularReveal( cardView, cx, cy, if (reverse) fullRadius else 0f, if (reverse) 0f else fullRadius ).apply { duration = ANIMATION_DURATION.toLong() interpolator = AccelerateInterpolator() addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { cardView.visibility = View.VISIBLE } override fun onAnimationEnd(animation: Animator) { isAnimating = false cardView.visibility = if (reverse) View.GONE else View.VISIBLE } }) start() } backgroundView.alpha = if (reverse) 1f else 0f backgroundView.animate() .alpha(if (reverse) 0f else 1f) .setDuration(ANIMATION_DURATION.toLong()) .start() return sheetAnimator } internal fun animateAndDismiss(): Animator { val animator = playAnimation(true) animator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { val activity = activity as MainActivity? activity?.supportFragmentManager?.beginTransaction()?.remove(this@SessionsSheetFragment)?.commit() } }) return animator } fun onBackPressed(): Boolean { animateAndDismiss() TelemetryWrapper.closeTabsTrayEvent() return true } override fun applyLocale() {} override fun onClick(view: View) { if (isAnimating) { // Ignore touched while we are animating return } when (view.id) { R.id.background -> { animateAndDismiss() TelemetryWrapper.closeTabsTrayEvent() } else -> throw IllegalStateException("Unhandled view in onClick()") } } companion object { const val FRAGMENT_TAG = "tab_sheet" private const val ANIMATION_DURATION = 200 } }
mpl-2.0
b2c92cf63efd72da125126523c0c344b
32.531915
116
0.660533
5.094828
false
false
false
false