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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ankidroid/Anki-Android
|
AnkiDroid/src/test/java/com/ichi2/testutils/ViewUtils.kt
|
1
|
2610
|
/*
* Copyright (c) 2022 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.testutils
import android.os.SystemClock
import android.view.MotionEvent
import android.view.View
import com.ichi2.anki.ui.DoubleTapListener
import org.robolectric.Shadows
/**
* Constant to be used - extracted from StackOverflow code
*/
private val uptime = SystemClock.uptimeMillis()
/** Simulates a double tap for a [DoubleTapListener] */
fun View.simulateDoubleTap() {
fun simulateEvent(action: Int, delta: Int = 0) = simulateEvent(this, action, delta)
simulateEvent(MotionEvent.ACTION_DOWN)
simulateEvent(MotionEvent.ACTION_UP)
// delta needs to be > 30 in Robolectric. GestureDetector: DOUBLE_TAP_MIN_TIME
simulateEvent(MotionEvent.ACTION_DOWN, 50)
simulateEvent(MotionEvent.ACTION_UP, 50)
}
/**
* Simulates an unconfirmed single tap for a [DoubleTapListener].
* Calling this twice will not result in a double-tap
*/
fun View.simulateUnconfirmedSingleTap() {
fun simulateEvent(action: Int) = simulateEvent(this, action)
simulateEvent(MotionEvent.ACTION_DOWN)
simulateEvent(MotionEvent.ACTION_UP)
}
/**
* https://stackoverflow.com/a/10124199
*/
private fun simulateEvent(target: View, action: Int, delta: Int = 0) {
val event = obtainMotionEvent(
downTime = uptime + delta,
eventTime = uptime + 100 + delta,
action = action,
x = 0.0f,
y = 0.0f,
metaState = 0
)
Shadows.shadowOf(target).onTouchListener.onTouch(target, event)
}
/**
* Kotlin wrapper for [MotionEvent.obtain] allowing named arguments
* @see MotionEvent.obtain
*/
@Suppress("SameParameterValue")
private fun obtainMotionEvent(
downTime: Long,
eventTime: Long,
action: Int,
x: Float,
y: Float,
metaState: Int
): MotionEvent {
return MotionEvent.obtain(
downTime,
eventTime,
action,
x,
y,
metaState
)!!
}
|
gpl-3.0
|
e10727892bf55b18c5e3e2289a825353
| 29 | 87 | 0.703448 | 3.978659 | false | false | false | false |
ankidroid/Anki-Android
|
AnkiDroid/src/main/java/com/ichi2/anki/CardTemplatePreviewer.kt
|
1
|
16730
|
/***************************************************************************************
* Copyright (c) 2020 Mike Hardy <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki
import android.os.Bundle
import android.view.View
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anki.UIUtils.showThemedToast
import com.ichi2.anki.cardviewer.PreviewLayout
import com.ichi2.anki.cardviewer.PreviewLayout.Companion.createAndDisplay
import com.ichi2.annotations.NeedsTest
import com.ichi2.libanki.*
import com.ichi2.libanki.Collection
import com.ichi2.libanki.TemplateManager.TemplateRenderContext.TemplateRenderOutput
import com.ichi2.libanki.utils.NoteUtils
import net.ankiweb.rsdroid.BackendFactory
import org.json.JSONObject
import timber.log.Timber
import java.io.IOException
import java.util.*
/**
* The card template previewer intent must supply one or more cards to show and the index in the list from where
* to begin showing them. Special rules are applied if the list size is 1 (i.e., no scrolling
* buttons will be shown).
*/
@NeedsTest("after switch to new schema as default, add test to confirm audio tags rendered")
open class CardTemplatePreviewer : AbstractFlashcardViewer() {
private var mEditedModelFileName: String? = null
private var mEditedModel: Model? = null
private var mOrdinal = 0
/** The index of the card in cardList to show */
private var mCardListIndex = 0
/** The list (currently singular) of cards to be previewed
* A single template was selected, and there was an associated card which exists
*/
private var mCardList: LongArray? = null
private var mNoteEditorBundle: Bundle? = null
private var mShowingAnswer = false
/**
* The number of valid templates for the note
* Only used if mNoteEditorBundle != null
*
* If launched from the Template Editor, only one the selected card template is selectable
*/
private var mTemplateCount = 0
var templateIndex = 0
private set
private var mAllFieldsNull = true
private var mCardType: String? = null
protected var previewLayout: PreviewLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
if (showedActivityFailedScreen(savedInstanceState)) {
return
}
Timber.d("onCreate()")
super.onCreate(savedInstanceState)
var parameters = savedInstanceState
if (parameters == null) {
parameters = intent.extras
}
if (parameters != null) {
mNoteEditorBundle = parameters.getBundle("noteEditorBundle")
mEditedModelFileName = parameters.getString(TemporaryModel.INTENT_MODEL_FILENAME)
mCardList = parameters.getLongArray("cardList")
mOrdinal = parameters.getInt("ordinal")
mCardListIndex = parameters.getInt("cardListIndex")
mShowingAnswer = parameters.getBoolean("showingAnswer", mShowingAnswer)
}
if (mEditedModelFileName != null) {
Timber.d("onCreate() loading edited model from %s", mEditedModelFileName)
try {
mEditedModel = TemporaryModel.getTempModel(mEditedModelFileName!!)
mCardType = mEditedModel!!.optString("name")
} catch (e: IOException) {
Timber.w(e, "Unable to load temp model from file %s", mEditedModelFileName)
closeCardTemplatePreviewer()
}
}
showBackIcon()
// Ensure navigation drawer can't be opened. Various actions in the drawer cause crashes.
disableDrawerSwipe()
startLoadingCollection()
}
override fun onResume() {
super.onResume()
if (currentCard == null || mOrdinal < 0) {
Timber.e("CardTemplatePreviewer started with empty card list or invalid index")
closeCardTemplatePreviewer()
}
}
private fun closeCardTemplatePreviewer() {
Timber.d("CardTemplatePreviewer:: closeCardTemplatePreviewer()")
setResult(RESULT_OK)
TemporaryModel.clearTempModelFiles()
finishWithAnimation(ActivityTransitionAnimation.Direction.END)
}
override fun onBackPressed() {
Timber.i("CardTemplatePreviewer:: onBackPressed()")
closeCardTemplatePreviewer()
}
override fun performReload() {
// This should not happen.
finishWithAnimation(ActivityTransitionAnimation.Direction.END)
}
override fun onNavigationPressed() {
Timber.i("CardTemplatePreviewer:: Navigation button pressed")
closeCardTemplatePreviewer()
}
override fun setTitle() {
if (supportActionBar != null) {
supportActionBar?.setTitle(R.string.preview_title)
}
}
override fun initLayout() {
super.initLayout()
topBarLayout!!.visibility = View.GONE
findViewById<View>(R.id.answer_options_layout).visibility = View.GONE
previewLayout = createAndDisplay(this, mToggleAnswerHandler)
previewLayout!!.setOnPreviousCard { onPreviousTemplate() }
previewLayout!!.setOnNextCard { onNextTemplate() }
previewLayout!!.hideNavigationButtons()
previewLayout!!.setPrevButtonEnabled(false)
}
override fun displayCardQuestion() {
super.displayCardQuestion()
mShowingAnswer = false
previewLayout!!.setShowingAnswer(false)
}
override fun displayCardAnswer() {
if (mAllFieldsNull && mCardType != null && mCardType == getString(R.string.basic_typing_model_name)) {
answerField!!.setText(getString(R.string.basic_answer_sample_text_user))
}
super.displayCardAnswer()
mShowingAnswer = true
previewLayout!!.setShowingAnswer(true)
}
override fun hideEaseButtons() {
/* do nothing */
}
override fun displayAnswerBottomBar() {
/* do nothing */
}
private val mToggleAnswerHandler = View.OnClickListener {
if (mShowingAnswer) {
displayCardQuestion()
} else {
displayCardAnswer()
}
}
/** When the next template is requested */
fun onNextTemplate() {
var index = templateIndex
if (!isNextBtnEnabled(index)) {
return
}
templateIndex = ++index
onTemplateIndexChanged()
}
/** When the previous template is requested */
fun onPreviousTemplate() {
var index = templateIndex
if (!isPrevBtnEnabled(index)) {
return
}
templateIndex = --index
onTemplateIndexChanged()
}
/**
* Loads the next card after the current template index has been changed
*/
private fun onTemplateIndexChanged() {
val prevBtnEnabled = isPrevBtnEnabled(templateIndex)
val nextBtnEnabled = isNextBtnEnabled(templateIndex)
previewLayout!!.setPrevButtonEnabled(prevBtnEnabled)
previewLayout!!.setNextButtonEnabled(nextBtnEnabled)
setCurrentCardFromNoteEditorBundle(col)
displayCardQuestion()
}
private fun isPrevBtnEnabled(templateIndex: Int): Boolean {
return templateIndex > 0
}
private fun isNextBtnEnabled(newTemplateIndex: Int): Boolean {
return newTemplateIndex < mTemplateCount - 1
}
public override fun onSaveInstanceState(outState: Bundle) {
outState.putString(TemporaryModel.INTENT_MODEL_FILENAME, mEditedModelFileName)
outState.putLongArray("cardList", mCardList)
outState.putInt("ordinal", mOrdinal)
outState.putInt("cardListIndex", mCardListIndex)
outState.putBundle("noteEditorBundle", mNoteEditorBundle)
outState.putBoolean("showingAnswer", mShowingAnswer)
super.onSaveInstanceState(outState)
}
override fun onCollectionLoaded(col: Collection) {
super.onCollectionLoaded(col)
if (mNoteEditorBundle != null) {
mAllFieldsNull = false
// loading from the note editor
val toPreview = setCurrentCardFromNoteEditorBundle(col)
if (toPreview != null) {
mTemplateCount = col.findTemplates(toPreview.note()).size
if (mTemplateCount >= 2) {
previewLayout!!.showNavigationButtons()
}
}
} else {
// loading from the card template editor
mAllFieldsNull = true
// card template with associated card due to opening from note editor
if (mCardList != null && mCardListIndex >= 0 && mCardListIndex < mCardList!!.size) {
currentCard = PreviewerCard(col, mCardList!![mCardListIndex])
} else if (mEditedModel != null) { // bare note type (not coming from note editor), or new card template
Timber.d("onCreate() CardTemplatePreviewer started with edited model and template index, displaying blank to preview formatting")
currentCard = getDummyCard(mEditedModel!!, mOrdinal)
if (currentCard == null) {
showThemedToast(applicationContext, getString(R.string.invalid_template), false)
closeCardTemplatePreviewer()
}
}
}
if (currentCard == null) {
showThemedToast(applicationContext, getString(R.string.invalid_template), false)
closeCardTemplatePreviewer()
return
}
displayCardQuestion()
if (mShowingAnswer) {
displayCardAnswer()
}
showBackIcon()
}
protected fun getCard(col: Collection, cardListIndex: Long): Card {
return PreviewerCard(col, cardListIndex)
}
private fun setCurrentCardFromNoteEditorBundle(col: Collection): Card? {
assert(mNoteEditorBundle != null)
currentCard = getDummyCard(mEditedModel, templateIndex, getBundleEditFields(mNoteEditorBundle))
// example: a basic card with no fields provided
if (currentCard == null) {
return null
}
val newDid = mNoteEditorBundle!!.getLong("did")
if (col.decks.isDyn(newDid)) {
currentCard!!.oDid = currentCard!!.did
}
currentCard!!.did = newDid
val currentNote = currentCard!!.note()
val tagsList = mNoteEditorBundle!!.getStringArrayList("tags")
NoteUtils.setTags(currentNote, tagsList)
return currentCard
}
private fun getLabels(fieldValues: MutableList<String>) {
if (mCardType != null && mCardType == getString(R.string.cloze_model_name)) {
fieldValues[0] = getString(R.string.cloze_sample_text, "c1")
}
if (mCardType != null && mCardType == getString(R.string.basic_typing_model_name)) {
fieldValues[1] = getString(R.string.basic_answer_sample_text)
}
}
private fun getBundleEditFields(noteEditorBundle: Bundle?): MutableList<String> {
val noteFields = noteEditorBundle!!.getBundle("editFields")
?: return ArrayList()
// we map from "int" -> field, but the order isn't guaranteed, and there may be skips.
// so convert this to a list of strings, with null in place of the invalid fields
val elementCount = noteFields.keySet().stream().map { s: String -> s.toInt() }.max { obj: Int, anotherInteger: Int? -> obj.compareTo(anotherInteger!!) }.orElse(-1) + 1
val ret = arrayOfNulls<String>(elementCount)
Arrays.fill(ret, "") // init array, nulls cause a crash
for (fieldOrd in noteFields.keySet()) {
ret[fieldOrd.toInt()] = noteFields.getString(fieldOrd)
}
return ArrayList(listOf(*ret))
}
/**
* This method generates a note from a sample model, or fails if invalid
* @param index The index in the templates for the model. NOT `ord`
*/
fun getDummyCard(model: Model, index: Int): Card? {
return getDummyCard(model, index, model.fieldsNames.toMutableList())
}
/**
* This method generates a note from a sample model, or fails if invalid
* @param index The index in the templates for the model. NOT `ord`
*/
private fun getDummyCard(model: Model?, index: Int, fieldValues: MutableList<String>): Card? {
Timber.d("getDummyCard() Creating dummy note for index %s", index)
if (model == null) {
return null
}
if (mAllFieldsNull) {
getLabels(fieldValues)
}
val n = col.newNote(model)
var i = 0
while (i < fieldValues.size && i < n.fields.size) {
if (mAllFieldsNull) {
if (mCardType != null && mCardType == getString(R.string.cloze_model_name) && i == 0 ||
mCardType == getString(R.string.basic_typing_model_name) && i == 1
) {
n.setField(i, fieldValues[i])
} else {
n.setField(i, "(" + fieldValues[i] + ")")
}
} else {
n.setField(i, fieldValues[i])
}
i++
}
try {
// TODO: Inefficient, we discard all but one of the elements.
val template = col.findTemplates(n)[index]
return col.getNewLinkedCard(PreviewerCard(col, n), n, template, 1, 0L, false)
} catch (e: Exception) {
Timber.e(e, "getDummyCard() unable to create card")
}
return null
}
/** Override certain aspects of Card behavior so we may display unsaved data */
inner class PreviewerCard : Card {
private val mNote: Note?
constructor(col: Collection, note: Note) : super(col) {
mNote = note
}
constructor(col: Collection, id: Long) : super(col, id) {
mNote = null
}
/* if we have an unsaved note saved, use it instead of a collection lookup */ override fun note(
reload: Boolean
): Note {
return mNote ?: super.note(reload)
}
/** if we have an unsaved note saved, use it instead of a collection lookup */
override fun note(): Note {
return mNote ?: super.note()
}
/** if we have an unsaved note, never return empty */
override val isEmpty: Boolean
get() = if (mNote != null) {
false
} else super.isEmpty
/** Override the method that fetches the model so we can render unsaved models */
override fun model(): Model {
return mEditedModel ?: super.model()
}
override fun render_output(reload: Boolean, browser: Boolean): TemplateRenderOutput {
if (render_output == null || reload) {
render_output = if (BackendFactory.defaultLegacySchema) {
col.render_output_legacy(this, reload, browser)
} else {
val index = if (model().isCloze) {
0
} else {
ord
}
val context = TemplateManager.TemplateRenderContext.from_card_layout(
note(),
this,
model(),
model().getJSONArray("tmpls")[index] as JSONObject,
fill_empty = false
)
context.render()
}
}
return render_output!!
}
}
}
|
gpl-3.0
|
8d9c06782471ae44521fd11603ab06a2
| 39.023923 | 175 | 0.597609 | 4.896108 | false | false | false | false |
ankidroid/Anki-Android
|
AnkiDroid/src/test/java/com/ichi2/anki/TestCardTemplatePreviewer.kt
|
1
|
1719
|
/*
* Copyright (c) 2021 Mike Hardy <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki
import android.view.View
class TestCardTemplatePreviewer : CardTemplatePreviewer() {
var showingAnswer = false
private set
fun disableDoubleClickPrevention() {
lastClickTime = (AnkiDroidApp.getSharedPrefs(baseContext).getInt(DOUBLE_TAP_TIME_INTERVAL, DEFAULT_DOUBLE_TAP_TIME_INTERVAL) * -2).toLong()
}
override fun displayCardAnswer() {
super.displayCardAnswer()
showingAnswer = true
}
override fun displayCardQuestion() {
super.displayCardQuestion()
showingAnswer = false
}
fun nextButtonVisible(): Boolean {
return previewLayout!!.nextCard.visibility != View.GONE
}
fun previousButtonVisible(): Boolean {
return previewLayout!!.prevCard.visibility != View.GONE
}
fun previousButtonEnabled(): Boolean {
return previewLayout!!.prevCard.isEnabled
}
fun nextButtonEnabled(): Boolean {
return previewLayout!!.nextCard.isEnabled
}
}
|
gpl-3.0
|
1550f194ade054b17f32b593a5b04394
| 31.433962 | 147 | 0.703316 | 4.396419 | false | false | false | false |
NooAn/bytheway
|
app/src/main/java/ru/a1024bits/bytheway/util/MapExtensions.kt
|
1
|
1481
|
package ru.a1024bits.bytheway.util
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.firebase.firestore.GeoPoint
import ru.a1024bits.bytheway.R
/**
* Created by tikhon.osipov on 25.11.17
*/
fun LatLng.createMarker(title: String): MarkerOptions =
MarkerOptions()
.position(this)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_blue))
.title(title)
fun LatLng.toJsonString(): String = "${this.latitude},${this.longitude}"
fun LatLng?.toGeoPoint(): GeoPoint = GeoPoint(this?.latitude ?: 0.0, this?.longitude ?: 0.0)
fun LatLng.getBearing(end: LatLng): Float {
val lat = Math.abs(this.latitude - end.latitude)
val lng = Math.abs(this.longitude - end.longitude)
if (this.latitude < end.latitude && this.longitude < end.longitude)
return Math.toDegrees(Math.atan(lng / lat)).toFloat()
else if (this.latitude >= end.latitude && this.longitude < end.longitude)
return (90 - Math.toDegrees(Math.atan(lng / lat)) + 90).toFloat()
else if (this.latitude >= end.latitude && this.longitude >= end.longitude)
return (Math.toDegrees(Math.atan(lng / lat)) + 180).toFloat()
else if (this.latitude < end.latitude && this.longitude >= end.longitude)
return (90 - Math.toDegrees(Math.atan(lng / lat)) + 270).toFloat()
return -1f
}
|
mit
|
c9e9651b1e98b7758a48d7a1123c9692
| 40.138889 | 92 | 0.688049 | 3.68408 | false | false | false | false |
JetBrains/anko
|
anko/library/generated/gridlayout-v7/src/main/java/Views.kt
|
4
|
2507
|
@file:JvmName("GridlayoutV7ViewsKt")
package org.jetbrains.anko.gridlayout.v7
import org.jetbrains.anko.custom.*
import org.jetbrains.anko.AnkoViewDslMarker
import android.view.ViewManager
import android.view.ViewGroup.LayoutParams
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.os.Build
import android.widget.*
@PublishedApi
internal object `$$Anko$Factories$GridlayoutV7ViewGroup` {
val GRID_LAYOUT = { ctx: Context -> _GridLayout(ctx) }
}
inline fun ViewManager.gridLayout(): android.support.v7.widget.GridLayout = gridLayout() {}
inline fun ViewManager.gridLayout(init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.support.v7.widget.GridLayout {
return ankoView(`$$Anko$Factories$GridlayoutV7ViewGroup`.GRID_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedGridLayout(theme: Int = 0): android.support.v7.widget.GridLayout = themedGridLayout(theme) {}
inline fun ViewManager.themedGridLayout(theme: Int = 0, init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.support.v7.widget.GridLayout {
return ankoView(`$$Anko$Factories$GridlayoutV7ViewGroup`.GRID_LAYOUT, theme) { init() }
}
inline fun Context.gridLayout(): android.support.v7.widget.GridLayout = gridLayout() {}
inline fun Context.gridLayout(init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.support.v7.widget.GridLayout {
return ankoView(`$$Anko$Factories$GridlayoutV7ViewGroup`.GRID_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedGridLayout(theme: Int = 0): android.support.v7.widget.GridLayout = themedGridLayout(theme) {}
inline fun Context.themedGridLayout(theme: Int = 0, init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.support.v7.widget.GridLayout {
return ankoView(`$$Anko$Factories$GridlayoutV7ViewGroup`.GRID_LAYOUT, theme) { init() }
}
inline fun Activity.gridLayout(): android.support.v7.widget.GridLayout = gridLayout() {}
inline fun Activity.gridLayout(init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.support.v7.widget.GridLayout {
return ankoView(`$$Anko$Factories$GridlayoutV7ViewGroup`.GRID_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedGridLayout(theme: Int = 0): android.support.v7.widget.GridLayout = themedGridLayout(theme) {}
inline fun Activity.themedGridLayout(theme: Int = 0, init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.support.v7.widget.GridLayout {
return ankoView(`$$Anko$Factories$GridlayoutV7ViewGroup`.GRID_LAYOUT, theme) { init() }
}
|
apache-2.0
|
25c93c57fd9186e794697e90b2de4f88
| 51.229167 | 146 | 0.766653 | 3.929467 | false | false | false | false |
WijayaPrinting/wp-javafx
|
openpss/src/com/hendraanggrian/openpss/schema/Invoice.kt
|
1
|
5750
|
package com.hendraanggrian.openpss.schema
import com.hendraanggrian.openpss.nosql.Document
import com.hendraanggrian.openpss.nosql.Schema
import com.hendraanggrian.openpss.nosql.Schemed
import com.hendraanggrian.openpss.nosql.StringId
import kotlinx.nosql.ListColumn
import kotlinx.nosql.boolean
import kotlinx.nosql.dateTime
import kotlinx.nosql.id
import kotlinx.nosql.integer
import kotlinx.nosql.string
import org.joda.time.DateTime
object Invoices : Schema<Invoice>("invoices", Invoice::class) {
val no = integer("no")
val employeeId = id("employee_id", Employees)
val customerId = id("customer_id", Customers)
val dateTime = dateTime("date_time")
val digitalJobs = DigitalJobs()
val offsetJobs = OffsetJobs()
val plateJobs = PlateJobs()
val otherJobs = OtherJobs()
val note = string("note")
val isPrinted = boolean("is_printed")
val isPaid = boolean("is_paid")
val isDone = boolean("is_done")
class DigitalJobs :
ListColumn<Invoice.DigitalJob, Invoices>(Invoices.DigitalJobs.schemaName, Invoice.DigitalJob::class) {
val qty = integer("qty")
val desc = string("desc")
val total = string("total")
val type = string("type")
val isTwoSide = boolean("two_side")
companion object : Schemed {
override val schemaName: String = "digital_jobs"
}
}
class OffsetJobs :
ListColumn<Invoice.OffsetJob, Invoices>(Invoices.OffsetJobs.schemaName, Invoice.OffsetJob::class) {
val qty = integer("qty")
val desc = string("desc")
val total = string("total")
val type = string("type")
val technique = string("technique")
companion object : Schemed {
override val schemaName: String = "offset_jobs"
}
}
class PlateJobs : ListColumn<Invoice.PlateJob, Invoices>(Invoices.PlateJobs.schemaName, Invoice.PlateJob::class) {
val qty = integer("qty")
val desc = string("desc")
val total = string("total")
val type = string("type")
companion object : Schemed {
override val schemaName: String = "plate_jobs"
}
}
class OtherJobs : ListColumn<Invoice.OtherJob, Invoices>(Invoices.OtherJobs.schemaName, Invoice.OtherJob::class) {
val qty = integer("qty")
val desc = string("desc")
val total = string("total")
companion object : Schemed {
override val schemaName: String = "other_jobs"
}
}
}
data class Invoice(
/**
* Since `id` is reserved in [Document], `no` is direct replacement.
* Basically means the same thing.
*/
val no: Int,
val employeeId: StringId<Employees>,
val customerId: StringId<Customers>,
val dateTime: DateTime,
var digitalJobs: List<DigitalJob>,
var offsetJobs: List<OffsetJob>,
var plateJobs: List<PlateJob>,
var otherJobs: List<OtherJob>,
var note: String,
var isPrinted: Boolean,
var isPaid: Boolean,
var isDone: Boolean
) : Document<Invoices> {
companion object {
fun new(
no: Int,
employeeId: StringId<Employees>,
customerId: StringId<Customers>,
dateTime: DateTime,
digitalJobs: List<DigitalJob>,
offsetJobs: List<OffsetJob>,
plateJobs: List<PlateJob>,
otherJobs: List<OtherJob>,
note: String
): Invoice = Invoice(
no, employeeId, customerId, dateTime, digitalJobs, offsetJobs, plateJobs, otherJobs,
note, false, false, false
)
}
override lateinit var id: StringId<Invoices>
val jobs: List<Job>
get() {
val list = mutableListOf<Job>()
digitalJobs.forEach { list += it }
offsetJobs.forEach { list += it }
plateJobs.forEach { list += it }
otherJobs.forEach { list += it }
return list
}
inline val total: Double get() = jobs.sumByDouble { it.total }
data class DigitalJob(
override val qty: Int,
override val desc: String,
override val total: Double,
override val type: String,
val isTwoSide: Boolean
) : JobWithType {
companion object {
fun new(
qty: Int,
title: String,
total: Double,
type: String,
isTwoSide: Boolean
): DigitalJob = DigitalJob(qty, title, total, type, isTwoSide)
}
}
data class OffsetJob(
override val qty: Int,
override val desc: String,
override val total: Double,
override val type: String,
val technique: String
) : JobWithType {
companion object
}
data class PlateJob(
override val qty: Int,
override val desc: String,
override val total: Double,
override val type: String
) : JobWithType {
companion object {
fun new(
qty: Int,
title: String,
total: Double,
type: String
): PlateJob = PlateJob(qty, title, total, type)
}
}
data class OtherJob(
override val qty: Int,
override val desc: String,
override val total: Double
) : Job {
companion object {
fun new(
qty: Int,
title: String,
total: Double
): Invoice.OtherJob = Invoice.OtherJob(qty, title, total)
}
}
interface JobWithType : Job {
val type: String
}
interface Job {
val qty: Int
val desc: String
val total: Double
}
}
|
apache-2.0
|
c3b6cd73037e62acd3fb3e73203a6548
| 27.894472 | 118 | 0.587826 | 4.369301 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/ui/NewPlayAddPlayersFragment.kt
|
1
|
6223
|
package com.boardgamegeek.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentNewPlayAddPlayersBinding
import com.boardgamegeek.databinding.RowNewPlayAddPlayerBinding
import com.boardgamegeek.entities.PlayerEntity
import com.boardgamegeek.extensions.*
import com.boardgamegeek.ui.adapter.AutoUpdatableAdapter
import com.boardgamegeek.ui.viewmodel.NewPlayViewModel
import com.google.android.material.chip.Chip
import kotlin.properties.Delegates
class NewPlayAddPlayersFragment : Fragment() {
private var _binding: FragmentNewPlayAddPlayersBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<NewPlayViewModel>()
private val adapter: PlayersAdapter by lazy { PlayersAdapter(viewModel, binding.filterEditText) }
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentNewPlayAddPlayersBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val columnWidth = 240
val width = requireActivity().calculateScreenWidth()
binding.recyclerView.layoutManager = GridLayoutManager(context, width / columnWidth)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.adapter = adapter
binding.filterEditText.doAfterTextChanged { s ->
if (s.isNullOrBlank()) {
binding.nextOrAddButton.setImageResource(R.drawable.ic_baseline_check_circle_24)
} else {
binding.nextOrAddButton.setImageResource(R.drawable.ic_baseline_add_circle_outline_24)
}
viewModel.filterPlayers(s.toString())
}
binding.nextOrAddButton.setOnClickListener {
if (binding.filterEditText.text?.isNotBlank() == true) {
viewModel.addPlayer(PlayerEntity(binding.filterEditText.text.toString(), ""))
binding.filterEditText.setText("")
} else {
viewModel.finishAddingPlayers()
}
}
viewModel.availablePlayers.observe(viewLifecycleOwner) {
adapter.players = it
binding.recyclerView.fadeIn()
if (it.isEmpty()) {
binding.emptyView.setText(
if (binding.filterEditText.text.isNullOrBlank()) {
R.string.empty_new_play_players
} else {
R.string.empty_new_play_players_filter
}
)
binding.emptyView.fadeIn()
} else {
binding.emptyView.fadeOut()
}
}
viewModel.addedPlayers.observe(viewLifecycleOwner) {
// TODO don't delete and recreate
binding.chipGroup.removeAllViews()
it?.let { list ->
for (player in list) {
binding.chipGroup.addView(Chip(context).apply {
text = player.description
isCloseIconVisible = true
if (player.avatarUrl.isBlank()) {
setChipIconResource(R.drawable.ic_baseline_account_circle_24)
// TODO use non-user's favorite color if available
setChipIconTintResource(R.color.dark_blue)
} else {
loadIcon(player.avatarUrl, R.drawable.ic_baseline_account_circle_24)
}
isClickable = false
setOnCloseIconClickListener {
viewModel.removePlayer(player)
}
})
}
}
}
viewModel.filterPlayers("")
}
override fun onResume() {
super.onResume()
(activity as? AppCompatActivity)?.supportActionBar?.setSubtitle(R.string.title_players)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private class PlayersAdapter(private val viewModel: NewPlayViewModel, private val filterView: TextView) :
RecyclerView.Adapter<PlayersAdapter.PlayersViewHolder>(), AutoUpdatableAdapter {
var players: List<PlayerEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue ->
autoNotify(oldValue, newValue) { old, new ->
old.name == new.name && old.username == new.username && old.avatarUrl == new.avatarUrl
}
}
override fun getItemCount() = players.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlayersViewHolder {
return PlayersViewHolder(parent.inflate(R.layout.row_new_play_add_player))
}
override fun onBindViewHolder(holder: PlayersViewHolder, position: Int) {
holder.bind(players.getOrNull(position))
}
inner class PlayersViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = RowNewPlayAddPlayerBinding.bind(itemView)
fun bind(player: PlayerEntity?) {
player?.let { p ->
binding.nameView.text = p.name
binding.usernameView.text = p.username
binding.avatarView.loadThumbnail(p.avatarUrl, R.drawable.person_image_empty)
itemView.setOnClickListener {
viewModel.addPlayer(p)
filterView.text = ""
}
}
}
}
}
}
|
gpl-3.0
|
b9c561c7d755dbbae8422239ed094a9a
| 40.765101 | 116 | 0.620922 | 5.291667 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/TeamEncoder.kt
|
1
|
2717
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.play
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import org.lanternpowered.api.text.format.NamedTextColor
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.PacketEncoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.text.LegacyNetworkText
import org.lanternpowered.server.network.text.NetworkText
import org.lanternpowered.server.network.vanilla.packet.type.play.TeamPacket
import org.lanternpowered.server.registry.type.scoreboard.CollisionRuleRegistry
import org.lanternpowered.server.registry.type.scoreboard.VisibilityRegistry
object TeamEncoder : PacketEncoder<TeamPacket> {
private val colorIndex = NamedTextColor.NAMES.values()
.withIndex().associateTo(Object2IntOpenHashMap()) { (index, value) -> value to index }
override fun encode(ctx: CodecContext, packet: TeamPacket): ByteBuffer {
val buf = ctx.byteBufAlloc().buffer()
buf.writeString(packet.teamName)
val type = when (packet) {
is TeamPacket.Create -> 0
is TeamPacket.Remove -> 1
is TeamPacket.Update -> 2
is TeamPacket.AddMembers -> 3
is TeamPacket.RemoveMembers -> 4
else -> error("Unknown type: ${packet.javaClass.name}")
}
buf.writeByte(type.toByte())
if (packet is TeamPacket.CreateOrUpdate) {
NetworkText.write(ctx, buf, packet.displayName)
var flags = 0
if (packet.friendlyFire)
flags += 0x1
if (packet.seeFriendlyInvisibles)
flags += 0x2
buf.writeByte(flags.toByte())
buf.writeString(VisibilityRegistry.requireId(packet.nameTagVisibility))
buf.writeString(CollisionRuleRegistry.requireId(packet.collisionRule))
buf.writeByte(if (packet.color == null) 21 else this.colorIndex.getInt(packet.color).toByte())
NetworkText.write(ctx, buf, packet.prefix)
NetworkText.write(ctx, buf, packet.suffix)
}
if (packet is TeamPacket.Members) {
buf.writeVarInt(packet.members.size)
for (member in packet.members)
LegacyNetworkText.write(ctx, buf, member)
}
return buf
}
}
|
mit
|
71d6d388d56ed264f7472b337a36a2fb
| 42.822581 | 106 | 0.688627 | 4.368167 | false | false | false | false |
ekager/focus-android
|
app/src/main/java/org/mozilla/focus/biometrics/BiometricAuthenticationHandler.kt
|
1
|
5170
|
/* 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.biometrics
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.OnLifecycleEvent
import android.arch.lifecycle.ProcessLifecycleOwner
import android.content.Context
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyPermanentlyInvalidatedException
import android.security.keystore.KeyProperties
import android.support.annotation.RequiresApi
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat
import android.support.v4.os.CancellationSignal
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
@RequiresApi(Build.VERSION_CODES.M)
class BiometricAuthenticationHandler(private val context: Context) :
FingerprintManagerCompat.AuthenticationCallback(), LifecycleObserver {
private val fingerprintManager = FingerprintManagerCompat.from(context)
private var cancellationSignal: CancellationSignal? = null
private var selfCancelled = false
private var keyStore: KeyStore? = null
private var keyGenerator: KeyGenerator? = null
private var cryptoObject: FingerprintManagerCompat.CryptoObject? = null
var needsAuth = false; private set
var biometricFragment: BiometricAuthenticationDialogFragment? = null; private set
init {
keyStore = KeyStore.getInstance("AndroidKeyStore")
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
createKey(DEFAULT_KEY_NAME, false)
val defaultCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" +
KeyProperties.BLOCK_MODE_CBC + "/" +
KeyProperties.ENCRYPTION_PADDING_PKCS7)
if (initCipher(defaultCipher, DEFAULT_KEY_NAME)) {
cryptoObject = FingerprintManagerCompat.CryptoObject(defaultCipher)
}
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
private fun initCipher(cipher: Cipher, keyName: String): Boolean {
return try {
keyStore?.load(null)
val key = keyStore?.getKey(keyName, null) as SecretKey
cipher.init(Cipher.ENCRYPT_MODE, key)
true
} catch (err: KeyPermanentlyInvalidatedException) {
false
}
}
private fun createKey(keyName: String, invalidatedByBiometricEnrollment: Boolean?) {
keyStore?.load(null)
val builder = KeyGenParameterSpec.Builder(keyName,
KeyProperties.PURPOSE_ENCRYPT).setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment!!)
}
keyGenerator?.init(builder.build())
keyGenerator?.generateKey()
}
// Create the prompt and begin listening
private fun startListening(cryptoObject: FingerprintManagerCompat.CryptoObject, openedFromExternalLink: Boolean) {
if (biometricFragment == null) {
biometricFragment = BiometricAuthenticationDialogFragment()
}
biometricFragment?.openedFromExternalLink = openedFromExternalLink
biometricFragment?.updateNewSessionButton()
cancellationSignal = CancellationSignal()
selfCancelled = false
fingerprintManager.authenticate(cryptoObject, 0, cancellationSignal, this, null)
}
fun stopListening() {
cancellationSignal?.let {
biometricFragment?.dismiss()
selfCancelled = true
it.cancel()
cancellationSignal = null
}
}
fun startAuthentication(openedFromLink: Boolean) {
val cryptoObject = cryptoObject
if (openedFromLink) needsAuth = true
if (needsAuth && cryptoObject != null) {
startListening(cryptoObject, openedFromLink)
}
}
override fun onAuthenticationError(errMsgId: Int, errString: CharSequence?) {
if (!selfCancelled) {
biometricFragment?.displayError(errString.toString())
}
}
override fun onAuthenticationSucceeded(result: FingerprintManagerCompat.AuthenticationResult?) {
needsAuth = false
biometricFragment?.onAuthenticated()
}
override fun onAuthenticationHelp(helpMsgId: Int, helpString: CharSequence?) {
biometricFragment?.displayError(helpString.toString())
}
override fun onAuthenticationFailed() {
biometricFragment?.onFailure()
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
needsAuth = true && Biometrics.hasFingerprintHardware(context)
stopListening()
}
companion object {
private const val DEFAULT_KEY_NAME = "default_key"
}
}
|
mpl-2.0
|
b4308e5356cd25bdc6dc49817e1735a9
| 35.666667 | 118 | 0.712766 | 5.043902 | false | false | false | false |
Mauin/detekt
|
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/invoke/CliArgument.kt
|
1
|
2858
|
package io.gitlab.arturbosch.detekt.invoke
import org.gradle.api.file.FileCollection
import java.io.File
private const val DEBUG_PARAMETER = "--debug"
private const val FILTERS_PARAMETER = "--filters"
private const val INPUT_PARAMETER = "--input"
private const val CONFIG_PARAMETER = "--config"
private const val BASELINE_PARAMETER = "--baseline"
private const val PARALLEL_PARAMETER = "--parallel"
private const val DISABLE_DEFAULT_RULESETS_PARAMETER = "--disable-default-rulesets"
private const val PLUGINS_PARAMETER = "--plugins"
private const val REPORT_PARAMETER = "--report"
private const val GENERATE_CONFIG_PARAMETER = "--generate-config"
private const val CREATE_BASELINE_PARAMETER = "--create-baseline"
internal sealed class CliArgument {
abstract fun toArgument(): List<String>
}
internal object CreateBaselineArgument : CliArgument() {
override fun toArgument() = listOf(CREATE_BASELINE_PARAMETER)
}
internal object GenerateConfigArgument : CliArgument() {
override fun toArgument() = listOf(GENERATE_CONFIG_PARAMETER)
}
internal data class InputArgument(val fileCollection: FileCollection) : CliArgument() {
override fun toArgument() = listOf(INPUT_PARAMETER, fileCollection.asPath)
}
internal data class FiltersArgument(val filters: String?) : CliArgument() {
override fun toArgument() = filters?.let { listOf(FILTERS_PARAMETER, it) } ?: emptyList()
}
internal data class PluginsArgument(val plugins: String?) : CliArgument() {
override fun toArgument() = plugins?.let { listOf(PLUGINS_PARAMETER, it) } ?: emptyList()
}
internal data class BaselineArgument(val baseline: File?) : CliArgument() {
override fun toArgument() = baseline?.let { listOf(BASELINE_PARAMETER, it.absolutePath) } ?: emptyList()
}
internal data class XmlReportArgument(val file: File?) : CliArgument() {
override fun toArgument() = file?.let { listOf(REPORT_PARAMETER, "xml:${it.absolutePath}") } ?: emptyList()
}
internal data class HtmlReportArgument(val file: File?) : CliArgument() {
override fun toArgument() = file?.let { listOf(REPORT_PARAMETER, "html:${it.absolutePath}") } ?: emptyList()
}
internal data class ConfigArgument(val config: FileCollection?) : CliArgument() {
override fun toArgument() = config?.let { configPaths ->
listOf(CONFIG_PARAMETER,
configPaths.joinToString(",") { it.absolutePath })
} ?: emptyList()
}
internal data class DebugArgument(val value: Boolean) : CliArgument() {
override fun toArgument() = if (value) listOf(DEBUG_PARAMETER) else emptyList()
}
internal data class ParallelArgument(val value: Boolean) : CliArgument() {
override fun toArgument() = if (value) listOf(PARALLEL_PARAMETER) else emptyList()
}
internal data class DisableDefaultRulesetArgument(val value: Boolean) : CliArgument() {
override fun toArgument() = if (value) listOf(DISABLE_DEFAULT_RULESETS_PARAMETER) else emptyList()
}
|
apache-2.0
|
964d24568c220bb52312c8314e222b43
| 38.694444 | 109 | 0.754024 | 3.99162 | false | true | false | false |
Mithrandir21/Duopoints
|
app/src/main/java/com/duopoints/android/MainAct.kt
|
1
|
23679
|
package com.duopoints.android
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AlertDialog
import android.support.v7.widget.Toolbar
import android.view.Gravity
import android.view.MenuItem
import android.widget.Toast
import co.chatsdk.core.events.NetworkEvent
import co.chatsdk.core.session.NM
import co.chatsdk.ui.helpers.NotificationUtils
import co.chatsdk.ui.helpers.OpenFromPushChecker
import co.chatsdk.ui.manager.BaseInterfaceAdapter
import co.chatsdk.ui.manager.InterfaceManager
import com.duopoints.android.activities.IntroActivity
import com.duopoints.android.fragments.base.BaseFrag
import com.duopoints.android.fragments.chat.MainChatFragment
import com.duopoints.android.fragments.connectivity.ConnectivityLostFrag
import com.duopoints.android.fragments.friends.FriendsFrag
import com.duopoints.android.fragments.general.SpinnerFrag
import com.duopoints.android.fragments.home.HomeFrag
import com.duopoints.android.fragments.points.GivePointsFrag
import com.duopoints.android.fragments.points.choose.ChoosePointsFrag
import com.duopoints.android.fragments.relprofile.RelationshipProfileFrag
import com.duopoints.android.fragments.requests.relationship.AllRelationshipRequestsFrag
import com.duopoints.android.fragments.settings.SettingMainFrag
import com.duopoints.android.fragments.settings.SettingNotificationsFrag
import com.duopoints.android.fragments.signin.SigninFrag
import com.duopoints.android.fragments.userprofile.UserProfileFrag
import com.duopoints.android.logistics.*
import com.duopoints.android.logistics.models.NotificationsType
import com.duopoints.android.logistics.receivers.NetworkStateReceiver
import com.duopoints.android.rest.models.points.PointType
import com.duopoints.android.ui.animations.FragmentTransitions
import com.duopoints.android.ui.lists.PointTypeAdapter
import com.duopoints.android.ui.lists.base.AdapterDelegatesManager
import com.duopoints.android.ui.lists.base.BaseAdapter
import com.duopoints.android.ui.lists.base.BaseAdapterListener
import com.duopoints.android.ui.lists.layouts.dividers.SimpleVerticalItemDivider
import com.duopoints.android.ui.lists.layouts.linear.PreFetchVerticalLayoutManager
import com.duopoints.android.utils.JavaUtils
import com.duopoints.android.utils.ReactiveUtils
import com.duopoints.android.utils.UiUtils
import com.duopoints.android.utils.logging.LogLevel
import com.duopoints.android.utils.logging.log
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.common.collect.Iterables
import com.mikepenz.aboutlibraries.Libs
import com.mikepenz.aboutlibraries.LibsBuilder
import com.trello.rxlifecycle2.RxLifecycle
import com.trello.rxlifecycle2.android.ActivityEvent
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_nav_main_menu.*
import kotlinx.android.synthetic.main.layout_nav_points_list.*
class MainAct : RxAppCompatActivity(), PointTypeAdapter.PointTypeClickListener, BaseAdapterListener, NetworkStateReceiver.NetworkStateReceiverListener {
private lateinit var drawer: DrawerLayout
private lateinit var pointAdapter: BaseAdapter
private var cartSubscription: Disposable? = null
private var chatSubscription: Disposable? = null
private var openFromPushChecker: OpenFromPushChecker? = null
private val networkStateReceiver: NetworkStateReceiver = NetworkStateReceiver()
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(if (SettingsManager.getUseLightTheme()) R.style.AppTheme_Light else R.style.AppTheme_Dark)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
drawer = drawerLayout // Set Drawer so that it can be manipulated by
if (isGooglePlayServicesAvailable()) {
// Opening Chat if Intent comes from a Push Notification
if (!chatPush(savedInstanceState)) {
replaceFragment(SigninFrag.newInstance(SettingsManager.getIntroCompleted()), false, true)
}
setupLeftNav()
setupRightNav()
}
// Locks drawers until unlocked by Splash Screen
lockDrawers()
networkStateReceiver.addListener(this)
registerReceiver(networkStateReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
notifyChatMessages()
}
override fun onResume() {
super.onResume()
// Put in both onCreate and onResume per the Firebase guidelines
isGooglePlayServicesAvailable()
if (!SettingsManager.getIntroCompleted()) {
startActivity(Intent(this, IntroActivity::class.java))
}
}
private fun setupLeftNav() {
SessionManager.observeUser()
.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.DESTROY))
.subscribe { userDataOptional ->
if (userDataOptional.isPresent) {
val userData = userDataOptional.get()
thinUserNav.setUserImage(userData.userUuid)
thinUserNav.setUserTitle(JavaUtils.getUserName(userData, false))
thinUserNav.setUserSubtitle(userData.userTotalPoints.toString() + " Points")
thinUserNav.setUserSubSubtitle("Level " + userData.userLevelNumber)
thinUserNav.setOnClickListener {
addFragment(UserProfileFrag.newInstance(userData), true)
drawer.closeDrawers()
}
} else {
thinUserNav.clearUserImage()
thinUserNav.setUserTitle("")
thinUserNav.setUserSubtitle("")
thinUserNav.setUserSubSubtitle("")
thinUserNav.setOnClickListener(null)
}
}
SessionManager.observeUserRelationshipWithDefault()
.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.DESTROY))
.subscribe { relationshipOptional ->
if (relationshipOptional.isPresent) {
// Update Notifications Badge Icon (if count > 0)
DuoNotificationsManager.observeNotificationsTypesWithDefault(NotificationsType.NEW_POINTS)
.compose(ReactiveUtils.commonObservableBindUntil(lifecycle(), ActivityEvent.DESTROY))
.subscribe({ thinNavRelationship.setNavIcon(R.drawable.relationship, it.size) })
thinNavRelationship.setOnClickListener {
DuoNotificationsManager.removeAllType(NotificationsType.NEW_POINTS)
addFragment(RelationshipProfileFrag.newInstance(relationshipOptional.get()), true, true)
drawer.closeDrawers()
}
} else {
// Update Notifications Badge Icon (if count > 0)
DuoNotificationsManager.observeNotificationsEntireList()
.map { it.filter { it.type == NotificationsType.NEW_RELATIONSHIP_REQUEST || it.type == NotificationsType.NEW_RELATIONSHIP_REQUEST_UPDATES } }
.compose(ReactiveUtils.commonObservableBindUntil(lifecycle(), ActivityEvent.DESTROY))
.subscribe({ thinNavRelationship.setNavIcon(R.drawable.relationship, it.size) })
thinNavRelationship.setOnClickListener {
DuoNotificationsManager.removeAllType(NotificationsType.NEW_RELATIONSHIP_REQUEST)
DuoNotificationsManager.removeAllType(NotificationsType.NEW_RELATIONSHIP_REQUEST_UPDATES)
addFragment(AllRelationshipRequestsFrag.newInstance(), true, true)
drawer.closeDrawers()
}
}
}
thinNavHome.setOnClickListener {
replaceFragment(HomeFrag.newInstance(), true, false, true)
drawer.closeDrawers()
}
thinNavPoints.setOnClickListener {
addFragment(ChoosePointsFrag.newInstance(), true, true)
drawer.closeDrawers()
}
DuoNotificationsManager.observeNotificationsTypesWithDefault(NotificationsType.NEW_FRIEND_REQUEST)
.compose(ReactiveUtils.commonObservableBindUntil(lifecycle(), ActivityEvent.DESTROY))
.subscribe({ thinNavFriends.setNavIcon(R.drawable.friends, it.size) })
thinNavFriends.setOnClickListener {
DuoNotificationsManager.removeAllType(NotificationsType.NEW_FRIEND_REQUEST)
addFragment(FriendsFrag.newInstance(SessionManager.getUser()), true, true)
drawer.closeDrawers()
}
thinNavChat.setOnClickListener({
addFragment(MainChatFragment.newInstance(), true, true)
drawer.closeDrawers()
})
thinNavSettings.setOnClickListener {
if (!alreadyShowingFragment(SettingNotificationsFrag::class.java.simpleName)) {
addFragment(SettingMainFrag.newInstance(), true, true)
}
drawer.closeDrawers()
}
thinNavAbout.setOnClickListener {
LibsBuilder().withActivityStyle(Libs.ActivityStyle.DARK).start(this)
drawer.closeDrawers()
}
thinNavLogOut.setOnClickListener {
CartManager.clear()
DuoNotificationsManager.clear()
FavouriteManager.clear()
SessionManager.clearUser()
intent.let {
finish()
startActivity(it)
}
}
}
private fun setupRightNav() {
rightNavRecyclerView.layoutManager = PreFetchVerticalLayoutManager(this)
rightNavRecyclerView.addItemDecoration(SimpleVerticalItemDivider(UiUtils.convertDpToPixel(8f).toInt()))
pointAdapter = BaseAdapter(AdapterDelegatesManager().addDelegate(PointTypeAdapter(this)), listener = this)
rightNavRecyclerView.adapter = pointAdapter
cartSubscription = CartManager.observeCurrentCart()
.subscribe({ newItems -> pointAdapter.replaceData(newItems) }) { throwable ->
Toast.makeText(this, "Error:" + throwable.message, Toast.LENGTH_SHORT).show()
throwable.printStackTrace()
}
rightNavClearPointsActionButton.setOnClickListener {
AlertDialog.Builder(this)
.setTitle("Clear Point")
.setMessage("Are you sure you want to clear all points gathered?")
.setPositiveButton("Yes") { _, _ -> CartManager.clear() }
.setNegativeButton("No") { dialog, _ -> dialog.dismiss() }
.show()
}
rightNavGivenPointsActionButton.setOnClickListener { givePointsAction() }
// If the Cart starts of empty, disable the buttons.
if (CartManager.getCurrentCart().isEmpty()) {
listEmptied()
}
// Reload the Cart after a Favourite has changed
FavouriteManager.observeFavouriteList()
.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.DESTROY))
.subscribe({ pointAdapter.replaceData(CartManager.getCurrentCart()) }, Throwable::printStackTrace)
}
override fun onBackPressed() {
if (drawer.isDrawerOpen(navLeftView) || drawer.isDrawerOpen(navRightView)) {
drawer.closeDrawers()
} else if (backStackBackAction()) {
log(LogLevel.DEBUG, "Back button consumed by fragments.")
} else {
super.onBackPressed()
}
}
private fun backStackBackAction(): Boolean {
if (supportFragmentManager.backStackEntryCount == 0) {
return false
}
val frag = Iterables.getLast(supportFragmentManager.fragments)
if (frag != null && frag is BaseFrag) {
// If the Fragment is onResume and it consumes the back button event
if (frag.backButtonReady() && frag.onBackButtonEvent()) {
return true
}
}
// None of the Fragments consumed the Back button
return false
}
override fun onDestroy() {
super.onDestroy()
cartSubscription?.dispose()
chatSubscription?.dispose()
networkStateReceiver.removeListener(this)
unregisterReceiver(networkStateReceiver)
}
override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
if (menuItem.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(menuItem)
}
/*********************
* PUSH NOTIFICATION
*********************/
private fun chatPush(savedInstanceState: Bundle?): Boolean {
openFromPushChecker = OpenFromPushChecker()
openFromPushChecker?.let {
if (it.checkOnCreate(intent, savedInstanceState)) {
val threadEntityID = intent.extras?.getString(BaseInterfaceAdapter.THREAD_ENTITY_ID)
InterfaceManager.shared().a.startChatActivityForID(this, threadEntityID)
return true
}
}
return false
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
openFromPushChecker = OpenFromPushChecker()
openFromPushChecker?.let {
if (it.checkOnNewIntent(intent)) {
val threadEntityID = intent.extras!!.getString(BaseInterfaceAdapter.THREAD_ENTITY_ID)
if (threadEntityID != null) {
InterfaceManager.shared().a.startChatActivityForID(this, threadEntityID)
}
}
}
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.let {
openFromPushChecker?.onSaveInstanceState(outState)
}
}
private fun notifyChatMessages() {
chatSubscription = NM.events().sourceOnMain()
.filter(NetworkEvent.threadsUpdated())
.subscribe {
it.message
?.takeUnless { it.sender.isMe }
?.let { NotificationUtils.createMessageNotification(this, it) }
}
}
/*******************
* CLASS FUNCTIONS
*******************/
fun lockDrawers() {
drawer.closeDrawers()
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
}
fun unlockDrawers() {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
}
fun openNavDrawer() {
drawer.openDrawer(Gravity.START)
}
fun openPointsDrawer() {
drawer.openDrawer(Gravity.END)
}
fun closeDrawer() {
drawer.closeDrawers()
}
fun setToolbar(toolbar: Toolbar, navIconPresenter: Boolean = true, drawerIconShowing: Boolean = false) {
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(navIconPresenter)
if (drawerIconShowing) {
val actionBarDrawerToggle = ActionBarDrawerToggle(this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close)
actionBarDrawerToggle.isDrawerIndicatorEnabled = true
drawer.addDrawerListener(actionBarDrawerToggle)
actionBarDrawerToggle.syncState()
}
}
private fun isGooglePlayServicesAvailable(): Boolean {
val googleApiAvailability = GoogleApiAvailability.getInstance()
val status = googleApiAvailability.isGooglePlayServicesAvailable(this)
if (status != ConnectionResult.SUCCESS) {
if (googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(this, status, 2404).show()
}
return false
}
return true
}
/*******************
* ADD FRAGMENT
*******************/
fun addFragment(fragment: BaseFrag, allowBackToThis: Boolean) {
addFragment(fragment, false, allowBackToThis)
}
fun addFragment(fragment: BaseFrag, skipIfVisible: Boolean, allowBackToThis: Boolean) {
addFragment(fragment, skipIfVisible, fragment.javaClass.simpleName, fragment.javaClass.simpleName, allowBackToThis)
}
fun addFragment(fragment: BaseFrag, skipIfVisible: Boolean, fragmentTag: String, backStackStateName: String, allowBackToThis: Boolean, transitions: FragmentTransitions? = null) {
transaction(false, skipIfVisible, fragment, fragmentTag, backStackStateName, allowBackToThis, false, transitions)
}
/*******************
* REPLACE FRAGMENT
*******************/
fun replaceFragment(fragment: BaseFrag, allowBackToThis: Boolean, clearStack: Boolean) {
replaceFragment(fragment, false, allowBackToThis, clearStack)
}
fun replaceFragment(fragment: BaseFrag, skipIfVisible: Boolean, allowBackToThis: Boolean, clearStack: Boolean) {
replaceFragment(fragment, skipIfVisible, fragment.javaClass.simpleName, fragment.javaClass.simpleName, allowBackToThis, clearStack)
}
fun replaceFragment(fragment: BaseFrag, skipIfVisible: Boolean, fragmentTag: String, backStackStateName: String, allowBackToThis: Boolean, clearStack: Boolean, transitions: FragmentTransitions? = null) {
transaction(true, skipIfVisible, fragment, fragmentTag, backStackStateName, allowBackToThis, clearStack, transitions)
}
private fun transaction(replace: Boolean, skipIfVisible: Boolean, fragment: BaseFrag, fragmentTag: String, backStackStateName: String, allowBackToThis: Boolean, clearStack: Boolean, transitions: FragmentTransitions?) {
if (skipIfVisible && alreadyShowingFragment(fragmentTag)) {
log(LogLevel.WARN, "Already showing $fragmentTag")
return // Already showing, so don't do anything.
}
if (clearStack) {
supportFragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
val transaction = supportFragmentManager.beginTransaction()
if (transitions != null) {
FragmentTransitions.addTransition(transitions, transaction)
}
if (replace) {
transaction.replace(R.id.mainContainer, fragment, fragmentTag)
} else {
transaction.add(R.id.mainContainer, fragment, fragmentTag)
}
if (allowBackToThis) {
transaction.addToBackStack(backStackStateName)
}
transaction.commit()
}
private fun alreadyShowingFragment(fragmentTag: String): Boolean {
// TODO - This will ONLY work for single pane layouts
return fragmentTag == supportFragmentManager.fragments.last().javaClass.simpleName
}
/*******************
* LOADING FRAGMENT
*******************/
fun showSpinner(show: Boolean) {
val fragment = supportFragmentManager.findFragmentByTag(SpinnerFrag::class.java.simpleName)
if (show) {
if (fragment != null) { // Loading fragment already showing
log(LogLevel.WARN, "Loading fragment already showing")
return
}
supportFragmentManager.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.add(R.id.spinnerContainer, SpinnerFrag.newInstance(), SpinnerFrag::class.java.simpleName)
.commit()
} else {
if (fragment == null) { // Loading fragment not showing
log(LogLevel.WARN, "Loading fragment not showing")
return
}
supportFragmentManager.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.remove(fragment)
.commit()
}
}
/*************************
* POINT NAV CALL BACKS
*************************/
override fun onClick(pointType: PointType) {
AlertDialog.Builder(this)
.setTitle("Remove point")
.setMessage("Are you sure you wish to remove '" + pointType.pointTypeTitle + "' from the list?")
.setPositiveButton("Yes") { _, _ ->
if (CartManager.removePointType(pointType)) {
Toast.makeText(this, "Point removed", Toast.LENGTH_SHORT).show()
} else {
log(LogLevel.ERROR, "Point does not exist in the list! Warning!\n" + pointType.toString())
}
}
.setNegativeButton("Cancel", null)
.show()
}
override fun listEmptied() {
rightNavGivenPointsActionButton.text = "Choose Points"
rightNavGivenPointsActionButton.setOnClickListener {
addFragment(ChoosePointsFrag.newInstance(), true)
drawer.closeDrawers()
}
rightNavClearPointsActionButton.isEnabled = false
}
override fun listFilled() {
rightNavGivenPointsActionButton.text = "Give Points"
rightNavGivenPointsActionButton.setOnClickListener { givePointsAction() }
rightNavClearPointsActionButton.isEnabled = true
}
private fun givePointsAction() {
if (SessionManager.getUserRelationship() == null) {
Toast.makeText(this, "You have to be in a relationship to give points. Why not start one?", Toast.LENGTH_LONG).show()
} else {
addFragment(GivePointsFrag.newInstance(), true)
drawer.closeDrawers()
}
}
/*******************
* NETWORK EVENTS
*******************/
override fun networkAvailable() {
val fragment = supportFragmentManager.findFragmentByTag(ConnectivityLostFrag::class.java.simpleName)
if (fragment == null) { // Connectivity fragment not showing
log(LogLevel.WARN, "Connectivity fragment not showing")
return
}
supportFragmentManager.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.remove(fragment)
.commit()
}
override fun networkUnavailable() {
val fragment = supportFragmentManager.findFragmentByTag(ConnectivityLostFrag::class.java.simpleName)
if (fragment != null) { // Loading fragment already showing
log(LogLevel.WARN, "Connectivity fragment already showing")
return
}
supportFragmentManager.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out)
.add(R.id.networkConnectivityContainer, ConnectivityLostFrag.newInstance(), ConnectivityLostFrag::class.java.simpleName)
.commit()
}
}
|
gpl-3.0
|
212a7b6ecf3eadb3efe724c1064ff9e6
| 39.827586 | 222 | 0.652223 | 5.171216 | false | false | false | false |
AgileVentures/MetPlus_resumeCruncher
|
core/src/main/kotlin/org/metplus/cruncher/utilities/DocumentParser.kt
|
1
|
1662
|
package org.metplus.cruncher.utilities
import org.apache.tika.exception.TikaException
import org.apache.tika.metadata.Metadata
import org.apache.tika.parser.AutoDetectParser
import org.apache.tika.sax.BodyContentHandler
import org.metplus.cruncher.error.DocumentParseException
import org.slf4j.LoggerFactory
import org.xml.sax.SAXException
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
class DocumentParserImpl(stream: ByteArrayOutputStream) {
private var stream: ByteArrayInputStream = ByteArrayInputStream(stream.toByteArray())
private var document: String? = null
@Throws(DocumentParseException::class)
fun parse() {
val parser = AutoDetectParser()
val handler = BodyContentHandler()
val metadata = Metadata()
try {
parser.parse(stream, handler, metadata)
document = handler.toString()
} catch (e: SAXException) {
throw DocumentParseException(e.message)
} catch (e: TikaException) {
throw DocumentParseException(e.message)
} catch (e: IOException) {
throw DocumentParseException(e.message)
} finally {
try {
stream.close()
} catch (e: IOException) {
LOG.warn("Unable to close the stream: " + e.message)
}
}
}
@Throws(DocumentParseException::class)
fun getDocument(): String? {
if (document == null)
parse()
return document
}
companion object {
private val LOG = LoggerFactory.getLogger(DocumentParserImpl::class.java)
}
}
|
gpl-3.0
|
e358e1506e168678cab78f75c02cbae7
| 30.358491 | 89 | 0.663658 | 4.629526 | false | false | false | false |
GeoffreyMetais/vlc-android
|
application/resources/src/main/java/org/videolan/resources/opensubtitles/OpenSubtitleService.kt
|
1
|
1478
|
package org.videolan.resources.opensubtitles
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.videolan.resources.AppContextProvider
import org.videolan.resources.util.ConnectivityInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
private const val BASE_URL = "https://rest.opensubtitles.org/search/"
private const val USER_AGENT = "VLSub 0.9"
private fun buildClient() = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(OkHttpClient.Builder()
.addInterceptor(UserAgentInterceptor(USER_AGENT))
.addInterceptor(ConnectivityInterceptor(AppContextProvider.appContext))
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.build())
.addConverterFactory(MoshiConverterFactory.create())
.build()
.create(IOpenSubtitleService::class.java)
private class UserAgentInterceptor(val userAgent: String): Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request: Request = chain.request()
val userAgentRequest: Request = request.newBuilder().header("User-Agent", userAgent).build()
return chain.proceed(userAgentRequest)
}
}
interface OpenSubtitleClient {
companion object { val instance: IOpenSubtitleService by lazy { buildClient() } }
}
|
gpl-2.0
|
9056e11df2097f4a184b5def2c2adb57
| 35.95 | 100 | 0.732747 | 4.707006 | false | false | false | false |
didi/DoraemonKit
|
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/ui/adapter/McCaseInfoDialogProvider.kt
|
1
|
1630
|
package com.didichuxing.doraemonkit.kit.mc.ui.adapter
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.didichuxing.doraemonkit.kit.test.mock.data.CaseInfo
import com.didichuxing.doraemonkit.mc.R
import com.didichuxing.doraemonkit.widget.dialog.DialogListener
import com.didichuxing.doraemonkit.widget.dialog.DialogProvider
/**
* Created by jint on 2019/4/12
* 完善健康体检用户信息dialog
* @author jintai
*/
class McCaseInfoDialogProvider internal constructor(data: Any?, listener: DialogListener?) :
DialogProvider<Any?>(data, listener) {
private lateinit var mPositive: TextView
private lateinit var mNegative: TextView
private lateinit var mCaseName: EditText
private lateinit var mPersonName: EditText
override fun getLayoutId(): Int {
return R.layout.dk_dialog_mc_case_info
}
override fun findViews(view: View) {
mPositive = view.findViewById(R.id.positive)
mNegative = view.findViewById(R.id.negative)
mCaseName = view.findViewById(R.id.edit_case_name)
mPersonName = view.findViewById(R.id.edit_user_name)
}
override fun getPositiveView(): View {
return mPositive
}
override fun getNegativeView(): View {
return mNegative
}
override fun getCancelView(): View? {
return null
}
fun getCaseInfo(): CaseInfo {
return CaseInfo(
caseName = mCaseName.text.toString(),
personName = mPersonName.text.toString()
)
}
override fun isCancellable(): Boolean {
return false
}
}
|
apache-2.0
|
e58b36561a5f3b1ae02f3830a45fe691
| 26.758621 | 92 | 0.7 | 4.055416 | false | false | false | false |
arturbosch/detekt
|
detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UnusedPrivateClassSpec.kt
|
1
|
12093
|
package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLint
import io.gitlab.arturbosch.detekt.test.lint
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class UnusedPrivateClassSpec : Spek({
val subject by memoized { UnusedPrivateClass() }
describe("top level interfaces") {
it("should report them if not used") {
val code = """
private interface Foo
class Bar
"""
val findings = subject.compileAndLint(code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(1, 1)
}
describe("top level private classes") {
it("should report them if not used") {
val code = """
private class Foo
class Bar
"""
val findings = subject.compileAndLint(code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(1, 1)
}
it("should not report them if used as parent") {
val code = """
private open class Foo
private class Bar : Foo()
"""
val findings = subject.compileAndLint(code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(2, 1)
}
it("should not report them used as generic parent type") {
val code = """
class Bar
private interface Foo<in T> {
operator fun invoke(b: T): Unit
}
data class FooOne(val b: Bar) : Foo<Bar> {
override fun invoke(b: Bar): Unit = Unit
}
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
}
it("should not report them if used inside a function") {
val code = """
private class Foo
fun something() {
val foo: Foo = Foo()
}
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as function parameter") {
val code = """
private class Foo
private object Bar {
fun bar(foo: Foo) = Unit
}
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as nullable variable type") {
val code = """
private class Foo
private val a: Foo? = null
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as variable type") {
val code = """
private class Foo
private lateinit var a: Foo
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as generic type") {
val code = """
private class Foo
private lateinit var foos: List<Foo>
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as inner type parameter") {
val code = """
private val elements = listOf(42).filterIsInstance<Set<Item>>()
private class Item
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as outer type parameter") {
val code = """
private val elements = listOf(42).filterIsInstance<Something<Int>>()
private abstract class Something<E>: Collection<E>
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as generic type in functions") {
val code = """
private class Foo
private var a = bar<Foo>()
fun <T> bar(): T {
throw Exception()
}
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as nested generic type") {
val code = """
private class Foo
private lateinit var foos: List<List<Foo>>
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as type with generics") {
val code = """
private class Foo<T>
private lateinit var foos: Foo<String>
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as nullable type with generics") {
val code = """
private class Foo<T>
private var foos: Foo<String>? = Foo()
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as non-argument constructor") {
val code = """
private class Foo
private val a = Foo()
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as constructor with arguments") {
val code = """
private class Foo(val a: String)
private val a = Foo("test")
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as function return type") {
val code = """
private class Foo(val a: String)
private object Bar {
fun foo(): Foo? = null
}
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as lambda declaration parameter") {
val code = """
private class Foo
private val lambda: ((Foo) -> Unit)? = null
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as lambda declaration return type") {
val code = """
private class Foo
private val lambda: (() -> Foo)? = null
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as lambda declaration generic type") {
val code = """
private class Foo
private val lambda: (() -> List<Foo>)? = null
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report them if used as inline object type") {
val code = """
private abstract class Foo {
abstract fun bar()
}
private object Bar {
private fun foo() = object : Foo() {
override fun bar() = Unit
}
}
"""
val findings = subject.compileAndLint(code)
assertThat(findings).isEmpty()
}
}
describe("testcase for reported false positives") {
it("does not crash when using wildcards in generics - #1345") {
val code = """
import kotlin.reflect.KClass
private class Foo
fun bar(clazz: KClass<*>) = Unit
"""
val findings = UnusedPrivateClass().compileAndLint(code)
assertThat(findings).hasSize(1)
}
it("does not report (companion-)object/named-dot references - #1347") {
val code = """
class Test {
val items = Item.values().map { it.text }.toList()
}
private enum class Item(val text: String) {
A("A"),
B("B"),
C("C")
}
"""
val findings = UnusedPrivateClass().compileAndLint(code)
assertThat(findings).isEmpty()
}
it("does not report classes that are used with ::class - #1390") {
val code = """
class UnusedPrivateClassTest {
private data class SomeClass(val name: String)
private data class AnotherClass(val id: Long)
fun `verify class is used`(): Boolean {
val instance = SomeClass(name = "test")
return AnotherClass::class.java.simpleName == instance::class.java.simpleName
}
fun getSomeObject(): ((String) -> Any) = ::InternalClass
private class InternalClass(val param: String)
}
"""
val findings = UnusedPrivateClass().compileAndLint(code)
assertThat(findings).isEmpty()
}
it("does not report used private annotations - #2093") {
val code = """
private annotation class Test1
private annotation class Test2
private annotation class Test3
private annotation class Test4
@Test1 class Custom(@Test2 param: String) {
@Test3 val property = ""
@Test4 fun function() {}
}
"""
val findings = UnusedPrivateClass().compileAndLint(code)
assertThat(findings).isEmpty()
}
it("does not report imported enum class - #2809") {
val code = """
package com.example
import com.example.C.E.E1
class C {
fun test() {
println(E1)
}
private enum class E {
E1,
E2,
E3
}
}
"""
val findings = UnusedPrivateClass().lint(code)
assertThat(findings).isEmpty()
}
it("should report not imported enum class - #2809, #2816") {
val code = """
package com.example
import com.example.C.EFG.EFG1
class C {
fun test() {
println(EFG1)
}
private enum class E {
E1
}
private enum class EFG {
EFG1
}
}
"""
val findings = UnusedPrivateClass().lint(code)
assertThat(findings).hasSize(1)
assertThat(findings).hasSourceLocation(10, 5)
}
}
})
|
apache-2.0
|
73b4a8ef5810ab35160c9d6f665cd98e
| 28.712531 | 105 | 0.469859 | 5.704245 | false | false | false | false |
nemerosa/ontrack
|
ontrack-extension-jenkins/src/main/java/net/nemerosa/ontrack/extension/jenkins/autoversioning/JenkinsPostProcessing.kt
|
1
|
4447
|
package net.nemerosa.ontrack.extension.jenkins.autoversioning
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.extension.av.dispatcher.AutoVersioningOrder
import net.nemerosa.ontrack.extension.av.postprocessing.PostProcessing
import net.nemerosa.ontrack.extension.av.postprocessing.PostProcessingMissingConfigException
import net.nemerosa.ontrack.extension.jenkins.JenkinsConfiguration
import net.nemerosa.ontrack.extension.jenkins.JenkinsConfigurationService
import net.nemerosa.ontrack.extension.jenkins.JenkinsExtensionFeature
import net.nemerosa.ontrack.extension.jenkins.client.JenkinsClientFactory
import net.nemerosa.ontrack.extension.support.AbstractExtension
import net.nemerosa.ontrack.model.settings.CachedSettingsService
import org.springframework.stereotype.Component
/**
* Upgrade post processing based on a generic job in Jenkins.
*/
@Component
class JenkinsPostProcessing(
extensionFeature: JenkinsExtensionFeature,
private val cachedSettingsService: CachedSettingsService,
private val jenkinsConfigurationService: JenkinsConfigurationService,
private val jenkinsClientFactory: JenkinsClientFactory,
// private val autoVersioningNotificationService: AutoVersioningNotificationService
) : AbstractExtension(extensionFeature), PostProcessing<JenkinsPostProcessingConfig> {
override val id: String = "jenkins"
override val name: String = "Jenkins job post processing"
override fun parseAndValidate(config: JsonNode?): JenkinsPostProcessingConfig {
return if (config != null && !config.isNull) {
JenkinsPostProcessingConfig.parseJson(config)
} else {
throw PostProcessingMissingConfigException()
}
}
override fun postProcessing(
config: JenkinsPostProcessingConfig,
autoVersioningOrder: AutoVersioningOrder,
repositoryURI: String,
repository: String,
upgradeBranch: String,
) {
// Gets the global settings
val settings: JenkinsPostProcessingSettings =
cachedSettingsService.getCachedSettings(JenkinsPostProcessingSettings::class.java)
// Configuration
val jenkinsConfigName = config.config ?: settings.config
val jenkinsJobPath = config.job ?: settings.job
// Checks the configuration
if (jenkinsConfigName.isBlank() || jenkinsJobPath.isBlank()) {
throw JenkinsPostProcessingSettingsNotFoundException()
}
// Gets the Jenkins configuration by name
val jenkinsConfig: JenkinsConfiguration = jenkinsConfigurationService.getConfiguration(jenkinsConfigName)
// Gets a Jenkins client for this configuration
val jenkinsClient = jenkinsClientFactory.getClient(jenkinsConfig)
// Launches the job and waits for its completion
try {
val jenkinsBuild = jenkinsClient.runJob(
jenkinsJobPath,
mapOf(
"DOCKER_IMAGE" to config.dockerImage,
"DOCKER_COMMAND" to config.dockerCommand,
"COMMIT_MESSAGE" to (config.commitMessage ?: autoVersioningOrder.defaultCommitMessage),
"REPOSITORY_URI" to repositoryURI,
"UPGRADE_BRANCH" to upgradeBranch,
"CREDENTIALS" to (config.credentials?.renderParameter() ?: ""),
),
settings.retries,
settings.retriesDelaySeconds
)
// Check for success
if (!jenkinsBuild.successful) {
throw JenkinsPostProcessingJobFailureException(
jenkins = jenkinsConfig.url,
job = jenkinsJobPath,
build = jenkinsBuild.id,
buildUrl = jenkinsBuild.url,
result = jenkinsBuild.result
)
}
} catch (e: Exception) {
if (e !is JenkinsPostProcessingJobFailureException) {
// Feedback already provided from inside the jenkins build
// TODO autoVersioningNotificationService.sendErrorNotification(prCreationOrder, "Failed to create post-processing build for ontrack auto-upgrade: ${e.message}")
}
throw e
}
}
private val AutoVersioningOrder.defaultCommitMessage: String
get() = "Post processing for version change in $targetPaths for $targetVersion"
}
|
mit
|
6a87e8f63894cb58da17ec57b7fa26c1
| 43.47 | 177 | 0.691253 | 5.423171 | false | true | false | false |
bbodi/KotlinReactSpringBootstrap
|
frontend/src/com/github/andrewoma/react/ReactSpec.kt
|
1
|
10337
|
package com.github.andrewoma.react
/**
* Interface describing ReactComponentSpec
*/
import org.w3c.dom.Element
import org.w3c.dom.HTMLElement
interface ReactMixin<P, S> {
/**
* Invoked immediately before rendering occurs.
* If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.
*/
fun componentWillMount(): Unit {
}
/**
* Invoked immediately after rendering occurs.
* At this point in the lifecycle, the component has a DOM representation which you can access via the rootNode argument or by calling this.getDOMNode().
* If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval,
* or send AJAX requests, perform those operations in this method.
*/
fun componentDidMount(): Unit {
}
/**
* Invoked when a component is receiving new props. This method is not called for the initial render.
*
* Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState().
* The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.
*
* @param nextProps the props object that the component will receive
*/
fun componentWillReceiveProps(nextProps: P): Unit {
}
/**
* Invoked before rendering when new props or state are being received.
* This method is not called for the initial render or when forceUpdate is used.
* Use this as an opportunity to return false when you're certain that the transition to the new props and state will not require a component update.
* By default, shouldComponentUpdate always returns true to prevent subtle bugs when state is mutated in place,
* but if you are careful to always treat state as immutable and to read only from props and state in render()
* then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.
*
* If performance is a bottleneck, especially with dozens or hundreds of components, use shouldComponentUpdate to speed up your app.
*
* @param nextProps the props object that the component will receive
* @param nextState the state object that the component will receive
*/
fun shouldComponentUpdate(nextProps: P, nextState: S): Boolean {
return true
}
/**
* Invoked immediately before rendering when new props or state are being received. This method is not called for the initial render.
* Use this as an opportunity to perform preparation before an update occurs.
*
* @param nextProps the props object that the component has received
* @param nextState the state object that the component has received
*/
fun componentWillUpdate(nextProps: P, nextState: S): Unit {
}
/**
* Invoked immediately after updating occurs. This method is not called for the initial render.
* Use this as an opportunity to operate on the DOM when the component has been updated.
*
* @param nextProps the props object that the component has received
* @param nextState the state object that the component has received
*/
fun componentDidUpdate(nextProps: P, nextState: S): Unit {
}
/**
* Invoked immediately before a component is unmounted from the DOM.
* Perform any necessary cleanup in this method, such as invalidating timers or cleaning up any DOM elements that were created in componentDidMount.
*/
fun componentWillUnmount(): Unit {
}
}
class Ref<T : Any>(val value: T?)
class RefContent(val realRef: dynamic) {
fun asComponent(): ReactComponent<Any, Any> = realRef
fun asDomNode(): HTMLElement = realRef
}
abstract class ReactComponentSpec<P : Any, S : Any>() : ReactMixin<P, S> {
lateinit var component: ReactComponent<Ref<P>, Ref<S>>
/**
* The mixins array allows you to use mixins to share behavior among multiple components.
*/
var mixins: Array<ReactMixin<Any, Any>> = arrayOf()
/**
* The displayName string is used in debugging messages. JSX sets this value automatically.
*/
var displayName: String = ""
fun refs(refName: String): RefContent {
return RefContent(component.refs[refName]!!)
}
var state: S
get() = component.state.value!!
set(value) = component.setState(Ref(value))
var props: P
get() = component.props.value!!
set(value) = component.setProps(Ref(value), null)
/**
* The propTypes object allows you to validate props being passed to your components.
*/
//var propTypes: PropTypeValidatorOptions
/**
* Invoked once before the component is mounted. The return value will be used as the initial value of this.state.
*/
fun getInitialState(): Ref<S>? {
val state = initialState()
return if (state == null) null else Ref(state)
}
open fun initialState(): S? {
return null
}
/**
* The render() method is required. When called, it should examine this.props and this.state and return a single child component.
* This child component can be either a virtual representation of a native DOM component (such as <div /> or React.DOM.div())
* or another composite component that you've defined yourself.
* The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked,
* and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using setTimeout).
* If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead.
* Keeping render() pure makes server rendering more practical and makes components easier to think about.
*/
abstract fun render(): ReactElement<P>?
// DefaultProps don't work very well as Kotlin set all the keys on an object and makes set versus null ambiguous
// So prevent the usage.
/**b
* Invoked once when the component is mounted.
* Values in the mapping will be set on this.props if that prop is not specified by the parent component (i.e. using an in check).
* This method is invoked before getInitialState and therefore cannot rely on this.state or use this.setState.
*/
fun getDefaultProps(): Ref<P>? {
return null
}
fun forceUpdate() {
component.forceUpdate();
}
}
/**
* Component classses created by createClass() return instances of ReactComponent when called.
* Most of the time when you're using React you're either creating or consuming these component objects.
*/
@native
interface ReactComponent<P, S> {
val refs: dynamic
val state: S
val props: P
/**
* If this component has been mounted into the DOM, this returns the corresponding native browser DOM element.
* This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.
*/
fun getDOMNode(): Element
/**
* When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with renderComponent().
* Simply call setProps() to change its properties and trigger a re-render.
*
* @param nextProps the object that will be merged with the component's props
* @param callback an optional callback function that is executed once setProps is completed.
*/
fun setProps(nextProps: P, callback: (() -> Unit)?): Unit
/**
* Like setProps() but deletes any pre-existing props instead of merging the two objects.
*
* @param nextProps the object that will replace the component's props
* @param callback an optional callback function that is executed once replaceProps is completed.
*/
fun replaceProps(nextProps: P, callback: () -> Unit): Unit
/**
* Transfer properties from this component to a target component that have not already been set on the target component.
* After the props are updated, targetComponent is returned as a convenience.
*
* @param target the component that will receive the props
*/
fun <C : ReactComponent<P, Any>> transferPropsTo(target: C): C
/**
* Merges nextState with the current state.
* This is the primary method you use to trigger UI updates from event handlers and server request callbacks.
* In addition, you can supply an optional callback function that is executed once setState is completed.
*
* @param nextState the object that will be merged with the component's state
* @param callback an optional callback function that is executed once setState is completed.
*/
fun setState(nextState: S, callback: () -> Unit = {}): Unit
/**
* Like setState() but deletes any pre-existing state keys that are not in nextState.
*
* @param nextState the object that will replace the component's state
* @param callback an optional callback function that is executed once replaceState is completed.
*/
fun replaceState(nextState: S, callback: () -> Unit): Unit
/**
* If your render() method reads from something other than this.props or this.state,
* you'll need to tell React when it needs to re-run render() by calling forceUpdate().
* You'll also need to call forceUpdate() if you mutate this.state directly.
* Calling forceUpdate() will cause render() to be called on the component and its children,
* but React will still only update the DOM if the markup changes.
* Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().
* This makes your application much simpler and more efficient.
*
* @param callback an optional callback that is executed once forceUpdate is completed.
*/
fun forceUpdate(callback: (() -> Unit)? = null): Unit
}
@native
interface ReactComponentFactory<P : Any, S : Any> {
operator fun invoke(properties: Ref<P>?, vararg children: Any?): ReactComponent<Ref<P>, Ref<S>>
}
@native
interface ReactElement<P> {
}
|
mit
|
78ceb1fd681c94cad3b1ef8d8658fe2b
| 41.719008 | 157 | 0.698655 | 4.639587 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise
|
imitate/src/main/java/com/engineer/imitate/ui/activity/fragmentmanager/TabLayoutsFragment.kt
|
1
|
2513
|
package com.engineer.imitate.ui.activity.fragmentmanager
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.engineer.imitate.R
import com.engineer.imitate.ui.widget.LabelLayoutProvider
import kotlinx.android.synthetic.main.fragment_tab_layouts.*
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [TabLayoutsFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class TabLayoutsFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab_layouts, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
context?.let {
val labels = arrayOf(
"111", "232", "232", "232",
"111", "232", "232", "232",
"111", "232", "232", "232"
)
dynamic_container.addView(LabelLayoutProvider.provideLabelLayout(it, labels))
}
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TabLayoutsFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
TabLayoutsFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
|
apache-2.0
|
bd3df107639b8dc67f761f556442cbf7
| 32.972973 | 89 | 0.637087 | 4.479501 | false | false | false | false |
groupdocs-comparison/GroupDocs.Comparison-for-Java
|
Demos/Micronaut/src/main/kotlin/com/groupdocs/ui/model/CompareResponse.kt
|
3
|
1282
|
package com.groupdocs.ui.model
data class CompareResponse(
/**
* List of change information
*/
val changes: List<DocumentChange>,
/**
* Extension of compared files, for saving total results
*/
val extension: String? = null,
/**
* Unique key of results
*/
val guid: String,
/**
* List of images of pages with marked changes
*/
val pages: List<ComparePage>,
)
/**
* PageDescriptionEntity
*
* @author Aspose Pty Ltd
*/
data class ComparePage(
val angle: Int = 0,
val data: String? = null,
val height: Int = 0,
val number: Int = 0,
val width: Int = 0,
)
data class DocumentChange(
val authors: List<String>,
val box: ChangeBox,
val comparisonAction: Int,
val componentType: String,
val id: Int,
val pageInfo: PageInfo,
val sourceText: String?,
val styleChanges: List<StyleChange>,
val targetText: String?,
val text: String,
val type: Int,
)
data class ChangeBox(
val x: Double,
val y: Double,
val height: Double,
val width: Double
)
data class PageInfo(
val height: Int,
val pageNumber: Int,
val width: Int
)
data class StyleChange(
val newValue: Any,
val oldValue: Any,
val propertyName: String
)
|
mit
|
ad3e18caf3c16e635dc988f0b67fc4c9
| 17.594203 | 60 | 0.620905 | 3.815476 | false | false | false | false |
donald-w/Anki-Android
|
AnkiDroid/src/main/java/com/ichi2/libanki/TagManager.kt
|
1
|
5361
|
/*
* Copyright (c) 2021 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.libanki
import com.ichi2.libanki.backend.model.TagUsnTuple
import net.ankiweb.rsdroid.RustCleanup
/**
* Manages the tag cache and tags for notes.
*
* This is the public API surface for tags, to unify [Tags] and [TagsV16]
*/
@RustCleanup("remove docs: this exists to unify Tags.java and TagsV16")
abstract class TagManager {
/*
* Registry save/load
* ***********************************************************
*/
@RustCleanup("Tags.java only")
abstract fun load(json: String)
@RustCleanup("Tags.java only")
abstract fun flush()
/*
* Registering and fetching tags
* ***********************************************************
*/
/** Given a list of tags, add any missing ones to tag registry. */
fun register(tags: Iterable<String>) = register(tags, null)
/** Given a list of tags, add any missing ones to tag registry. */
fun register(tags: Iterable<String>, usn: Int? = null) = register(tags, usn, false)
/** Given a list of tags, add any missing ones to tag registry.
* @param clear_first Whether to clear the tags in the database before registering the provided tags
* */
abstract fun register(tags: Iterable<String>, usn: Int? = null, clear_first: Boolean = false)
abstract fun all(): List<String>
/** Add any missing tags from notes to the tags list. The old list is cleared first */
fun registerNotes() = registerNotes(null)
/**
* Add any missing tags from notes to the tags list.
* @param nids The old list is cleared first if this is null
*/
abstract fun registerNotes(nids: kotlin.collections.Collection<Long>? = null)
abstract fun allItems(): Iterable<TagUsnTuple>
@RustCleanup("Tags.java only")
abstract fun save()
/**
* byDeck returns the tags of the cards in the deck
* @param did the deck id
* @param children whether to include the deck's children
* @return a list of the tags
*/
abstract fun byDeck(did: Long, children: Boolean = false): List<String>
/*
* Bulk addition/removal from notes
* ***********************************************************
*/
/**
* FIXME: This method must be fixed before it is used. See note below.
* Add/remove tags in bulk. TAGS is space-separated.
*
* @param ids The cards to tag.
* @param tags List of tags to add/remove. They are space-separated.
*/
fun bulkAdd(ids: List<Long>, tags: String) = bulkAdd(ids, tags, true)
/**
* FIXME: This method must be fixed before it is used. Its behaviour is currently incorrect.
* This method is currently unused in AnkiDroid so it will not cause any errors in its current state.
*
* @param ids The cards to tag.
* @param tags List of tags to add/remove. They are space-separated.
* @param add True/False to add/remove.
*/
abstract fun bulkAdd(ids: List<Long>, tags: String, add: Boolean = true)
fun bulkRem(ids: List<Long>, tags: String) = bulkAdd(ids, tags, false)
/*
* String-based utilities
* ***********************************************************
*/
/** Parse a string and return a list of tags. */
abstract fun split(tags: String): MutableList<String>
/** Join tags into a single string, with leading and trailing spaces. */
abstract fun join(tags: kotlin.collections.Collection<String>): String
/** Delete tags if they exist. */
abstract fun remFromStr(deltags: String, tags: String): String
/*
* List-based utilities
* ***********************************************************
*/
/** Strip duplicates, adjust case to match existing tags, and sort. */
@RustCleanup("List, not Collection")
abstract fun canonify(tagList: List<String>): java.util.AbstractSet<String>
/** @return True if TAG is in TAGS. Ignore case. */
abstract fun inList(tag: String, tags: Iterable<String>): Boolean
/*
* Sync handling
* ***********************************************************
*/
@RustCleanup("Tags.java only")
abstract fun beforeUpload()
/*
* ***********************************************************
* The methods below are not in LibAnki.
* ***********************************************************
*/
/** Add a tag to the collection. We use this method instead of exposing mTags publicly.*/
abstract fun add(tag: String, usn: Int?)
/** Whether any tags have a usn of -1 */
@RustCleanup("not optimised")
open fun minusOneValue(): Boolean = allItems().any { it.usn == -1 }
}
|
gpl-3.0
|
28e1d72d84ac2bbed0711ab81ffb4cb6
| 37.292857 | 105 | 0.602873 | 4.41598 | false | false | false | false |
Ztiany/Repository
|
Kotlin/Kotlin-github/common/src/main/java/com/bennyhuo/github/common/unused/PropertiesDelegate.kt
|
2
|
2047
|
package com.bennyhuo.github.common.unused
import java.io.File
import java.io.FileInputStream
import java.net.URL
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.full.isSuperclassOf
/**
* Created by benny on 8/12/17.
*/
class PropertiesDelegate(private val path: String) {
private lateinit var url: URL
private val properties: Properties by lazy {
val prop = Properties()
url = try {
javaClass.getResourceAsStream(path).use {
prop.load(it)
}
javaClass.getResource(path)
} catch (e: Exception) {
try {
ClassLoader.getSystemClassLoader().getResourceAsStream(path).use {
prop.load(it)
}
ClassLoader.getSystemClassLoader().getResource(path)
} catch (e: Exception) {
FileInputStream(path).use {
prop.load(it)
}
URL("file://${File(path).canonicalPath}")
}
}
prop
}
operator fun <T> getValue(thisRef: Any, property: KProperty<*>): T {
val value = properties[property.name]
val classOfT = property.returnType.classifier as KClass<*>
return when {
Boolean::class == classOfT -> value.toString().toBoolean()
Number::class.isSuperclassOf(classOfT) -> {
classOfT.javaObjectType.getDeclaredMethod("parse${classOfT.simpleName}", String::class.java).invoke(null, value)
}
String::class == classOfT -> value
else -> throw IllegalArgumentException("Unsupported type.")
} as T
}
operator fun <T> setValue(thisRef: Any, property: KProperty<*>, value: T) {
properties[property.name] = value.toString()
File(url.toURI()).outputStream().use {
properties.store(it, "")
}
}
}
abstract class AbsProperties(path: String) {
protected val prop = PropertiesDelegate(path)
}
|
apache-2.0
|
f06c689add21d0311fa420e5bed7daba
| 30.507692 | 128 | 0.590132 | 4.684211 | false | false | false | false |
android/health-samples
|
health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/screen/sleepsession/SleepSessionViewModel.kt
|
1
|
4993
|
/*
* 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.example.healthconnectsample.presentation.screen.sleepsession
import android.os.RemoteException
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.health.connect.client.permission.HealthPermission
import androidx.health.connect.client.records.SleepSessionRecord
import androidx.health.connect.client.records.SleepStageRecord
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.example.healthconnectsample.data.HealthConnectManager
import com.example.healthconnectsample.data.SleepSessionData
import kotlinx.coroutines.launch
import java.io.IOException
import java.util.UUID
class SleepSessionViewModel(private val healthConnectManager: HealthConnectManager) :
ViewModel() {
val permissions = setOf(
HealthPermission.createReadPermission(SleepSessionRecord::class),
HealthPermission.createWritePermission(SleepSessionRecord::class),
HealthPermission.createReadPermission(SleepStageRecord::class),
HealthPermission.createWritePermission(SleepStageRecord::class)
)
var permissionsGranted = mutableStateOf(false)
private set
var sessionsList: MutableState<List<SleepSessionData>> = mutableStateOf(listOf())
private set
var uiState: UiState by mutableStateOf(UiState.Uninitialized)
private set
val permissionsLauncher = healthConnectManager.requestPermissionsActivityContract()
fun initialLoad() {
viewModelScope.launch {
tryWithPermissionsCheck {
sessionsList.value = healthConnectManager.readSleepSessions()
}
}
}
fun generateSleepData() {
viewModelScope.launch {
tryWithPermissionsCheck {
// Delete all existing sleep data before generating new random sleep data.
healthConnectManager.deleteAllSleepData()
healthConnectManager.generateSleepData()
sessionsList.value = healthConnectManager.readSleepSessions()
}
}
}
/**
* Provides permission check and error handling for Health Connect suspend function calls.
*
* Permissions are checked prior to execution of [block], and if all permissions aren't granted
* the [block] won't be executed, and [permissionsGranted] will be set to false, which will
* result in the UI showing the permissions button.
*
* Where an error is caught, of the type Health Connect is known to throw, [uiState] is set to
* [UiState.Error], which results in the snackbar being used to show the error message.
*/
private suspend fun tryWithPermissionsCheck(block: suspend () -> Unit) {
permissionsGranted.value = healthConnectManager.hasAllPermissions(permissions)
uiState = try {
if (permissionsGranted.value) {
block()
}
UiState.Done
} catch (remoteException: RemoteException) {
UiState.Error(remoteException)
} catch (securityException: SecurityException) {
UiState.Error(securityException)
} catch (ioException: IOException) {
UiState.Error(ioException)
} catch (illegalStateException: IllegalStateException) {
UiState.Error(illegalStateException)
}
}
sealed class UiState {
object Uninitialized : UiState()
object Done : UiState()
// A random UUID is used in each Error object to allow errors to be uniquely identified,
// and recomposition won't result in multiple snackbars.
data class Error(val exception: Throwable, val uuid: UUID = UUID.randomUUID()) : UiState()
}
}
class SleepSessionViewModelFactory(
private val healthConnectManager: HealthConnectManager
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(SleepSessionViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return SleepSessionViewModel(
healthConnectManager = healthConnectManager
) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
|
apache-2.0
|
5f93f256b440bebe5197138701ae5187
| 38.944 | 99 | 0.714 | 5.311702 | false | false | false | false |
vondear/RxTools
|
RxUI/src/main/java/com/tamsiree/rxui/view/tablayout/tool/TLayoutMsgTool.kt
|
1
|
2015
|
package com.tamsiree.rxui.view.tablayout.tool
import android.view.View
import android.widget.RelativeLayout
import com.tamsiree.rxui.view.tablayout.TLayoutMsg
/**
* 未读消息提示View,显示小红点或者带有数字的红点:
* 数字一位,圆
* 数字两位,圆角矩形,圆角是高度的一半
* 数字超过两位,显示99+
*/
object TLayoutMsgTool {
@JvmStatic
fun show(msgView: TLayoutMsg?, num: Int) {
if (msgView == null) {
return
}
val lp = msgView.layoutParams as RelativeLayout.LayoutParams
val dm = msgView.resources.displayMetrics
msgView.visibility = View.VISIBLE
if (num <= 0) { //圆点,设置默认宽高
msgView.setStrokeWidth(0)
msgView.text = ""
lp.width = (5 * dm.density).toInt()
lp.height = (5 * dm.density).toInt()
msgView.layoutParams = lp
} else {
lp.height = (18 * dm.density).toInt()
if (num > 0 && num < 10) { //圆
lp.width = (18 * dm.density).toInt()
msgView.text = num.toString() + ""
} else if (num > 9 && num < 100) { //圆角矩形,圆角是高度的一半,设置默认padding
lp.width = RelativeLayout.LayoutParams.WRAP_CONTENT
msgView.setPadding((6 * dm.density).toInt(), 0, (6 * dm.density).toInt(), 0)
msgView.text = num.toString() + ""
} else { //数字超过两位,显示99+
lp.width = RelativeLayout.LayoutParams.WRAP_CONTENT
msgView.setPadding((6 * dm.density).toInt(), 0, (6 * dm.density).toInt(), 0)
msgView.text = "99+"
}
msgView.layoutParams = lp
}
}
fun setSize(rtv: TLayoutMsg?, size: Int) {
if (rtv == null) {
return
}
val lp = rtv.layoutParams as RelativeLayout.LayoutParams
lp.width = size
lp.height = size
rtv.layoutParams = lp
}
}
|
apache-2.0
|
1a920bff8b765d83fab68e8a955ea4fe
| 32.672727 | 92 | 0.546191 | 3.552783 | false | false | false | false |
varpeti/Suli
|
Android/work/varpe8/homeworks/01/HF01/app/src/main/java/ml/varpeti/hf01/ItemViewActivity.kt
|
1
|
1133
|
package ml.varpeti.hf01
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Button
import android.widget.TextView
class ItemViewActivity : AppCompatActivity()
{
var status = 0
var id = 0
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.item_view)
val extras = intent.extras ?: return
val name = extras.getString("name","")
id = extras.getInt("id",0)
status = 0
val tw = findViewById<TextView>(R.id.tw02)
tw.text = name;
val bok = findViewById<Button>(R.id.bok)
bok.setOnClickListener {
status = 1
finish()
}
}
override fun finish()
{
Log.i("\\|/", "fin: "+id+" "+status)
val data = Intent()
// Extras should be defined as constants
data.putExtra("id",id)
data.putExtra("status",status)
setResult(Activity.RESULT_OK, data)
super.finish()
}
}
|
unlicense
|
99f8976462dc3af7130ade70dabaf6dd
| 22.142857 | 54 | 0.619594 | 4.090253 | false | false | false | false |
wikimedia/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/talk/TalkTopicViewModel.kt
|
1
|
8011
|
package org.wikipedia.talk
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.DiffUtil
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.wikipedia.auth.AccountUtil
import org.wikipedia.database.AppDatabase
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.discussiontools.ThreadItem
import org.wikipedia.page.PageTitle
import org.wikipedia.settings.Prefs
import org.wikipedia.talk.db.TalkPageSeen
import org.wikipedia.util.Resource
import org.wikipedia.util.SingleLiveData
class TalkTopicViewModel(bundle: Bundle) : ViewModel() {
val pageTitle = bundle.getParcelable<PageTitle>(TalkTopicActivity.EXTRA_PAGE_TITLE)!!
val topicName = bundle.getString(TalkTopicActivity.EXTRA_TOPIC_NAME)!!
val topicId = bundle.getString(TalkTopicActivity.EXTRA_TOPIC_ID)!!
var currentSearchQuery = bundle.getString(TalkTopicActivity.EXTRA_SEARCH_QUERY)
var scrollTargetId = bundle.getString(TalkTopicActivity.EXTRA_REPLY_ID)
var topic: ThreadItem? = null
val sectionId get() = threadItems.indexOf(topic)
val threadItems = mutableListOf<ThreadItem>()
val flattenedThreadItems = mutableListOf<ThreadItem>()
var subscribed = false
private set
val threadItemsData = MutableLiveData<Resource<List<ThreadItem>>>()
val subscribeData = SingleLiveData<Resource<Boolean>>()
val undoResponseData = SingleLiveData<Resource<Boolean>>()
var undoSubject: CharSequence? = null
var undoBody: CharSequence? = null
var undoTopicId: String? = null
val isExpandable: Boolean get() {
return topic?.allReplies.orEmpty().any { it.level > 1 }
}
val isFullyExpanded: Boolean get() {
return !currentSearchQuery.isNullOrEmpty() || flattenedThreadItems.size == topic?.allReplies?.size
}
init {
loadTopic()
}
fun loadTopic() {
viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
threadItemsData.postValue(Resource.Error(throwable))
}) {
val discussionToolsInfoResponse = async { ServiceFactory.get(pageTitle.wikiSite).getTalkPageTopics(pageTitle.prefixedText) }
val subscribeResponse = async { ServiceFactory.get(pageTitle.wikiSite).getTalkPageTopicSubscriptions(topicName) }
val oldItemsFlattened = topic?.allReplies.orEmpty()
topic = discussionToolsInfoResponse.await().pageInfo?.threads.orEmpty().find { it.id == topicId }
val res = subscribeResponse.await()
subscribed = res.subscriptions[topicName] == 1
threadSha(topic)?.let {
AppDatabase.instance.talkPageSeenDao().insertTalkPageSeen(TalkPageSeen(it))
}
val newItemsFlattened = topic?.allReplies.orEmpty().filter { it.id !in oldItemsFlattened.map { item -> item.id } }
if (oldItemsFlattened.isNotEmpty() && newItemsFlattened.isNotEmpty()) {
if (AccountUtil.isLoggedIn) {
scrollTargetId = newItemsFlattened.findLast { it.author == AccountUtil.userName }?.id
}
if (scrollTargetId.isNullOrEmpty()) {
scrollTargetId = newItemsFlattened.first().id
}
}
threadItems.clear()
threadItems.addAll(topic?.replies.orEmpty())
if (scrollTargetId.isNullOrEmpty()) {
// By default, expand or collapse based on user preference
expandOrCollapseAll()
} else {
// If we have a scroll target, make sure we're expanded to view the target
topic?.allReplies?.forEach { it.isExpanded = true }
}
updateFlattenedThreadItems()
threadItemsData.postValue(Resource.Success(threadItems))
}
}
fun toggleSubscription() {
viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
subscribeData.postValue(Resource.Error(throwable))
}) {
val token = ServiceFactory.get(pageTitle.wikiSite).getToken().query?.csrfToken()!!
val response = ServiceFactory.get(pageTitle.wikiSite).subscribeTalkPageTopic(pageTitle.prefixedText, topicName, token, if (!subscribed) true else null)
subscribed = response.status!!.subscribe
subscribeData.postValue(Resource.Success(subscribed))
}
}
fun toggleItemExpanded(item: ThreadItem): DiffUtil.DiffResult {
val prevList = mutableListOf<ThreadItem>()
prevList.addAll(flattenedThreadItems)
item.isExpanded = !item.isExpanded
updateFlattenedThreadItems()
return getDiffResult(prevList, flattenedThreadItems)
}
fun expandOrCollapseAll(): DiffUtil.DiffResult {
val prevList = mutableListOf<ThreadItem>()
prevList.addAll(flattenedThreadItems)
val expand = Prefs.talkTopicExpandOrCollapseByDefault
topic?.allReplies?.forEach { if (it.level > 1) it.isExpanded = expand }
updateFlattenedThreadItems()
return getDiffResult(prevList, flattenedThreadItems)
}
private fun getDiffResult(prevList: List<ThreadItem>, newList: List<ThreadItem>): DiffUtil.DiffResult {
return DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return prevList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return prevList[oldItemPosition] == newList[newItemPosition]
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return prevList[oldItemPosition].id == newList[newItemPosition].id
}
})
}
fun undo(undoRevId: Long) {
viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
undoResponseData.postValue(Resource.Error(throwable))
}) {
val token = ServiceFactory.get(pageTitle.wikiSite).getToken().query?.csrfToken()!!
val response = ServiceFactory.get(pageTitle.wikiSite).postUndoEdit(title = pageTitle.prefixedText, undoRevId = undoRevId, token = token)
undoResponseData.postValue(Resource.Success(response.edit!!.editSucceeded))
}
}
fun findTopicById(id: String?): ThreadItem? {
return topic?.allReplies?.find { it.id == id }
}
private fun threadSha(threadItem: ThreadItem?): String? {
return threadItem?.let { it.name + "|" + it.allReplies.map { reply -> reply.timestamp }.maxOrNull() }
}
private fun updateFlattenedThreadItems() {
flattenedThreadItems.clear()
flattenThreadLevel(threadItems, flattenedThreadItems)
for (i in flattenedThreadItems.indices) {
flattenedThreadItems[i].isFirstTopLevel = false
flattenedThreadItems[i].isLastSibling = i > 0 && flattenedThreadItems[i].level > 1 && (if (i < flattenedThreadItems.size - 1) flattenedThreadItems[i + 1].level < flattenedThreadItems[i].level else true)
}
flattenedThreadItems.find { it.level == 1 }?.isFirstTopLevel = true
}
private fun flattenThreadLevel(list: List<ThreadItem>, flatList: MutableList<ThreadItem>) {
list.forEach {
flatList.add(it)
if (it.isExpanded) {
flattenThreadLevel(it.replies, flatList)
}
}
}
class Factory(val bundle: Bundle) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return TalkTopicViewModel(bundle) as T
}
}
}
|
apache-2.0
|
8574dc826c19e780ded38a71869fc42f
| 40.942408 | 214 | 0.672575 | 4.849274 | false | false | false | false |
AndroidX/androidx
|
window/window/src/main/java/androidx/window/layout/adapter/sidecar/SidecarCompat.kt
|
3
|
18563
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Sidecar is deprecated but we still need to support it.
@file:Suppress("DEPRECATION")
package androidx.window.layout.adapter.sidecar
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.os.IBinder
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.annotation.GuardedBy
import androidx.annotation.VisibleForTesting
import androidx.core.content.OnConfigurationChangedProvider
import androidx.core.util.Consumer
import androidx.window.core.Version
import androidx.window.core.Version.Companion.parse
import androidx.window.layout.WindowLayoutInfo
import androidx.window.layout.adapter.sidecar.ExtensionInterfaceCompat.ExtensionCallbackInterface
import androidx.window.layout.adapter.sidecar.SidecarWindowBackend.Companion.DEBUG
import androidx.window.sidecar.SidecarDeviceState
import androidx.window.sidecar.SidecarDisplayFeature
import androidx.window.sidecar.SidecarInterface
import androidx.window.sidecar.SidecarInterface.SidecarCallback
import androidx.window.sidecar.SidecarProvider
import androidx.window.sidecar.SidecarWindowLayoutInfo
import java.lang.ref.WeakReference
import java.util.WeakHashMap
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/** Extension interface compatibility wrapper for v0.1 sidecar. */
internal class SidecarCompat @VisibleForTesting constructor(
@get:VisibleForTesting
val sidecar: SidecarInterface?,
private val sidecarAdapter: SidecarAdapter
) : ExtensionInterfaceCompat {
// Map of active listeners registered with #onWindowLayoutChangeListenerAdded() and not yet
// removed by #onWindowLayoutChangeListenerRemoved().
private val windowListenerRegisteredContexts = mutableMapOf<IBinder, Activity>()
// Map of activities registered to their component callbacks so we can keep track and
// remove when the activity is unregistered
private val componentCallbackMap = mutableMapOf<Activity, Consumer<Configuration>>()
private var extensionCallback: DistinctElementCallback? = null
constructor(context: Context) : this(
getSidecarCompat(context),
SidecarAdapter()
)
override fun setExtensionCallback(extensionCallback: ExtensionCallbackInterface) {
this.extensionCallback = DistinctElementCallback(extensionCallback)
sidecar?.setSidecarCallback(
DistinctElementSidecarCallback(
sidecarAdapter,
TranslatingCallback()
)
)
}
@VisibleForTesting
fun getWindowLayoutInfo(activity: Activity): WindowLayoutInfo {
val windowToken = getActivityWindowToken(activity) ?: return WindowLayoutInfo(emptyList())
val windowLayoutInfo = sidecar?.getWindowLayoutInfo(windowToken)
return sidecarAdapter.translate(
windowLayoutInfo,
sidecar?.deviceState ?: SidecarDeviceState()
)
}
override fun onWindowLayoutChangeListenerAdded(activity: Activity) {
val windowToken = getActivityWindowToken(activity)
if (windowToken != null) {
register(windowToken, activity)
} else {
val attachAdapter = FirstAttachAdapter(this, activity)
activity.window.decorView.addOnAttachStateChangeListener(attachAdapter)
}
}
/**
* Register an [IBinder] token and an [Activity] so that the given
* [Activity] will receive updates when there is a new [WindowLayoutInfo].
* @param windowToken for the given [Activity].
* @param activity that is listening for changes of [WindowLayoutInfo]
*/
fun register(windowToken: IBinder, activity: Activity) {
windowListenerRegisteredContexts[windowToken] = activity
sidecar?.onWindowLayoutChangeListenerAdded(windowToken)
// Since SidecarDeviceState and SidecarWindowLayout are merged we trigger both
// data streams.
if (windowListenerRegisteredContexts.size == 1) {
sidecar?.onDeviceStateListenersChanged(false)
}
extensionCallback?.onWindowLayoutChanged(activity, getWindowLayoutInfo(activity))
registerConfigurationChangeListener(activity)
}
private fun registerConfigurationChangeListener(activity: Activity) {
// Only register a component callback if we haven't already as register
// may be called multiple times for the same activity
if (componentCallbackMap[activity] == null && activity is OnConfigurationChangedProvider) {
// Create a configuration change observer to send updated WindowLayoutInfo
// when the configuration of the app changes: b/186647126
val configChangeObserver = Consumer<Configuration> {
extensionCallback?.onWindowLayoutChanged(
activity,
getWindowLayoutInfo(activity)
)
}
componentCallbackMap[activity] = configChangeObserver
activity.addOnConfigurationChangedListener(configChangeObserver)
}
}
override fun onWindowLayoutChangeListenerRemoved(activity: Activity) {
val windowToken = getActivityWindowToken(activity) ?: return
sidecar?.onWindowLayoutChangeListenerRemoved(windowToken)
unregisterComponentCallback(activity)
extensionCallback?.clearWindowLayoutInfo(activity)
val isLast = windowListenerRegisteredContexts.size == 1
windowListenerRegisteredContexts.remove(windowToken)
if (isLast) {
sidecar?.onDeviceStateListenersChanged(true)
}
}
private fun unregisterComponentCallback(activity: Activity) {
val configChangeObserver = componentCallbackMap[activity] ?: return
if (activity is OnConfigurationChangedProvider) {
activity.removeOnConfigurationChangedListener(configChangeObserver)
}
componentCallbackMap.remove(activity)
}
@SuppressLint("BanUncheckedReflection")
override fun validateExtensionInterface(): Boolean {
return try {
// sidecar.setSidecarCallback(SidecarInterface.SidecarCallback);
val methodSetSidecarCallback = sidecar?.javaClass?.getMethod(
"setSidecarCallback",
SidecarCallback::class.java
)
val rSetSidecarCallback = methodSetSidecarCallback?.returnType
if (rSetSidecarCallback != Void.TYPE) {
throw NoSuchMethodException(
"Illegal return type for 'setSidecarCallback': $rSetSidecarCallback"
)
}
// DO NOT REMOVE SINCE THIS IS VALIDATING THE INTERFACE.
// sidecar.getDeviceState()
@Suppress("VARIABLE_WITH_REDUNDANT_INITIALIZER")
var tmpDeviceState = sidecar?.deviceState
// sidecar.onDeviceStateListenersChanged(boolean);
sidecar?.onDeviceStateListenersChanged(true /* isEmpty */)
// sidecar.getWindowLayoutInfo(IBinder)
val methodGetWindowLayoutInfo = sidecar?.javaClass
?.getMethod("getWindowLayoutInfo", IBinder::class.java)
val rtGetWindowLayoutInfo = methodGetWindowLayoutInfo?.returnType
if (rtGetWindowLayoutInfo != SidecarWindowLayoutInfo::class.java) {
throw NoSuchMethodException(
"Illegal return type for 'getWindowLayoutInfo': $rtGetWindowLayoutInfo"
)
}
// sidecar.onWindowLayoutChangeListenerAdded(IBinder);
val methodRegisterWindowLayoutChangeListener = sidecar?.javaClass
?.getMethod("onWindowLayoutChangeListenerAdded", IBinder::class.java)
val rtRegisterWindowLayoutChangeListener =
methodRegisterWindowLayoutChangeListener?.returnType
if (rtRegisterWindowLayoutChangeListener != Void.TYPE) {
throw NoSuchMethodException(
"Illegal return type for 'onWindowLayoutChangeListenerAdded': " +
"$rtRegisterWindowLayoutChangeListener"
)
}
// sidecar.onWindowLayoutChangeListenerRemoved(IBinder);
val methodUnregisterWindowLayoutChangeListener = sidecar?.javaClass
?.getMethod("onWindowLayoutChangeListenerRemoved", IBinder::class.java)
val rtUnregisterWindowLayoutChangeListener =
methodUnregisterWindowLayoutChangeListener?.returnType
if (rtUnregisterWindowLayoutChangeListener != Void.TYPE) {
throw NoSuchMethodException(
"Illegal return type for 'onWindowLayoutChangeListenerRemoved': " +
"$rtUnregisterWindowLayoutChangeListener"
)
}
// SidecarDeviceState constructor
tmpDeviceState = SidecarDeviceState()
// deviceState.posture
// TODO(b/172620880): Workaround for Sidecar API implementation issue.
try {
tmpDeviceState.posture = SidecarDeviceState.POSTURE_OPENED
} catch (error: NoSuchFieldError) {
if (DEBUG) {
Log.w(
TAG,
"Sidecar implementation doesn't conform to primary interface version, " +
"continue to check for the secondary one ${Version.VERSION_0_1}, " +
"error: $error"
)
}
val methodSetPosture = SidecarDeviceState::class.java.getMethod(
"setPosture",
Int::class.javaPrimitiveType
)
methodSetPosture.invoke(tmpDeviceState, SidecarDeviceState.POSTURE_OPENED)
val methodGetPosture = SidecarDeviceState::class.java.getMethod("getPosture")
val posture = methodGetPosture.invoke(tmpDeviceState) as Int
if (posture != SidecarDeviceState.POSTURE_OPENED) {
throw Exception("Invalid device posture getter/setter")
}
}
// SidecarDisplayFeature constructor
val displayFeature = SidecarDisplayFeature()
// displayFeature.getRect()/setRect()
val tmpRect = displayFeature.rect
displayFeature.rect = tmpRect
// displayFeature.getType()/setType()
@Suppress("UNUSED_VARIABLE")
val tmpType = displayFeature.type
displayFeature.type = SidecarDisplayFeature.TYPE_FOLD
// SidecarWindowLayoutInfo constructor
val windowLayoutInfo = SidecarWindowLayoutInfo()
// windowLayoutInfo.displayFeatures
try {
@Suppress("UNUSED_VARIABLE")
val tmpDisplayFeatures = windowLayoutInfo.displayFeatures
// TODO(b/172620880): Workaround for Sidecar API implementation issue.
} catch (error: NoSuchFieldError) {
if (DEBUG) {
Log.w(
TAG,
"Sidecar implementation doesn't conform to primary interface version, " +
"continue to check for the secondary one ${Version.VERSION_0_1}, " +
"error: $error"
)
}
val featureList: MutableList<SidecarDisplayFeature> = ArrayList()
featureList.add(displayFeature)
val methodSetFeatures = SidecarWindowLayoutInfo::class.java.getMethod(
"setDisplayFeatures", MutableList::class.java
)
methodSetFeatures.invoke(windowLayoutInfo, featureList)
val methodGetFeatures = SidecarWindowLayoutInfo::class.java.getMethod(
"getDisplayFeatures"
)
@Suppress("UNCHECKED_CAST")
val resultDisplayFeatures =
methodGetFeatures.invoke(windowLayoutInfo) as List<SidecarDisplayFeature>
if (featureList != resultDisplayFeatures) {
throw Exception("Invalid display feature getter/setter")
}
}
true
} catch (t: Throwable) {
if (DEBUG) {
Log.e(
TAG,
"Sidecar implementation doesn't conform to interface version " +
"${Version.VERSION_0_1}, error: $t"
)
}
false
}
}
/**
* An adapter that will run a callback when a window is attached and then be removed from the
* listener set.
*/
private class FirstAttachAdapter(
private val sidecarCompat: SidecarCompat,
activity: Activity
) : View.OnAttachStateChangeListener {
private val activityWeakReference = WeakReference(activity)
override fun onViewAttachedToWindow(view: View) {
view.removeOnAttachStateChangeListener(this)
val activity = activityWeakReference.get()
val token = getActivityWindowToken(activity)
if (activity == null) {
if (DEBUG) {
Log.d(TAG, "Unable to register activity since activity is missing")
}
return
}
if (token == null) {
if (DEBUG) {
Log.w(TAG, "Unable to register activity since the window token is missing")
}
return
}
sidecarCompat.register(token, activity)
}
override fun onViewDetachedFromWindow(view: View) {}
}
/**
* A callback to translate from Sidecar classes to local classes.
*
* If you change the name of this class, you must update the proguard file.
*/
internal inner class TranslatingCallback : SidecarCallback {
@SuppressLint("SyntheticAccessor")
override fun onDeviceStateChanged(newDeviceState: SidecarDeviceState) {
windowListenerRegisteredContexts.values.forEach { activity ->
val layoutInfo = getActivityWindowToken(activity)
?.let { windowToken -> sidecar?.getWindowLayoutInfo(windowToken) }
extensionCallback?.onWindowLayoutChanged(
activity,
sidecarAdapter.translate(layoutInfo, newDeviceState)
)
}
}
@SuppressLint("SyntheticAccessor")
override fun onWindowLayoutChanged(
windowToken: IBinder,
newLayout: SidecarWindowLayoutInfo
) {
val activity = windowListenerRegisteredContexts[windowToken]
if (activity == null) {
Log.w(
TAG,
"Unable to resolve activity from window token. Missing a call to " +
"#onWindowLayoutChangeListenerAdded()?"
)
return
}
val layoutInfo = sidecarAdapter.translate(
newLayout,
sidecar?.deviceState ?: SidecarDeviceState()
)
extensionCallback?.onWindowLayoutChanged(activity, layoutInfo)
}
}
/**
* A class to record the last calculated values from [SidecarInterface] and filter out
* duplicates. This class uses [WindowLayoutInfo] as opposed to
* [SidecarDisplayFeature] since the methods [Object.equals] and
* [Object.hashCode] may not have been overridden.
*/
private class DistinctElementCallback(
private val callbackInterface: ExtensionCallbackInterface
) : ExtensionCallbackInterface {
private val lock = ReentrantLock()
/**
* A map from [Activity] to the last computed [WindowLayoutInfo] for the
* given activity. A [WeakHashMap] is used to avoid retaining the [Activity].
*/
@GuardedBy("mLock")
private val activityWindowLayoutInfo = WeakHashMap<Activity, WindowLayoutInfo>()
override fun onWindowLayoutChanged(
activity: Activity,
newLayout: WindowLayoutInfo
) {
lock.withLock {
val lastInfo = activityWindowLayoutInfo[activity]
if (newLayout == lastInfo) {
return
}
activityWindowLayoutInfo.put(activity, newLayout)
}
callbackInterface.onWindowLayoutChanged(activity, newLayout)
}
fun clearWindowLayoutInfo(activity: Activity) {
lock.withLock {
activityWindowLayoutInfo[activity] = null
}
}
}
companion object {
private const val TAG = "SidecarCompat"
val sidecarVersion: Version?
get() = try {
val vendorVersion = SidecarProvider.getApiVersion()
if (!TextUtils.isEmpty(vendorVersion)) parse(vendorVersion) else null
} catch (e: NoClassDefFoundError) {
if (DEBUG) {
Log.d(TAG, "Sidecar version not found")
}
null
} catch (e: UnsupportedOperationException) {
if (DEBUG) {
Log.d(TAG, "Stub Sidecar")
}
null
}
internal fun getSidecarCompat(context: Context): SidecarInterface? {
return SidecarProvider.getSidecarImpl(context.applicationContext)
}
/**
* A utility method [Activity] to return an optional [IBinder] window token from an
* [Activity].
*/
internal fun getActivityWindowToken(activity: Activity?): IBinder? {
return activity?.window?.attributes?.token
}
}
}
|
apache-2.0
|
e50fb235dd24bf8704fec8b466f92e77
| 41.675862 | 99 | 0.632441 | 5.566117 | false | false | false | false |
AndroidX/androidx
|
fragment/fragment-lint/src/main/java/androidx/fragment/lint/OnCreateDialogIncorrectCallbackDetector.kt
|
3
|
6350
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UnstableApiUsage")
package androidx.fragment.lint
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.android.tools.lint.detector.api.isKotlin
import com.intellij.psi.impl.source.PsiClassReferenceType
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getSuperNames
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UElement
import org.jetbrains.uast.visitor.AbstractUastVisitor
/**
* When using a `DialogFragment`, the `setOnCancelListener` and `setOnDismissListener` callback
* functions within the `onCreateDialog` function __must not be used__
* because the `DialogFragment` owns these callbacks. Instead the respective `onCancel` and
* `onDismiss` functions can be used to achieve the desired effect.
*/
class OnCreateDialogIncorrectCallbackDetector : Detector(), SourceCodeScanner {
companion object Issues {
val ISSUE = Issue.create(
id = "DialogFragmentCallbacksDetector",
briefDescription = "Use onCancel() and onDismiss() instead of calling " +
"setOnCancelListener() and setOnDismissListener() from onCreateDialog()",
explanation = """When using a `DialogFragment`, the `setOnCancelListener` and \
`setOnDismissListener` callback functions within the `onCreateDialog` function \
__must not be used__ because the `DialogFragment` owns these callbacks. \
Instead the respective `onCancel` and `onDismiss` functions can be used to \
achieve the desired effect.""",
category = Category.CORRECTNESS,
severity = Severity.WARNING,
implementation = Implementation(
OnCreateDialogIncorrectCallbackDetector::class.java,
Scope.JAVA_FILE_SCOPE
),
androidSpecific = true
)
}
override fun getApplicableUastTypes(): List<Class<out UElement>>? {
return listOf(UClass::class.java)
}
override fun createUastHandler(context: JavaContext): UElementHandler? {
return UastHandler(context)
}
private inner class UastHandler(val context: JavaContext) : UElementHandler() {
override fun visitClass(node: UClass) {
if (isKotlin(context.psiFile) &&
(node.sourcePsi as? KtClassOrObject)?.getSuperNames()?.firstOrNull() !=
DIALOG_FRAGMENT_CLASS
) {
return
}
if (!isKotlin(context.psiFile) &&
(node.uastSuperTypes.firstOrNull()?.type as? PsiClassReferenceType)
?.className != DIALOG_FRAGMENT_CLASS
) {
return
}
node.methods.forEach {
if (it.name == ENTRY_METHOD) {
val visitor = UastMethodsVisitor(context, it.name)
it.uastBody?.accept(visitor)
}
}
}
}
/**
* A UAST Visitor that explores all method calls within a
* [androidx.fragment.app.DialogFragment] callback to check for an incorrect method call.
*
* @param context The context of the lint request.
* @param containingMethodName The name of the originating Fragment lifecycle method.
*/
private class UastMethodsVisitor(
private val context: JavaContext,
private val containingMethodName: String
) : AbstractUastVisitor() {
private val visitedMethods = mutableSetOf<UCallExpression>()
override fun visitCallExpression(node: UCallExpression): Boolean {
if (visitedMethods.contains(node)) {
return super.visitCallExpression(node)
}
val methodName = node.methodIdentifier?.name ?: return super.visitCallExpression(node)
when (methodName) {
SET_ON_CANCEL_LISTENER -> {
report(
context = context,
node = node,
message = "Use onCancel() instead of calling setOnCancelListener() " +
"from onCreateDialog()"
)
visitedMethods.add(node)
}
SET_ON_DISMISS_LISTENER -> {
report(
context = context,
node = node,
message = "Use onDismiss() instead of calling setOnDismissListener() " +
"from onCreateDialog()"
)
visitedMethods.add(node)
}
}
return super.visitCallExpression(node)
}
private fun report(context: JavaContext, node: UCallExpression, message: String) {
context.report(
issue = ISSUE,
location = context.getLocation(node),
message = message,
quickfixData = null
)
}
}
}
private const val ENTRY_METHOD = "onCreateDialog"
private const val DIALOG_FRAGMENT_CLASS = "DialogFragment"
private const val SET_ON_CANCEL_LISTENER = "setOnCancelListener"
private const val SET_ON_DISMISS_LISTENER = "setOnDismissListener"
|
apache-2.0
|
dbf723f109cca8649c91c3d4a3776f33
| 39.44586 | 98 | 0.633543 | 5.150041 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/ide/formatter/processors/RsStatementSemicolonFormatProcessor.kt
|
5
|
1852
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.formatter.processors
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiRecursiveElementVisitor
import com.intellij.psi.impl.source.codeStyle.PreFormatProcessor
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.SEMICOLON
import org.rust.lang.core.psi.ext.elementType
import org.rust.lang.core.psi.ext.getNextNonCommentSibling
class RsStatementSemicolonFormatProcessor : PreFormatProcessor {
override fun process(node: ASTNode, range: TextRange): TextRange {
if (!shouldRunPunctuationProcessor(node)) return range
val elements = arrayListOf<PsiElement>()
node.psi.accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element.textRange in range) {
super.visitElement(element)
}
// no semicolons inside "match"
if (element.parent !is RsMatchArm) {
if (element is RsRetExpr || element is RsBreakExpr || element is RsContExpr) {
elements.add(element)
}
}
}
})
return range.grown(elements.count(::tryAddSemicolonAfter))
}
private fun tryAddSemicolonAfter(element: PsiElement): Boolean {
val nextSibling = element.getNextNonCommentSibling()
if (nextSibling == null || nextSibling.elementType != SEMICOLON) {
val psiFactory = RsPsiFactory(element.project)
element.parent.addAfter(psiFactory.createSemicolon(), element)
return true
}
return false
}
}
|
mit
|
5c944cacf09b65c6d14e67b737365b86
| 34.615385 | 98 | 0.661987 | 4.78553 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/ide/inspections/RsVariableMutableInspection.kt
|
3
|
2420
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.rust.ide.inspections.fixes.RemoveMutableFix
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.lang.core.psi.ext.descendantsOfType
import org.rust.lang.core.psi.ext.mutability
import org.rust.lang.core.psi.ext.selfParameter
class RsVariableMutableInspection : RsLocalInspectionTool() {
override fun getDisplayName(): String = "No mutable required"
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor =
object : RsVisitor() {
override fun visitPatBinding(o: RsPatBinding) {
if (!o.mutability.isMut) return
val block = o.ancestorStrict<RsBlock>() ?: o.ancestorStrict<RsFunction>() ?: return
if (ReferencesSearch.search(o, LocalSearchScope(block))
.any { checkOccurrenceNeedMutable(it.element.parent) }) return
if (block.descendantsOfType<RsMacroCall>().any { checkExprPosition(o, it) }) return
holder.registerProblem(
o,
"Variable `${o.identifier.text}` does not need to be mutable",
RemoveMutableFix()
)
}
}
fun checkExprPosition(o: RsPatBinding, expr: RsMacroCall): Boolean = o.textOffset < expr.textOffset
fun checkOccurrenceNeedMutable(occurrence: PsiElement): Boolean {
when (val parent = occurrence.parent) {
is RsUnaryExpr -> return parent.isMutable || parent.mul != null
is RsBinaryExpr -> return parent.left == occurrence
is RsMethodCall -> {
val ref = parent.reference.resolve() as? RsFunction ?: return true
val self = ref.selfParameter ?: return true
return self.mutability.isMut
}
is RsTupleExpr -> {
val expr = parent.parent as? RsUnaryExpr ?: return true
return expr.isMutable
}
is RsValueArgumentList -> return false
}
return true
}
private val RsUnaryExpr.isMutable: Boolean get() = mut != null
}
|
mit
|
c69d3f4318490dc36814f0ba8894028d
| 40.724138 | 103 | 0.640083 | 4.859438 | false | false | false | false |
glung/DroidconFr
|
CounterCycle/app/src/main/java/com/glung/github/counter/cycle/Counter.kt
|
1
|
1249
|
package com.glung.github.counter.cycle
import android.content.Context
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import org.jetbrains.anko.button
import org.jetbrains.anko.sp
import org.jetbrains.anko.textView
import org.jetbrains.anko.verticalLayout
import rx.Observable
val UP = 0
val DOWN = 1
fun main(context: Context, select: (Int) -> ActivityIO): Observable<View> =
Observable
// INTENT
.merge(
select(UP).clickEvents().map { it -> +1 },
select(DOWN).clickEvents().map { it -> -1 }
)
// MODEL
.startWith(0)
.scan({ x, y -> x + y })
// VIEW
.map({ x -> view(context, x) })
fun view(context: Context, counter: Int): LinearLayout {
with(context) {
return verticalLayout {
button(getString(R.string.up)) {
id = UP
}
button(getString(R.string.down)) {
id = DOWN
}
textView(counter.toString()) {
textSize = sp(24).toFloat()
gravity = Gravity.CENTER
}
}
}
}
|
mit
|
e411fe3b78a75cbe2f60efdc711e136c
| 27.409091 | 75 | 0.522018 | 4.367133 | false | false | false | false |
charleskorn/batect
|
app/src/main/kotlin/batect/config/io/deserializers/PrerequisiteListSerializer.kt
|
1
|
3412
|
/*
Copyright 2017-2020 Charles Korn.
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 batect.config.io.deserializers
import batect.config.io.ConfigurationException
import com.charleskorn.kaml.YamlInput
import kotlinx.serialization.CompositeDecoder
import kotlinx.serialization.CompositeDecoder.Companion.READ_ALL
import kotlinx.serialization.CompositeDecoder.Companion.READ_DONE
import kotlinx.serialization.Decoder
import kotlinx.serialization.Encoder
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialDescriptor
import kotlinx.serialization.Serializer
import kotlinx.serialization.internal.ArrayListClassDesc
import kotlinx.serialization.internal.StringSerializer
import kotlinx.serialization.list
@Serializer(forClass = List::class)
internal object PrerequisiteListSerializer : KSerializer<List<String>> {
val elementSerializer = StringSerializer
override val descriptor: SerialDescriptor = ArrayListClassDesc(elementSerializer.descriptor)
override fun deserialize(decoder: Decoder): List<String> {
val input = decoder.beginStructure(descriptor, elementSerializer)
val result = read(input)
input.endStructure(descriptor)
return result
}
private fun read(input: CompositeDecoder): List<String> {
val size = input.decodeCollectionSize(descriptor)
while (true) {
when (val index = input.decodeElementIndex(descriptor)) {
READ_ALL -> return readAll(input, size)
else -> return readUntilDone(input, index)
}
}
}
private fun readAll(input: CompositeDecoder, size: Int): List<String> {
val soFar = mutableListOf<String>()
for (currentIndex in 0..size) {
soFar.add(readSingle(input, currentIndex, soFar))
}
return soFar
}
private fun readUntilDone(input: CompositeDecoder, firstIndex: Int): List<String> {
var currentIndex = firstIndex
val soFar = mutableListOf<String>()
while (currentIndex != READ_DONE) {
soFar.add(currentIndex, readSingle(input, currentIndex, soFar))
currentIndex = input.decodeElementIndex(descriptor)
}
return soFar
}
private fun readSingle(input: CompositeDecoder, index: Int, soFar: List<String>): String {
val value = input.decodeSerializableElement(descriptor, index, elementSerializer)
if (value in soFar) {
val location = (input as YamlInput).getCurrentLocation()
throw ConfigurationException(getDuplicateValueMessage(value), location.line, location.column)
}
return value
}
private fun getDuplicateValueMessage(value: String) = "The prerequisite '$value' is given more than once"
override fun serialize(encoder: Encoder, obj: List<String>) = StringSerializer.list.serialize(encoder, obj)
}
|
apache-2.0
|
5c1217f4ceed49bc9e1dcbe8373da4c4
| 34.175258 | 111 | 0.721571 | 4.832861 | false | false | false | false |
nrizzio/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/info/StoryInfoRecipientRow.kt
|
1
|
2146
|
package org.thoughtcrime.securesms.stories.viewer.info
import android.view.View
import android.widget.TextView
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.AvatarImageView
import org.thoughtcrime.securesms.messagedetails.RecipientDeliveryStatus
import org.thoughtcrime.securesms.util.DateUtils
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
import java.util.Locale
/**
* Holds information needed to render a single recipient row in the info sheet.
*/
object StoryInfoRecipientRow {
fun register(mappingAdapter: MappingAdapter) {
mappingAdapter.registerFactory(Model::class.java, LayoutFactory(::ViewHolder, R.layout.story_info_recipient_row))
}
class Model(
val recipientDeliveryStatus: RecipientDeliveryStatus
) : MappingModel<Model> {
override fun areItemsTheSame(newItem: Model): Boolean {
return recipientDeliveryStatus.recipient.id == newItem.recipientDeliveryStatus.recipient.id
}
override fun areContentsTheSame(newItem: Model): Boolean {
return recipientDeliveryStatus.recipient.hasSameContent(newItem.recipientDeliveryStatus.recipient) &&
recipientDeliveryStatus.timestamp == newItem.recipientDeliveryStatus.timestamp
}
}
private class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) {
private val avatarView: AvatarImageView = itemView.findViewById(R.id.story_info_avatar)
private val nameView: TextView = itemView.findViewById(R.id.story_info_display_name)
private val timestampView: TextView = itemView.findViewById(R.id.story_info_timestamp)
override fun bind(model: Model) {
avatarView.setRecipient(model.recipientDeliveryStatus.recipient)
nameView.text = model.recipientDeliveryStatus.recipient.getDisplayName(context)
timestampView.text = DateUtils.getTimeString(context, Locale.getDefault(), model.recipientDeliveryStatus.timestamp)
}
}
}
|
gpl-3.0
|
ceb7b57c15189424d303c3b3c269654c
| 43.708333 | 121 | 0.804287 | 4.536998 | false | false | false | false |
androidx/androidx
|
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/RadioButton.kt
|
3
|
6754
|
/*
* 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.glance.appwidget
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.glance.Emittable
import androidx.glance.GlanceModifier
import androidx.glance.GlanceNode
import androidx.glance.GlanceTheme
import androidx.glance.action.Action
import androidx.glance.action.clickable
import androidx.glance.appwidget.unit.CheckableColorProvider
import androidx.glance.appwidget.unit.CheckedUncheckedColorProvider.Companion.createCheckableColorProvider
import androidx.glance.appwidget.unit.ResourceCheckableColorProvider
import androidx.glance.color.DynamicThemeColorProviders
import androidx.glance.text.TextStyle
import androidx.glance.unit.ColorProvider
import androidx.glance.unit.FixedColorProvider
/** Set of colors to apply to a RadioButton depending on the checked state. */
class RadioButtonColors internal constructor(internal val radio: CheckableColorProvider)
/**
* RadioButtonColors to tint the drawable of the [RadioButton] according to the checked state.
*
* None of the [ColorProvider] parameters to this function can be created from resource ids. To use
* resources to tint the switch color, use `RadioButtonColors(Int, Int)` instead.
*
* @param checkedColor the tint to apply to the radio button when it is checked, or null
* to use the default tint.
* @param uncheckedColor the tint to apply to the radio button when it is not checked,
* or null to use the default tint.
*/
fun radioButtonColors(
checkedColor: ColorProvider,
uncheckedColor: ColorProvider,
): RadioButtonColors {
return RadioButtonColors(
radio = createCheckableColorProvider(
source = "RadioButtonColors", checked = checkedColor, unchecked = uncheckedColor
)
)
}
/**
* [radioButtonColors] that uses [checkedColor] or [uncheckedColor] depending on the checked state
* of the RadioButton.
*
* @param checkedColor the [Color] to use when the RadioButton is checked
* @param uncheckedColor the [Color] to use when the RadioButton is not checked
*/
fun radioButtonColors(checkedColor: Color, uncheckedColor: Color): RadioButtonColors =
radioButtonColors(FixedColorProvider(checkedColor), FixedColorProvider(uncheckedColor))
@Composable
fun radioButtonColors(): RadioButtonColors {
val colorProvider = if (GlanceTheme.colors == DynamicThemeColorProviders) {
// If using the m3 dynamic color theme, we need to create a color provider from xml
// because resource backed ColorStateLists cannot be created programmatically
ResourceCheckableColorProvider(R.color.glance_default_radio_button)
} else {
createCheckableColorProvider(
source = "CheckBoxColors",
checked = GlanceTheme.colors.primary,
unchecked = GlanceTheme.colors.onSurfaceVariant
)
}
return RadioButtonColors(colorProvider)
}
internal class EmittableRadioButton(
var colors: RadioButtonColors
) : Emittable {
override var modifier: GlanceModifier = GlanceModifier
var checked: Boolean = false
var enabled: Boolean = true
var text: String = ""
var style: TextStyle? = null
var maxLines: Int = Int.MAX_VALUE
override fun copy(): Emittable = EmittableRadioButton(colors = colors).also {
it.modifier = modifier
it.checked = checked
it.enabled = enabled
it.text = text
it.style = style
it.maxLines = maxLines
}
override fun toString(): String = "EmittableRadioButton(" +
"$text, " +
"modifier=$modifier, " +
"checked=$checked, " +
"enabled=$enabled, " +
"text=$text, " +
"style=$style, " +
"colors=$colors, " +
"maxLines=$maxLines, " +
")"
}
/**
* Adds a radio button to the glance view.
*
* When showing a [Row] or [Column] that has [RadioButton] children, use
* [GlanceModifier.selectableGroup] to enable the radio group effect (unselecting the previously
* selected radio button when another is selected).
*
* @param checked whether the radio button is checked
* @param onClick the action to be run when the radio button is clicked
* @param modifier the modifier to apply to the radio button
* @param enabled if false, the radio button will not be clickable
* @param text the text to display to the end of the radio button
* @param style the style to apply to [text]
* @param colors the color tint to apply to the radio button
* @param maxLines An optional maximum number of lines for the text to span, wrapping if
* necessary. If the text exceeds the given number of lines, it will be truncated.
*/
@Composable
fun RadioButton(
checked: Boolean,
onClick: Action?,
modifier: GlanceModifier = GlanceModifier,
enabled: Boolean = true,
text: String = "",
style: TextStyle? = null,
colors: RadioButtonColors = radioButtonColors(),
maxLines: Int = Int.MAX_VALUE,
) {
val finalModifier = if (enabled && onClick != null) modifier.clickable(onClick) else modifier
GlanceNode(factory = { EmittableRadioButton(colors) }, update = {
this.set(checked) { this.checked = it }
this.set(finalModifier) { this.modifier = it }
this.set(enabled) { this.enabled = it }
this.set(text) { this.text = it }
this.set(style) { this.style = it }
this.set(colors) { this.colors = it }
this.set(maxLines) { this.maxLines = it }
})
}
/**
* Use this modifier to group a list of RadioButtons together for accessibility purposes.
*
* This modifier can only be used on a [Row] or [Column]. This modifier additonally enables
* the radio group effect, which automatically unselects the currently selected RadioButton when
* another is selected. When this modifier is used, an error will be thrown if more than one
* RadioButton has their "checked" value set to true.
*/
fun GlanceModifier.selectableGroup(): GlanceModifier = this.then(SelectableGroupModifier)
internal object SelectableGroupModifier : GlanceModifier.Element
internal val GlanceModifier.isSelectableGroup: Boolean
get() = any { it is SelectableGroupModifier }
|
apache-2.0
|
93319d58569f2e5a250f08e6da89c71d
| 38.497076 | 106 | 0.727569 | 4.47878 | false | false | false | false |
cqjjjzr/Laplacian
|
Laplacian.Essential/src/main/kotlin/charlie/laplacian/track/grouping/essential/Album.kt
|
1
|
1013
|
package charlie.laplacian.track.grouping.essential
import charlie.laplacian.I18n
import charlie.laplacian.track.Track
import charlie.laplacian.track.grouping.TrackGroupingMethod
import charlie.laplacian.track.property.Property
import java.util.*
class Album: TrackGroupingMethod {
private val tracks: MutableList<Track> = LinkedList()
private val properties: MutableList<Property> = LinkedList()
override fun getName(): String = I18n.getString("grouping.album.name")
override fun getTracks(): List<Track> = Collections.unmodifiableList(tracks)
override fun getProperties(): List<Property> = Collections.unmodifiableList(properties)
override fun addTrack(track: Track) {
if (tracks.find { it == track } != null)
throw IllegalArgumentException("duplicate track")
tracks += track
}
override fun removeTrack(track: Track) {
tracks -= track
}
override fun canDuplicate(): Boolean = false
override fun count(): Int = tracks.size
}
|
apache-2.0
|
7244256ce2b7c1d6d70bb5ac7eb5dd1a
| 30.6875 | 91 | 0.726555 | 4.604545 | false | false | false | false |
google/android-auto-companion-android
|
trustagent/src/com/google/android/libraries/car/trustagent/AssociatedCarManager.kt
|
1
|
6525
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.trustagent
import android.content.Context
import com.google.android.libraries.car.trustagent.storage.CryptoHelper
import com.google.android.libraries.car.trustagent.storage.KeyStoreCryptoHelper
import com.google.android.libraries.car.trustagent.util.logw
import java.util.UUID
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
/**
* Manages the cars for which this device has been associated with.
*
* @property connectedCarDatabase The database to write and read car association info from.
* @property coroutineContext The context with which to access the database. Should be a background
* dispatcher.
* @property cryptoHelper The class responsible for encrypting the encryption keys of cars before
* storing into the database.
*/
internal class AssociatedCarManager
internal constructor(
context: Context,
connectedCarDatabase: ConnectedCarDatabase = DatabaseProvider.getInstance(context).database,
private val cryptoHelper: CryptoHelper = KeyStoreCryptoHelper()
) {
private val keyGenerator =
KeyGenerator.getInstance(IDENTIFICATION_KEY_ALGORITHM).apply {
init(IDENTIFICATION_KEY_SIZE_BITS)
}
private val database = connectedCarDatabase.associatedCarDao()
/** Returns `true` if this device is associated with at least one car. */
suspend fun loadIsAssociated(): Boolean = database.loadIsAssociated()
/** Returns `true` if a car with the given [deviceId] is associated with this phone. */
suspend fun loadIsAssociated(deviceId: UUID): Boolean =
database.loadIsAssociatedByCarId(deviceId.toString())
/** Returns `true` if a car with the given [macAddress] is associated with this phone. */
suspend fun loadIsAssociated(macAddress: String): Boolean =
database.loadIsAssociatedByMacAddress(macAddress)
/** Returns the cars that this device has been associated with. */
suspend fun retrieveAssociatedCars(): List<AssociatedCar> =
database.loadAllAssociatedCars().map {
AssociatedCar(
UUID.fromString(it.id),
it.name,
it.macAddress,
it.identificationKey.toSecretKey()
)
}
/** Stores a [Car] as an associated device and returns `true` if the operation succeeded. */
suspend fun add(car: Car): Boolean {
val key = car.messageStream.encryptionKey
if (key == null) {
return false
}
val encryptedKey = cryptoHelper.encrypt(key.asBytes()) ?: return false
val entity =
AssociatedCarEntity(
car.deviceId.toString(),
encryptedKey,
car.identificationKey.toEncryptedString(),
car.name,
car.bluetoothDevice.address,
isUserRenamed = false
)
database.insertAssociatedCar(entity)
return true
}
/**
* Removes a car from the stored associated car list and returns `true` if the operation
* succeeded.
*/
suspend fun clear(deviceId: UUID): Boolean {
return database.deleteAssociatedCar(deviceId.toString()) > 0
}
/** Removes all stored associated cars and returns `true` if the operation succeeded. */
suspend fun clearAll(): Boolean {
return database.deleteAllAssociatedCars() > 0
}
/**
* Updates any stored encryption key for the given [car] to match the new key that is present in
* the [car] and returns `true` if the operation succeeded.
*/
suspend fun updateEncryptionKey(car: Car): Boolean {
val key = car.messageStream.encryptionKey
if (key == null) {
return false
}
val encryptedKey = cryptoHelper.encrypt(key.asBytes()) ?: return false
val entity = AssociatedCarKey(car.deviceId.toString(), encryptedKey)
return database.updateEncryptionKey(entity) > 0
}
/**
* Returns the encryption key for the car with the given [deviceId] or `null` if that car is not
* currently associated with this phone.
*/
suspend fun loadEncryptionKey(deviceId: UUID): ByteArray? =
database.loadEncryptionKey(deviceId.toString())?.let { cryptoHelper.decrypt(it.encryptionKey) }
/** Returns the mac address of the associated car with id [deviceId]. */
suspend fun loadMacAddress(deviceId: UUID): String =
database.loadMacAddressByCarId(deviceId.toString())
/** Returns the name of the associated car with id [deviceId]. */
suspend fun loadName(deviceId: UUID): String = database.loadNameByCarId(deviceId.toString())
/**
* Renames a car with the given [deviceId] to the specified [name] and returns `true` if the
* operation succeeded.
*
* The given name should be non-empty, or this call will do nothing.
*/
suspend fun rename(deviceId: UUID, name: String): Boolean {
if (name.isEmpty()) {
logw(TAG, "Rename called with an empty car name. Ignoring.")
return false
}
val entity = AssociatedCarName(deviceId.toString(), name, isUserRenamed = true)
return database.updateName(entity) > 0
}
/** Generates a [SecretKey]. */
fun generateKey(): SecretKey = keyGenerator.generateKey()
/**
* Converts [this] String to a SecretKey.
*
* This String must be an encrypted value of a SecretKey. See [toEncryptedString].
*/
private fun String.toSecretKey(): SecretKey =
SecretKeySpec(cryptoHelper.decrypt(this), AssociatedCarManager.IDENTIFICATION_KEY_ALGORITHM)
/**
* Encrypts [this] SecretKey to a String.
*
* The reverse can be done by [String.toSecretKey].
*/
private fun SecretKey.toEncryptedString(): String {
val encrypted = cryptoHelper.encrypt(encoded)
if (encrypted == null) {
// TODO(b/155932001): CryptoHelper should not be able to return null.
throw IllegalStateException("Could not encrypt secret key.")
}
return encrypted
}
companion object {
private const val TAG = "AssociatedCarManager"
private const val IDENTIFICATION_KEY_SIZE_BITS = 256
internal const val IDENTIFICATION_KEY_ALGORITHM = "HmacSHA256"
}
}
|
apache-2.0
|
507e3250f0b661c031ec5b6fd6c223d9
| 35.452514 | 99 | 0.721379 | 4.382136 | false | false | false | false |
andstatus/andstatus
|
app/src/main/kotlin/org/andstatus/app/activity/TimelineDataNoteWrapper.kt
|
1
|
1639
|
/*
* Copyright (c) 2017 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.activity
import org.andstatus.app.note.NoteViewItem
import org.andstatus.app.timeline.TimelineData
internal class TimelineDataNoteWrapper(listData: TimelineData<ActivityViewItem>) : TimelineDataWrapper<NoteViewItem>(listData) {
override fun getItem(position: Int): NoteViewItem {
return listData.getItem(position).noteViewItem
}
override fun getPositionById(itemId: Long): Int {
val position = -1
if (itemId != 0L) {
for (ind in 0 until listData.size()) {
val item = listData.getItem(ind)
if (item.noteViewItem.getId() == itemId) {
return position
} else if (item.isCollapsed) {
for (child in item.getChildren()) {
if (child.noteViewItem.getId() == itemId) {
return position
}
}
}
}
}
return -1
}
}
|
apache-2.0
|
0e5617435c218e1fc7d7dad907f87e06
| 36.25 | 128 | 0.61928 | 4.591036 | false | false | false | false |
Notifique/Notifique
|
notifique/src/main/java/com/nathanrassi/notifique/AdaptingPagingSource.kt
|
1
|
2124
|
package com.nathanrassi.notifique
import androidx.paging.PagingSource
import androidx.paging.PagingState
internal class AdaptingPagingSourceFactory<OriginalValue : Any, AdaptedValue : Any>(
private val delegate: () -> PagingSource<Int, OriginalValue>,
private val adapter: (OriginalValue) -> AdaptedValue
) : () -> PagingSource<Int, AdaptedValue> {
override fun invoke(): PagingSource<Int, AdaptedValue> {
return AdaptingPagingSource(delegate(), adapter)
}
}
private class AdaptingPagingSource<OriginalValue : Any, AdaptedValue : Any>(
private val delegate: PagingSource<Int, OriginalValue>,
private val adapter: (OriginalValue) -> AdaptedValue
) : PagingSource<Int, AdaptedValue>() {
init {
// When the delegate source invalidates itself, we need to invalidate this source.
delegate.registerInvalidatedCallback(::invalidate)
// This will not be recursive
// because the invalidate callbacks are not called on an invalidated source.
// The source keeps the invalid flag for us.
registerInvalidatedCallback(delegate::invalidate)
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, AdaptedValue> {
return when (val result = delegate.load(params)) {
is LoadResult.Page<Int, OriginalValue> -> {
val items = result.data
val adaptedItems = ArrayList<AdaptedValue>(items.size)
for (i in items.indices) {
val item = items[i]
adaptedItems += adapter(item)
}
LoadResult.Page(
adaptedItems,
result.prevKey,
result.nextKey,
result.itemsBefore,
result.itemsAfter
)
}
is LoadResult.Error -> {
LoadResult.Error(result.throwable)
}
}
}
override fun getRefreshKey(state: PagingState<Int, AdaptedValue>): Int? {
// This could delegate if we had an adapter backwards, but the abstraction isn't worth it here.
return state.anchorPosition
}
override val jumpingSupported: Boolean
get() = delegate.jumpingSupported
override val keyReuseSupported: Boolean
get() = delegate.keyReuseSupported
}
|
apache-2.0
|
90afbba2c5f3717fbf09736e02233b9b
| 33.836066 | 99 | 0.698682 | 4.45283 | false | false | false | false |
MaTriXy/android-topeka
|
app/src/main/java/com/google/samples/apps/topeka/fragment/SignInFragment.kt
|
1
|
9391
|
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.fragment
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.app.Fragment
import android.support.v4.util.Pair
import android.support.v4.view.ViewCompat
import android.support.v4.view.animation.FastOutSlowInInterpolator
import android.text.Editable
import android.text.TextWatcher
import android.transition.Transition
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.EditText
import android.widget.GridView
import com.google.samples.apps.topeka.R
import com.google.samples.apps.topeka.activity.CategorySelectionActivity
import com.google.samples.apps.topeka.adapter.AvatarAdapter
import com.google.samples.apps.topeka.helper.ApiLevelHelper
import com.google.samples.apps.topeka.helper.TransitionHelper
import com.google.samples.apps.topeka.helper.getPlayer
import com.google.samples.apps.topeka.helper.onLayoutChange
import com.google.samples.apps.topeka.helper.savePlayer
import com.google.samples.apps.topeka.model.Avatar
import com.google.samples.apps.topeka.model.Player
import com.google.samples.apps.topeka.widget.TextWatcherAdapter
import com.google.samples.apps.topeka.widget.TransitionListenerAdapter
/**
* Enable selection of an [Avatar] and user name.
*/
class SignInFragment : Fragment() {
private var firstNameView: EditText? = null
private var lastInitialView: EditText? = null
private var doneFab: FloatingActionButton? = null
private var avatarGrid: GridView? = null
private var edit: Boolean = false
private var selectedAvatarView: View? = null
private lateinit var player: Player
private var selectedAvatar: Avatar? = null
override fun onCreate(savedInstanceState: Bundle?) {
if (savedInstanceState != null) {
val avatarIndex = savedInstanceState.getInt(KEY_SELECTED_AVATAR_INDEX)
if (avatarIndex != GridView.INVALID_POSITION) {
selectedAvatar = Avatar.values()[avatarIndex]
}
}
super.onCreate(savedInstanceState)
}
override fun onAttach(context: Context?) {
super.onAttach(context)
player = activity.getPlayer()
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val contentView = inflater.inflate(R.layout.fragment_sign_in, container, false)
contentView.onLayoutChange {
avatarGrid?.apply {
adapter = AvatarAdapter(activity)
onItemClickListener = AdapterView.OnItemClickListener {
_, view, position, _ ->
selectedAvatarView = view
selectedAvatar = Avatar.values()[position]
// showing the floating action button if input data is valid
if (isInputDataValid()) doneFab?.show()
}
numColumns = calculateSpanCount()
selectedAvatar?.let { setItemChecked(it.ordinal, true) }
}
}
return contentView
}
/**
* Calculates spans for avatars dynamically.
* @return The recommended amount of columns.
*/
private fun calculateSpanCount(): Int {
val avatarSize = resources.getDimensionPixelSize(R.dimen.size_fab)
val avatarPadding = resources.getDimensionPixelSize(R.dimen.spacing_double)
return (avatarGrid?.width ?: 0) / (avatarSize + avatarPadding)
}
override fun onSaveInstanceState(outState: Bundle?) {
outState?.putInt(KEY_SELECTED_AVATAR_INDEX, (avatarGrid?.checkedItemPosition ?: 0))
super.onSaveInstanceState(outState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
firstNameView = view.findViewById<EditText>(R.id.first_name)
lastInitialView = view.findViewById<EditText>(R.id.last_initial)
doneFab = view.findViewById<FloatingActionButton>(R.id.done)
avatarGrid = view.findViewById<GridView>(R.id.avatars)
checkIsInEditMode()
if (edit || !player.valid()) {
view.findViewById<View>(R.id.empty).visibility = View.GONE
view.findViewById<View>(R.id.content).visibility = View.VISIBLE
initContentViews()
initContents()
} else {
CategorySelectionActivity.start(activity, player)
activity.finish()
}
super.onViewCreated(view, savedInstanceState)
}
private fun checkIsInEditMode() {
if (arguments == null) {
edit = false
} else {
edit = arguments.getBoolean(ARG_EDIT, false)
}
}
@SuppressLint("NewApi")
private fun initContentViews() {
val textWatcher = object : TextWatcher by TextWatcherAdapter {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
// hiding the floating action button if text is empty
if (s.isEmpty()) {
doneFab?.hide()
}
}
// showing the floating action button if avatar is selected and input data is valid
override fun afterTextChanged(s: Editable) {
if (isAvatarSelected() && isInputDataValid()) doneFab?.show()
}
}
firstNameView?.addTextChangedListener(textWatcher)
lastInitialView?.addTextChangedListener(textWatcher)
doneFab?.setOnClickListener {
if (it.id == R.id.done) {
player = Player(firstName = firstNameView?.text?.toString(),
lastInitial = lastInitialView?.text?.toString(),
avatar = selectedAvatar)
activity.savePlayer(player)
removeDoneFab(Runnable {
performSignInWithTransition(selectedAvatarView ?:
avatarGrid?.getChildAt(selectedAvatar!!.ordinal))
})
} else throw UnsupportedOperationException(
"The onClick method has not been implemented for ${resources
.getResourceEntryName(it.id)}")
}
}
private fun removeDoneFab(endAction: Runnable) {
ViewCompat.animate(doneFab)
.scaleX(0f)
.scaleY(0f)
.setInterpolator(FastOutSlowInInterpolator())
.withEndAction(endAction)
.start()
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun performSignInWithTransition(v: View?) {
if (v == null || ApiLevelHelper.isLowerThan(Build.VERSION_CODES.LOLLIPOP)) {
// Don't run a transition if the passed view is null
with(activity) {
CategorySelectionActivity.start(this, player)
finish()
}
return
}
if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {
activity.window.sharedElementExitTransition.addListener(object :
Transition.TransitionListener by TransitionListenerAdapter {
override fun onTransitionEnd(transition: Transition) = activity.finish()
})
val pairs = TransitionHelper.createSafeTransitionParticipants(activity, true,
Pair(v, activity.getString(R.string.transition_avatar)))
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, *pairs)
CategorySelectionActivity.start(activity, player, options)
}
}
private fun initContents() {
with(player) {
valid().let {
firstNameView?.setText(firstName)
lastInitialView?.setText(lastInitial)
selectedAvatar = avatar
}
}
}
private fun isAvatarSelected() = selectedAvatarView != null || selectedAvatar != null
private fun isInputDataValid() =
firstNameView?.text?.isNotEmpty() == true &&
lastInitialView?.text?.isNotEmpty() == true
companion object {
private const val ARG_EDIT = "EDIT"
private const val KEY_SELECTED_AVATAR_INDEX = "selectedAvatarIndex"
fun newInstance(edit: Boolean = false): SignInFragment {
return SignInFragment().apply {
arguments = Bundle().apply {
putBoolean(ARG_EDIT, edit)
}
}
}
}
}
|
apache-2.0
|
ba5aad6e466d58b4172f9dcb7063480f
| 37.174797 | 95 | 0.645299 | 4.963531 | false | false | false | false |
develar/mapsforge-tile-server
|
server/src/TileHttpRequestHandler.kt
|
1
|
7957
|
package org.develar.mapsforgeTileServer
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache
import com.google.common.cache.Weigher
import com.google.common.util.concurrent.UncheckedExecutionException
import com.luciad.imageio.webp.WebP
import com.luciad.imageio.webp.WebPWriteParam
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelFutureListener
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.codec.http.*
import io.netty.util.concurrent.FastThreadLocal
import org.develar.mapsforgeTileServer.http.*
import org.mapsforge.core.model.Tile
import org.mapsforge.map.layer.renderer.DatabaseRenderer
import org.mapsforge.map.layer.renderer.RendererJob
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.Locale
import java.util.regex.Pattern
import javax.imageio.ImageIO
class TileNotFound() : RuntimeException() {
companion object {
val INSTANCE = TileNotFound()
}
}
private val WRITE_PARAM = WebPWriteParam(Locale.ENGLISH)
// http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
private val MAP_TILE_NAME_PATTERN = Pattern.compile("^/(\\d+)/(\\d+)/(\\d+)(?:\\.(png|webp|v))?(?:\\?theme=(\\w+))?")
private fun checkClientCache(request:HttpRequest, lastModified:Long, etag:String):Boolean {
return checkCache(request, lastModified) || etag == request.headers().get(HttpHeaderNames.IF_NONE_MATCH)
}
private fun encodePng(bufferedImage:BufferedImage):ByteArray {
val bytes:ByteArray
val out = ByteArrayOutputStream(8 * 1024)
ImageIO.write(bufferedImage, "png", out)
bytes = out.toByteArray()
out.close()
return bytes
}
ChannelHandler.Sharable
class TileHttpRequestHandler(private val tileServer:MapsforgeTileServer, fileCacheManager:FileCacheManager?, executorCount:Int, maxMemoryCacheSize:Long, shutdownHooks:MutableList<() -> Unit>) : SimpleChannelInboundHandler<FullHttpRequest>() {
private val tileCache:LoadingCache<TileRequest, RenderedTile>
private val threadLocalRenderer = object : FastThreadLocal<Renderer>() {
override fun initialValue():Renderer {
return Renderer(tileServer)
}
}
private val tileCacheInfoProvider:DatabaseRenderer.TileCacheInfoProvider
init {
val cacheBuilder = CacheBuilder.newBuilder()
.concurrencyLevel(executorCount)
.weigher(object : Weigher<TileRequest, RenderedTile> {
override fun weigh(key:TileRequest, value:RenderedTile):Int = TILE_REQUEST_WEIGHT + value.computeWeight()
})
.maximumWeight(maxMemoryCacheSize)
if (fileCacheManager == null) {
tileCache = cacheBuilder.build(object : CacheLoader<TileRequest, RenderedTile>() {
override fun load(tile:TileRequest):RenderedTile {
return renderTile(tile)
}
})
}
else {
tileCache = fileCacheManager.configureMemoryCache(cacheBuilder).build(object : CacheLoader<TileRequest, RenderedTile>() {
override fun load(tile:TileRequest):RenderedTile {
val renderedTile = fileCacheManager.get(tile)
return renderedTile ?: renderTile(tile)
}
})
shutdownHooks.add {
LOG.info("Flush unwritten data");
fileCacheManager.close(tileCache.asMap());
}
}
tileCacheInfoProvider = object : DatabaseRenderer.TileCacheInfoProvider {
override fun contains(tile:Tile, rendererJob:RendererJob?):Boolean = tileCache.asMap().containsKey(tile as TileRequest)
}
}
override fun exceptionCaught(context:ChannelHandlerContext, cause:Throwable) {
if (cause is IOException && cause.getMessage()?.endsWith("Connection reset by peer") ?: false) {
// ignore Connection reset by peer
return
}
LOG.error(cause.getMessage(), cause)
}
override fun channelRead0(context:ChannelHandlerContext, request:FullHttpRequest) {
val uri = request.uri()
val matcher = MAP_TILE_NAME_PATTERN.matcher(uri)
val channel = context.channel()
if (!matcher.find()) {
val file = tileServer.renderThemeManager.requestToFile(uri, request)
if (file != null) {
sendFile(request, channel, file)
return
}
sendStatus(HttpResponseStatus.NOT_FOUND, channel, request)
return
}
val zoom = java.lang.Byte.parseByte(matcher.group(1)!!)
val x = Integer.parseUnsignedInt(matcher.group(2))
val y = Integer.parseUnsignedInt(matcher.group(3))
val maxTileNumber = Tile.getMaxTileNumber(zoom)
if (x > maxTileNumber || y > maxTileNumber) {
send(response(HttpResponseStatus.BAD_REQUEST), channel, request)
return
}
var imageFormat = imageFormat(matcher.group(4))
val useVaryAccept = imageFormat == null
if (useVaryAccept) {
imageFormat = if (isWebpSupported(request)) ImageFormat.WEBP else ImageFormat.PNG
}
val renderedTile:RenderedTile
val tile = TileRequest(x, y, zoom, imageFormat!!.ordinal().toByte())
if (imageFormat == ImageFormat.VECTOR) {
val rendererManager = threadLocalRenderer.get()
val renderer = rendererManager.getTileRenderer(tile, tileServer, tileCacheInfoProvider)
if (renderer == null) {
send(response(HttpResponseStatus.NOT_FOUND), channel, request)
return
}
renderedTile = RenderedTile(renderer.renderVector(tile, tileServer.renderThemeManager.pixiGraphicFactory), Math.floorDiv(System.currentTimeMillis(), 1000), "")
}
else {
try {
renderedTile = tileCache.get(tile)
}
catch (e:UncheckedExecutionException) {
if (e.getCause() is TileNotFound) {
send(response(HttpResponseStatus.NOT_FOUND), channel, request)
}
else {
send(response(HttpResponseStatus.INTERNAL_SERVER_ERROR), channel, request)
LOG.error(e.getMessage(), e)
}
return
}
}
if (checkCache(request, renderedTile.lastModified) || renderedTile.etag == request.headers().get(HttpHeaderNames.IF_NONE_MATCH)) {
send(response(HttpResponseStatus.NOT_MODIFIED), channel, request)
return
}
val isHeadRequest = request.method() == HttpMethod.HEAD
val response = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, if (isHeadRequest) Unpooled.EMPTY_BUFFER else Unpooled.wrappedBuffer(renderedTile.data))
//noinspection ConstantConditions
response.headers().set(HttpHeaderNames.CONTENT_TYPE, imageFormat.getContentType())
// default cache for one day
if (imageFormat != ImageFormat.VECTOR) {
response.headers().set(HttpHeaderNames.CACHE_CONTROL, "public, max-age=" + (60 * 60 * 24))
response.headers().set(HttpHeaderNames.ETAG, renderedTile.etag)
}
response.headers().set(HttpHeaderNames.LAST_MODIFIED, formatTime(renderedTile.lastModified))
addCommonHeaders(response)
if (useVaryAccept) {
response.headers().add(HttpHeaderNames.VARY, "Accept")
}
val keepAlive = addKeepAliveIfNeed(response, request)
if (!isHeadRequest) {
HttpHeaderUtil.setContentLength(response, renderedTile.data.size().toLong())
}
val future = channel.writeAndFlush(response)
if (!keepAlive) {
future.addListener(ChannelFutureListener.CLOSE)
}
}
private fun renderTile(tile:TileRequest):RenderedTile {
val rendererManager = threadLocalRenderer.get()
val renderer = rendererManager.getTileRenderer(tile, tileServer, tileCacheInfoProvider) ?: throw TileNotFound.INSTANCE
val bufferedImage = renderer.render(tile)
val bytes = if (tile.getImageFormat() == ImageFormat.WEBP) WebP.encode(WRITE_PARAM, bufferedImage) else encodePng(bufferedImage)
return RenderedTile(bytes, Math.floorDiv(System.currentTimeMillis(), 1000), renderer.computeETag(tile, rendererManager.stringBuilder))
}
}
|
mit
|
7fdb4cbf33035928da24c5288cfbf461
| 37.814634 | 242 | 0.724645 | 4.340971 | false | false | false | false |
inorichi/tachiyomi-extensions
|
src/tr/MangaDenizi/src/eu/kanade/tachiyomi/extension/tr/mangadenizi/MangaDenizi.kt
|
1
|
4996
|
package eu.kanade.tachiyomi.extension.tr.mangadenizi
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Response
import org.json.JSONObject
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.Locale
class MangaDenizi : ParsedHttpSource() {
override val name = "MangaDenizi"
override val baseUrl = "https://mangadenizi.com"
override val lang = "tr"
override val supportsLatest = true
override val client = network.cloudflareClient
override fun popularMangaSelector() = "div.media-left"
override fun popularMangaRequest(page: Int) = GET("$baseUrl/manga-list?page=$page", headers)
override fun popularMangaFromElement(element: Element) = SManga.create().apply {
setUrlWithoutDomain(element.select("a").attr("href"))
title = element.select("img").attr("alt")
thumbnail_url = element.select("img").attr("abs:src")
}
override fun popularMangaNextPageSelector() = "[rel=next]"
override fun latestUpdatesSelector() = "h3 > a"
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/latest-release?page=$page", headers)
// No thumbnail on latest releases page
override fun latestUpdatesFromElement(element: Element) = SManga.create().apply {
setUrlWithoutDomain(element.attr("href"))
title = element.text()
}
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
override fun latestUpdatesParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas = document.select(latestUpdatesSelector())
.distinctBy { it.text().trim() }
.map { latestUpdatesFromElement(it) }
val hasNextPage = latestUpdatesNextPageSelector().let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
override fun searchMangaSelector() = "Unused"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList) = GET("$baseUrl/search?query=$query", headers)
override fun searchMangaNextPageSelector() = "Unused"
override fun searchMangaFromElement(element: Element) = throw UnsupportedOperationException("Unused")
override fun searchMangaParse(response: Response): MangasPage {
val res = response.body!!.string()
return getMangasPage(res)
}
private fun getMangasPage(json: String): MangasPage {
val response = JSONObject(json)
val results = response.getJSONArray("suggestions")
val mangas = ArrayList<SManga>()
// No thumbnail here either
for (i in 0 until results.length()) {
val obj = results.getJSONObject(i)
val manga = SManga.create()
manga.title = obj.getString("value")
manga.url = "/manga/${obj.getString("data")}"
mangas.add(manga)
}
return MangasPage(mangas, false)
}
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
description = document.select(".well > p").text()
genre = document.select("dd > a[href*=category]").joinToString { it.text() }
status = parseStatus(document.select(".label.label-success").text())
thumbnail_url = document.select("img.img-responsive").attr("abs:src")
}
private fun parseStatus(status: String) = when {
status.contains("Devam Ediyor") -> SManga.ONGOING
status.contains("Tamamlandı") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "ul.chapters li"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
setUrlWithoutDomain(element.select("a").attr("href"))
name = "${element.select("a").text()}: ${element.select("em").text()}"
date_upload = try {
dateFormat.parse(element.select("div.date-chapter-title-rtl").text().trim())?.time ?: 0
} catch (_: Exception) {
0
}
}
companion object {
val dateFormat by lazy {
SimpleDateFormat("dd MMM. yyyy", Locale.US)
}
}
override fun pageListParse(document: Document): List<Page> {
return document.select("img.img-responsive").mapIndexed { i, element ->
val url = if (element.hasAttr("data-src")) element.attr("abs:data-src") else element.attr("abs:src")
Page(i, "", url)
}
}
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not Used")
override fun getFilterList() = FilterList()
}
|
apache-2.0
|
5920f32530c4952472791470601c2099
| 36 | 129 | 0.673473 | 4.565814 | false | true | false | false |
czyzby/ktx
|
assets/src/test/kotlin/ktx/assets/ResolversTest.kt
|
2
|
4082
|
package ktx.assets
import com.badlogic.gdx.Files.FileType
import com.badlogic.gdx.assets.loaders.FileHandleResolver
import com.badlogic.gdx.assets.loaders.resolvers.AbsoluteFileHandleResolver
import com.badlogic.gdx.assets.loaders.resolvers.ClasspathFileHandleResolver
import com.badlogic.gdx.assets.loaders.resolvers.ExternalFileHandleResolver
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver
import com.badlogic.gdx.assets.loaders.resolvers.LocalFileHandleResolver
import com.badlogic.gdx.assets.loaders.resolvers.ResolutionFileResolver
import com.badlogic.gdx.assets.loaders.resolvers.ResolutionFileResolver.Resolution
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Tests [FileHandleResolver] utilities.
*/
class ResolversTest {
@Test
fun `should convert Classpath file type to ClasspathFileHandleResolver`() {
val resolver: FileHandleResolver = FileType.Classpath.getResolver()
assertTrue(resolver is ClasspathFileHandleResolver)
}
@Test
fun `should convert Internal file type to InternalFileHandleResolver`() {
val resolver: FileHandleResolver = FileType.Internal.getResolver()
assertTrue(resolver is InternalFileHandleResolver)
}
@Test
fun `should convert Local file type to LocalFileHandleResolver`() {
val resolver: FileHandleResolver = FileType.Local.getResolver()
assertTrue(resolver is LocalFileHandleResolver)
}
@Test
fun `should convert External file type to ExternalFileHandleResolver`() {
val resolver: FileHandleResolver = FileType.External.getResolver()
assertTrue(resolver is ExternalFileHandleResolver)
}
@Test
fun `should convert Absolute file type to AbsoluteFileHandleResolver`() {
val resolver: FileHandleResolver = FileType.Absolute.getResolver()
assertTrue(resolver is AbsoluteFileHandleResolver)
}
@Test
fun `should decorate FileHandleResolver with PrefixFileHandleResolver`() {
val resolver = InternalFileHandleResolver()
val decorated = resolver.withPrefix("test")
assertSame(resolver, decorated.baseResolver)
assertEquals("test", decorated.prefix)
}
@Test
fun `should decorate FileHandleResolver with ResolutionFileResolver`() {
val resolver = InternalFileHandleResolver()
val decorated = resolver.forResolutions(Resolution(600, 400, "mock"))
assertSame(resolver, decorated.baseResolver)
assertEquals(1, decorated.resolutions.size)
val resolution = decorated.resolutions[0]
assertEquals(600, resolution.portraitWidth)
assertEquals(400, resolution.portraitHeight)
assertEquals("mock", resolution.folder)
}
@Test(expected = IllegalArgumentException::class)
fun `should not decorate FileHandleResolver with ResolutionFileResolver given no resolutions`() {
val resolver = InternalFileHandleResolver()
resolver.forResolutions()
}
@Test
fun `should construct Resolution`() {
val resolution = resolution(width = 800, height = 600, folder = "test")
assertEquals(800, resolution.portraitWidth)
assertEquals(600, resolution.portraitHeight)
assertEquals("test", resolution.folder)
}
@Test
fun `should construct Resolution with default folder name`() {
val resolution = resolution(width = 1024, height = 768)
assertEquals(1024, resolution.portraitWidth)
assertEquals(768, resolution.portraitHeight)
assertEquals("1024x768", resolution.folder)
}
/**
* Extracts protected [FileHandleResolver] field.
*/
val ResolutionFileResolver.baseResolver: FileHandleResolver
get() = ResolutionFileResolver::class.java.getDeclaredField("baseResolver")
.apply { isAccessible = true }
.get(this) as FileHandleResolver
/**
* Extracts protected [Resolution] array field.
*/
@Suppress("UNCHECKED_CAST")
val ResolutionFileResolver.resolutions: Array<Resolution>
get() = ResolutionFileResolver::class.java.getDeclaredField("descriptors")
.apply { isAccessible = true }
.get(this) as Array<Resolution>
}
|
cc0-1.0
|
da53abe5680c33e088f4d88038cbce4a
| 32.735537 | 99 | 0.769721 | 4.84223 | false | true | false | false |
TCA-Team/TumCampusApp
|
app/src/main/java/de/tum/in/tumcampusapp/utils/DateTimeUtils.kt
|
1
|
6570
|
package de.tum.`in`.tumcampusapp.utils
import android.content.Context
import android.text.format.DateUtils.*
import de.tum.`in`.tumcampusapp.R
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import java.text.ParseException
import java.util.*
object DateTimeUtils {
@JvmStatic
fun dateWithStartOfDay(): DateTime {
return DateTime.now().withTimeAtStartOfDay()
}
@JvmStatic
fun dateWithEndOfDay(): DateTime {
return dateWithStartOfDay()
.withHourOfDay(23)
.withMinuteOfHour(59)
.withSecondOfMinute(59)
}
/**
* TODO this uses inconsistent capitalization: "Just now" and "in 30 minutes"
* Format an upcoming string nicely by being more precise as time comes closer
* E.g.:
* Just now
* in 30 minutes
* at 15:20
* in 5 hours
* tomorrow
* @see getRelativeTimeSpanString()
*/
fun formatFutureTime(time: DateTime, context: Context): String {
val timeInMillis = time.millis
val now = DateTime.now().millis
// Catch future dates: current clock might be running behind
if (timeInMillis < now || timeInMillis <= 0) {
return DateTimeUtils.formatTimeOrDay(time, context)
}
val diff = timeInMillis - now
return when {
diff < 60 * MINUTE_IN_MILLIS -> {
val formatter = DateTimeFormat.forPattern("m")
.withLocale(Locale.ENGLISH)
"${context.getString(R.string.IN)} ${formatter.print(DateTime(diff))} " +
context.getString(R.string.MINUTES)
}
// Be more precise by telling the user the exact time if below 3 hours
diff < 3 * HOUR_IN_MILLIS -> {
val formatter = DateTimeFormat.forPattern("HH:mm")
.withLocale(Locale.ENGLISH)
"${context.getString(R.string.AT)} ${formatter.print(time)}"
}
else -> getRelativeTimeSpanString(timeInMillis, now, MINUTE_IN_MILLIS,
FORMAT_ABBREV_RELATIVE).toString()
}
}
/**
* @Deprecated use formatTimeOrDay(DateTime, Context)
*/
@Deprecated("Use the version with a proper DateTime object, there's really no reason to pass datetimes as strings")
fun formatTimeOrDayFromISO(datetime: String, context: Context): String {
val d = DateTimeUtils.parseIsoDate(datetime) ?: return ""
return DateTimeUtils.formatTimeOrDay(d, context)
}
/**
* Format a *past* ISO string timestamp with degrading granularity as time goes by
* E.g.:
* Just now
* 18:20
* Yesterday
* 12.03.2016
*
* Please note, that this does *not* use getRelativeTimeSpanString(), because lectures scheduled
* at 12:00 and starting at 12:15 get a bit annoying nagging you with "12 minutes ago", when
* they actually only start in a couple of minutes
* This is similar to formatFutureTime(), but not specialized on future dates
* When in doubt, use formatFutureTime()
* @see formatFutureTime()
*/
fun formatTimeOrDay(time: DateTime, context: Context): String {
val timeInMillis = time.millis
val now = DateTime.now().millis
// Catch future dates: current clock might be running behind
if (timeInMillis > now || timeInMillis <= 0) {
return context.getString(R.string.just_now)
}
val diff = now - timeInMillis
return when {
diff < MINUTE_IN_MILLIS ->
context.getString(R.string.just_now)
diff < 24 * HOUR_IN_MILLIS ->
DateTimeFormat.forPattern("HH:mm")
.withLocale(Locale.ENGLISH)
.print(time)
diff < 48 * HOUR_IN_MILLIS ->
context.getString(R.string.yesterday)
else ->
DateTimeFormat.forPattern("dd.MM.yyyy")
.withLocale(Locale.ENGLISH)
.print(time)
}
}
/**
* 2014-06-30T16:31:57Z
*/
private val isoDateFormatter: DateTimeFormatter =
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
fun parseIsoDate(datetime: String) = try {
isoDateFormatter.parseDateTime(datetime)
} catch (e: ParseException) {
Utils.log(e)
null
}
/**
* 2014-06-30T16:31:57.878Z
*/
private val isoDateWithMillisFormatter: DateTimeFormatter =
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
fun parseIsoDateWithMillis(datetime: String) = try {
isoDateWithMillisFormatter.parseDateTime(datetime)
} catch (e: ParseException) {
Utils.log(e)
null
}
/**
* Checks whether two DateTime contain the same day
*
* @return true if both dates are on the same day
*/
fun isSameDay(first: DateTime, second: DateTime) =
first.year() == second.year() && first.dayOfYear() == second.dayOfYear()
private val dateFormatter: DateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd")
/**
* Converts a date-string to DateTime
*
* @param str String with ISO-Date (yyyy-mm-dd)
* @return DateTime
*/
fun getDate(str: String): DateTime = try {
DateTime.parse(str, dateFormatter)
} catch (e: RuntimeException) {
Utils.log(e)
DateTime()
}
/**
* Converts DateTime to an ISO date-string
*
* @param d DateTime
* @return String (yyyy-mm-dd)
*/
fun getDateString(d: DateTime): String = dateFormatter.print(d)
private val dateTimeFormatter: DateTimeFormatter =
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
/**
* Converts DateTime to an ISO datetime-string
*
* @return String (yyyy-mm-dd hh:mm:ss)
*/
@JvmStatic
fun getDateTimeString(d: DateTime): String = dateTimeFormatter.print(d)
/**
* Converts a datetime-string to DateTime
*
* @param str String with ISO-DateTime (yyyy-mm-dd hh:mm:ss)
*/
fun getDateTime(str: String): DateTime = try {
DateTime.parse(str, dateTimeFormatter)
} catch (e: RuntimeException) {
Utils.log(e)
DateTime()
}
fun getTimeString(d: DateTime): String = timeFormatter.print(d)
private val timeFormatter = DateTimeFormat.forPattern("HH:mm")
}
|
gpl-3.0
|
81b5c623100a80a21a296d79dbbe0811
| 32.015075 | 119 | 0.601674 | 4.394649 | false | false | false | false |
mitallast/netty-queue
|
src/main/java/org/mitallast/queue/common/component/LifecycleService.kt
|
1
|
1447
|
package org.mitallast.queue.common.component
import com.google.inject.spi.ProvisionListener
import org.mitallast.queue.common.logging.LoggingService
import java.util.*
class LifecycleService(logging: LoggingService) : AbstractLifecycleComponent(logging), ProvisionListener {
private val lifecycleQueue = ArrayList<LifecycleComponent>()
@Synchronized
override fun <T> onProvision(provision: ProvisionListener.ProvisionInvocation<T>) {
val instance = provision.provision()
if (instance === this) {
return
}
logger.debug("provision {}", instance)
val lifecycleComponent = instance as LifecycleComponent
lifecycleQueue.add(lifecycleComponent)
}
@Synchronized
override fun doStart() {
for (component in lifecycleQueue) {
logger.debug("starting {}", component)
component.start()
}
}
@Synchronized
override fun doStop() {
val size = lifecycleQueue.size
for (i in size - 1 downTo 0) {
val component = lifecycleQueue[i]
logger.debug("stopping {}", component)
component.stop()
}
}
@Synchronized
override fun doClose() {
val size = lifecycleQueue.size
for (i in size - 1 downTo 0) {
val component = lifecycleQueue[i]
logger.debug("closing {}", component)
component.close()
}
}
}
|
mit
|
4a1c1f3d1c6dd093222adda0db8d217d
| 28.530612 | 106 | 0.628887 | 4.855705 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/intellij-compat/src/223/compat/com/intellij/compat/openapi/module/MockModuleManager.kt
|
1
|
3144
|
/*
* Copyright (C) 2018, 2022 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.compat.openapi.module
import com.intellij.openapi.module.*
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.graph.Graph
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.nio.file.Path
@TestOnly
@Suppress("NonExtendableApiUsage")
abstract class MockModuleManager : ModuleManager() {
private var modules: Array<Module> = arrayOf()
protected abstract fun createModule(moduleFile: VirtualFile): Module
fun addModule(moduleFile: VirtualFile): Module {
val module = createModule(moduleFile)
modules = arrayOf(module, *modules)
return module
}
@Suppress("UnstableApiUsage")
override fun setUnloadedModules(unloadedModuleNames: MutableList<String>): Unit = TODO()
override fun getModifiableModel(): ModifiableModuleModel = TODO()
override fun newModule(filePath: String, moduleTypeId: String): Module = TODO()
override fun getModuleDependentModules(module: Module): MutableList<Module> = TODO()
override fun moduleDependencyComparator(): Comparator<Module> = TODO()
override fun moduleGraph(): Graph<Module> = TODO()
override fun moduleGraph(includeTests: Boolean): Graph<Module> = TODO()
@ApiStatus.Experimental
@Suppress("UnstableApiUsage")
override fun getUnloadedModuleDescriptions(): MutableCollection<UnloadedModuleDescription> = TODO()
override fun hasModuleGroups(): Boolean = TODO()
override fun isModuleDependent(module: Module, onModule: Module): Boolean = TODO()
@ApiStatus.Experimental
@Suppress("UnstableApiUsage")
override fun getAllModuleDescriptions(): MutableCollection<ModuleDescription> = TODO()
override fun getModuleGroupPath(module: Module): Array<String> = TODO()
@ApiStatus.Experimental
@Suppress("UnstableApiUsage")
override fun getModuleGrouper(model: ModifiableModuleModel?): ModuleGrouper = TODO()
@Deprecated("Deprecated in Java", ReplaceWith("TODO()"))
override fun loadModule(filePath: String): Module = TODO()
override fun loadModule(file: Path): Module = TODO()
@ApiStatus.Experimental
@Suppress("UnstableApiUsage")
override fun getUnloadedModuleDescription(moduleName: String): UnloadedModuleDescription = TODO()
override fun getModules(): Array<Module> = modules
override fun getSortedModules(): Array<Module> = modules
override fun findModuleByName(name: String): Module = TODO()
override fun disposeModule(module: Module): Unit = TODO()
}
|
apache-2.0
|
81a3827c32f5fa0b0bc5d8a8b3adc4d4
| 35.137931 | 103 | 0.744911 | 4.904836 | false | false | false | false |
jiaminglu/kotlin-native
|
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/MappingBridgeGeneratorImpl.kt
|
1
|
7686
|
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.native.interop.gen
import org.jetbrains.kotlin.native.interop.indexer.RecordType
import org.jetbrains.kotlin.native.interop.indexer.Type
import org.jetbrains.kotlin.native.interop.indexer.VoidType
/**
* The [MappingBridgeGenerator] implementation which uses [SimpleBridgeGenerator] as the backend and
* maps the type using [mirror].
*/
class MappingBridgeGeneratorImpl(
val declarationMapper: DeclarationMapper,
val simpleBridgeGenerator: SimpleBridgeGenerator,
val kotlinScope: KotlinScope
) : MappingBridgeGenerator {
override fun kotlinToNative(
builder: KotlinCodeBuilder,
nativeBacked: NativeBacked,
returnType: Type,
kotlinValues: List<TypedKotlinValue>,
block: NativeCodeBuilder.(nativeValues: List<NativeExpression>) -> NativeExpression
): KotlinExpression {
val bridgeArguments = mutableListOf<BridgeTypedKotlinValue>()
kotlinValues.forEachIndexed { index, (type, value) ->
if (type.unwrapTypedefs() is RecordType) {
val tmpVarName = "kni$index"
builder.pushBlock("$value.usePointer { $tmpVarName ->")
bridgeArguments.add(BridgeTypedKotlinValue(BridgedType.NATIVE_PTR, "$tmpVarName.rawValue"))
} else {
val info = mirror(declarationMapper, type).info
bridgeArguments.add(BridgeTypedKotlinValue(info.bridgedType, info.argToBridged(value)))
}
}
val unwrappedReturnType = returnType.unwrapTypedefs()
val kniRetVal = "kniRetVal"
val bridgeReturnType = when (unwrappedReturnType) {
VoidType -> BridgedType.VOID
is RecordType -> {
val mirror = mirror(declarationMapper, returnType)
val tmpVarName = kniRetVal
builder.out("val $tmpVarName = nativeHeap.alloc<${mirror.pointedType.render(kotlinScope)}>()")
builder.pushBlock("try {", free = "finally { nativeHeap.free($tmpVarName) }")
bridgeArguments.add(BridgeTypedKotlinValue(BridgedType.NATIVE_PTR, "$tmpVarName.rawPtr"))
BridgedType.VOID
}
else -> {
val mirror = mirror(declarationMapper, returnType)
mirror.info.bridgedType
}
}
val callExpr = simpleBridgeGenerator.kotlinToNative(
nativeBacked, bridgeReturnType, bridgeArguments
) { bridgeNativeValues ->
val nativeValues = mutableListOf<String>()
kotlinValues.forEachIndexed { index, (type, _) ->
val unwrappedType = type.unwrapTypedefs()
if (unwrappedType is RecordType) {
nativeValues.add("*(${unwrappedType.decl.spelling}*)${bridgeNativeValues[index]}")
} else {
nativeValues.add(mirror(declarationMapper, type).info.cFromBridged(bridgeNativeValues[index]))
}
}
val nativeResult = block(nativeValues)
when (unwrappedReturnType) {
is VoidType -> {
out(nativeResult + ";")
""
}
is RecordType -> {
out("*(${unwrappedReturnType.decl.spelling}*)${bridgeNativeValues.last()} = $nativeResult;")
""
}
else -> {
nativeResult
}
}
}
val result = when (unwrappedReturnType) {
is VoidType -> callExpr
is RecordType -> {
builder.out(callExpr)
"$kniRetVal.readValue()"
}
else -> {
val mirror = mirror(declarationMapper, returnType)
mirror.info.argFromBridged(callExpr, kotlinScope)
}
}
return result
}
override fun nativeToKotlin(
builder: NativeCodeBuilder,
nativeBacked: NativeBacked,
returnType: Type,
nativeValues: List<TypedNativeValue>,
block: KotlinCodeBuilder.(kotlinValues: List<KotlinExpression>) -> KotlinExpression
): NativeExpression {
val bridgeArguments = mutableListOf<BridgeTypedNativeValue>()
nativeValues.forEachIndexed { _, (type, value) ->
val bridgeArgument = if (type.unwrapTypedefs() is RecordType) {
BridgeTypedNativeValue(BridgedType.NATIVE_PTR, "&$value")
} else {
val info = mirror(declarationMapper, type).info
BridgeTypedNativeValue(info.bridgedType, value)
}
bridgeArguments.add(bridgeArgument)
}
val unwrappedReturnType = returnType.unwrapTypedefs()
val kniRetVal = "kniRetVal"
val bridgeReturnType = when (unwrappedReturnType) {
VoidType -> BridgedType.VOID
is RecordType -> {
val tmpVarName = kniRetVal
builder.out("${unwrappedReturnType.decl.spelling} $tmpVarName;")
bridgeArguments.add(BridgeTypedNativeValue(BridgedType.NATIVE_PTR, "&$tmpVarName"))
BridgedType.VOID
}
else -> {
val mirror = mirror(declarationMapper, returnType)
mirror.info.bridgedType
}
}
val callExpr = simpleBridgeGenerator.nativeToKotlin(
nativeBacked,
bridgeReturnType,
bridgeArguments
) { bridgeKotlinValues ->
val kotlinValues = mutableListOf<String>()
nativeValues.forEachIndexed { index, (type, _) ->
val mirror = mirror(declarationMapper, type)
if (type.unwrapTypedefs() is RecordType) {
val pointedTypeName = mirror.pointedType.render(kotlinScope)
kotlinValues.add(
"interpretPointed<$pointedTypeName>(${bridgeKotlinValues[index]}).readValue()"
)
} else {
kotlinValues.add(mirror.info.argFromBridged(bridgeKotlinValues[index], kotlinScope))
}
}
val kotlinResult = block(kotlinValues)
when (unwrappedReturnType) {
is RecordType -> {
"$kotlinResult.write(${bridgeKotlinValues.last()})"
}
is VoidType -> {
kotlinResult
}
else -> {
mirror(declarationMapper, returnType).info.argToBridged(kotlinResult)
}
}
}
val result = when (unwrappedReturnType) {
is VoidType -> callExpr
is RecordType -> {
builder.out("$callExpr;")
kniRetVal
}
else -> {
mirror(declarationMapper, returnType).info.cFromBridged(callExpr)
}
}
return result
}
}
|
apache-2.0
|
f516ad2d495f60033981f37969db9097
| 37.823232 | 114 | 0.575852 | 5.203791 | false | false | false | false |
da1z/intellij-community
|
plugins/git4idea/src/git4idea/GitStatisticsCollector.kt
|
1
|
3958
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea
import com.google.common.collect.HashMultiset
import com.intellij.internal.statistic.AbstractProjectsUsagesCollector
import com.intellij.internal.statistic.UsageTrigger
import com.intellij.internal.statistic.beans.GroupDescriptor
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.internal.statistic.utils.getBooleanUsage
import com.intellij.internal.statistic.utils.getCountingUsage
import com.intellij.openapi.project.Project
import com.intellij.util.io.URLUtil
import git4idea.config.GitVcsSettings
import git4idea.repo.GitRemote
fun reportUsage(key: String) {
UsageTrigger.trigger(key)
}
class GitStatisticsCollector : AbstractProjectsUsagesCollector() {
private val ID = GroupDescriptor.create("Git")
override fun getProjectUsages(project: Project): Set<UsageDescriptor> {
val repositoryManager = GitUtil.getRepositoryManager(project)
val settings = GitVcsSettings.getInstance(project)
val repositories = repositoryManager.repositories
val usages = hashSetOf<UsageDescriptor>()
usages.add(UsageDescriptor("config.repo.sync." + settings.syncSetting.name, 1))
usages.add(UsageDescriptor("config.update.type." + settings.updateType.name, 1))
usages.add(UsageDescriptor("config.save.policy." + settings.updateChangesPolicy().name, 1))
usages.add(getBooleanUsage("config.ssh", settings.isIdeaSsh))
usages.add(getBooleanUsage("config.push.autoupdate", settings.autoUpdateIfPushRejected()))
usages.add(getBooleanUsage("config.push.update.all.roots", settings.shouldUpdateAllRootsIfPushRejected()))
usages.add(getBooleanUsage("config.cherry-pick.autocommit", settings.isAutoCommitOnCherryPick))
usages.add(getBooleanUsage("config.warn.about.crlf", settings.warnAboutCrlf()))
usages.add(getBooleanUsage("config.warn.about.detached", settings.warnAboutDetachedHead()))
usages.add(getBooleanUsage("config.force.push", settings.warnAboutDetachedHead()))
for (repository in repositories) {
val branches = repository.branches
usages.add(getCountingUsage("data.local.branches.count", branches.localBranches.size, listOf(0, 1, 2, 5, 8, 15, 30, 50)))
usages.add(getCountingUsage("data.remote.branches.count", branches.remoteBranches.size, listOf(0, 1, 2, 5, 8, 15, 30, 100)))
usages.add(getCountingUsage("data.remotes.in.project", repository.remotes.size, listOf(0, 1, 2, 5)))
val servers = repository.remotes.mapNotNull(this::getRemoteServerType).toCollection(HashMultiset.create())
for (serverName in servers) {
usages.add(getCountingUsage("data.remote.servers." + serverName, servers.count(serverName), listOf(0, 1, 2, 3, 5)))
}
}
return usages
}
override fun getGroupId(): GroupDescriptor {
return ID
}
private fun getRemoteServerType(remote: GitRemote): String? {
val hosts = remote.urls.map(URLUtil::parseHostFromSshUrl).distinct()
if (hosts.contains("github.com")) return "github.com"
if (hosts.contains("gitlab.com")) return "gitlab.com"
if (hosts.contains("bitbucket.org")) return "bitbucket.org"
if (remote.urls.any { it.contains("github") }) return "github.custom"
if (remote.urls.any { it.contains("gitlab") }) return "gitlab.custom"
if (remote.urls.any { it.contains("bitbucket") }) return "bitbucket.custom"
return null
}
}
|
apache-2.0
|
4587bcd06ffa0460b47de4eb3431ea41
| 44.494253 | 130 | 0.755179 | 4.080412 | false | true | false | false |
apollostack/apollo-android
|
composite/samples/kotlin-sample/src/main/java/com/apollographql/apollo3/kotlinsample/commits/CommitsActivity.kt
|
1
|
2772
|
package com.apollographql.apollo3.kotlinsample.commits
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.apollographql.apollo3.kotlinsample.GithubRepositoryCommitsQuery
import com.apollographql.apollo3.kotlinsample.KotlinSampleApp
import com.apollographql.apollo3.kotlinsample.R
import com.apollographql.apollo3.kotlinsample.data.GitHubDataSource
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_commits.*
class CommitsActivity : AppCompatActivity() {
private val adapter = CommitsAdapter()
private val compositeDisposable = CompositeDisposable()
private val dataSource: GitHubDataSource by lazy {
(application as KotlinSampleApp).getDataSource()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_commits)
val repoName = intent.getStringExtra(REPO_NAME_KEY)!!
supportActionBar?.title = repoName
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerView.adapter = adapter
tvError.visibility = GONE
progressBar.visibility = VISIBLE
setupDataSource()
dataSource.fetchCommits(repoName)
}
private fun setupDataSource() {
val successDisposable = dataSource.commits
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::handleCommits)
val errorDisposable = dataSource.error
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::handleError)
compositeDisposable.add(successDisposable)
compositeDisposable.add(errorDisposable)
}
override fun onDestroy() {
super.onDestroy()
compositeDisposable.dispose()
dataSource.cancelFetching()
}
private fun handleCommits(commits: List<GithubRepositoryCommitsQuery.Data.Viewer.Repository.Ref.CommitTarget.History.Edge>) {
progressBar.visibility = GONE
adapter.setItems(commits)
}
private fun handleError(error: Throwable?) {
progressBar.visibility = GONE
tvError.visibility = VISIBLE
tvError.text = error?.localizedMessage
}
companion object {
private const val REPO_NAME_KEY = "repoName"
fun start(context: Context, repoName: String) {
val intent = Intent(context, CommitsActivity::class.java)
intent.putExtra(REPO_NAME_KEY, repoName)
context.startActivity(intent)
}
}
}
|
mit
|
055851587e959c731f7608f27e2bd210
| 32.39759 | 127 | 0.77381 | 4.837696 | false | false | false | false |
Heiner1/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt
|
1
|
11807
|
package info.nightscout.androidaps.plugins.aps.openAPSSMB
import android.content.Context
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreference
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.annotations.OpenForTesting
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.extensions.target
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.HardLimits
import info.nightscout.androidaps.utils.Profiler
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP
import javax.inject.Inject
import javax.inject.Singleton
@OpenForTesting
@Singleton
class OpenAPSSMBPlugin @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
private val rxBus: RxBus,
private val constraintChecker: ConstraintChecker,
rh: ResourceHelper,
private val profileFunction: ProfileFunction,
val context: Context,
private val activePlugin: ActivePlugin,
private val iobCobCalculator: IobCobCalculator,
private val hardLimits: HardLimits,
private val profiler: Profiler,
private val sp: SP,
private val dateUtil: DateUtil,
private val repository: AppRepository,
private val glucoseStatusProvider: GlucoseStatusProvider
) : PluginBase(
PluginDescription()
.mainType(PluginType.APS)
.fragmentClass(OpenAPSSMBFragment::class.java.name)
.pluginIcon(R.drawable.ic_generic_icon)
.pluginName(R.string.openapssmb)
.shortName(R.string.smb_shortname)
.preferencesId(R.xml.pref_openapssmb)
.description(R.string.description_smb)
.setDefault(),
aapsLogger, rh, injector
), APS, Constraints {
// last values
override var lastAPSRun: Long = 0
override var lastAPSResult: DetermineBasalResultSMB? = null
override var lastDetermineBasalAdapter: DetermineBasalAdapterInterface? = null
override var lastAutosensResult = AutosensResult()
override fun specialEnableCondition(): Boolean {
return try {
activePlugin.activePump.pumpDescription.isTempBasalCapable
} catch (ignored: Exception) {
// may fail during initialization
true
}
}
override fun specialShowInListCondition(): Boolean {
val pump = activePlugin.activePump
return pump.pumpDescription.isTempBasalCapable
}
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment)
val smbAlwaysEnabled = sp.getBoolean(R.string.key_enableSMB_always, false)
preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_enableSMB_with_COB))?.isVisible = !smbAlwaysEnabled
preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_enableSMB_with_temptarget))?.isVisible = !smbAlwaysEnabled
preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_enableSMB_after_carbs))?.isVisible = !smbAlwaysEnabled
}
override fun invoke(initiator: String, tempBasalFallback: Boolean) {
aapsLogger.debug(LTag.APS, "invoke from $initiator tempBasalFallback: $tempBasalFallback")
lastAPSResult = null
val glucoseStatus = glucoseStatusProvider.glucoseStatusData
val profile = profileFunction.getProfile()
val pump = activePlugin.activePump
if (profile == null) {
rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.noprofileset)))
aapsLogger.debug(LTag.APS, rh.gs(R.string.noprofileset))
return
}
if (!isEnabled(PluginType.APS)) {
rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_disabled)))
aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_disabled))
return
}
if (glucoseStatus == null) {
rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_noglucosedata)))
aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_noglucosedata))
return
}
val inputConstraints = Constraint(0.0) // fake. only for collecting all results
val maxBasal = constraintChecker.getMaxBasalAllowed(profile).also {
inputConstraints.copyReasons(it)
}.value()
var start = System.currentTimeMillis()
var startPart = System.currentTimeMillis()
profiler.log(LTag.APS, "getMealData()", startPart)
val maxIob = constraintChecker.getMaxIOBAllowed().also { maxIOBAllowedConstraint ->
inputConstraints.copyReasons(maxIOBAllowedConstraint)
}.value()
var minBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetLowMgdl(), 0.1), R.string.profile_low_target, HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1])
var maxBg =
hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetHighMgdl(), 0.1), R.string.profile_high_target, HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1])
var targetBg = hardLimits.verifyHardLimits(profile.getTargetMgdl(), R.string.temp_target_value, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1])
var isTempTarget = false
val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet()
if (tempTarget is ValueWrapper.Existing) {
isTempTarget = true
minBg =
hardLimits.verifyHardLimits(
tempTarget.value.lowTarget,
R.string.temp_target_low_target,
HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0].toDouble(),
HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1].toDouble()
)
maxBg =
hardLimits.verifyHardLimits(
tempTarget.value.highTarget,
R.string.temp_target_high_target,
HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0].toDouble(),
HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1].toDouble()
)
targetBg =
hardLimits.verifyHardLimits(
tempTarget.value.target(),
R.string.temp_target_value,
HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0].toDouble(),
HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[1].toDouble()
)
}
if (!hardLimits.checkHardLimits(profile.dia, R.string.profile_dia, hardLimits.minDia(), hardLimits.maxDia())) return
if (!hardLimits.checkHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), R.string.profile_carbs_ratio_value, hardLimits.minIC(), hardLimits.maxIC())) return
if (!hardLimits.checkHardLimits(profile.getIsfMgdl(), R.string.profile_sensitivity_value, HardLimits.MIN_ISF, HardLimits.MAX_ISF)) return
if (!hardLimits.checkHardLimits(profile.getMaxDailyBasal(), R.string.profile_max_daily_basal_value, 0.02, hardLimits.maxBasal())) return
if (!hardLimits.checkHardLimits(pump.baseBasalRate, R.string.current_basal_value, 0.01, hardLimits.maxBasal())) return
startPart = System.currentTimeMillis()
if (constraintChecker.isAutosensModeEnabled().value()) {
val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin")
if (autosensData == null) {
rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openaps_noasdata)))
return
}
lastAutosensResult = autosensData.autosensResult
} else {
lastAutosensResult.sensResult = "autosens disabled"
}
val iobArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget)
profiler.log(LTag.APS, "calculateIobArrayInDia()", startPart)
startPart = System.currentTimeMillis()
val smbAllowed = Constraint(!tempBasalFallback).also {
constraintChecker.isSMBModeEnabled(it)
inputConstraints.copyReasons(it)
}
val advancedFiltering = Constraint(!tempBasalFallback).also {
constraintChecker.isAdvancedFilteringEnabled(it)
inputConstraints.copyReasons(it)
}
val uam = Constraint(true).also {
constraintChecker.isUAMEnabled(it)
inputConstraints.copyReasons(it)
}
profiler.log(LTag.APS, "detectSensitivityAndCarbAbsorption()", startPart)
profiler.log(LTag.APS, "SMB data gathering", start)
start = System.currentTimeMillis()
provideDetermineBasalAdapter().also { determineBasalAdapterSMBJS ->
determineBasalAdapterSMBJS.setData(
profile, maxIob, maxBasal, minBg, maxBg, targetBg,
activePlugin.activePump.baseBasalRate,
iobArray,
glucoseStatus,
iobCobCalculator.getMealDataWithWaitingForCalculationFinish(),
lastAutosensResult.ratio,
isTempTarget,
smbAllowed.value(),
uam.value(),
advancedFiltering.value(),
activePlugin.activeBgSource.javaClass.simpleName == "DexcomPlugin"
)
val now = System.currentTimeMillis()
val determineBasalResultSMB = determineBasalAdapterSMBJS.invoke()
profiler.log(LTag.APS, "SMB calculation", start)
if (determineBasalResultSMB == null) {
aapsLogger.error(LTag.APS, "SMB calculation returned null")
lastDetermineBasalAdapter = null
lastAPSResult = null
lastAPSRun = 0
} else {
// TODO still needed with oref1?
// Fix bug determine basal
if (determineBasalResultSMB.rate == 0.0 && determineBasalResultSMB.duration == 0 && iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now()) == null) determineBasalResultSMB.tempBasalRequested =
false
determineBasalResultSMB.iob = iobArray[0]
determineBasalResultSMB.json?.put("timestamp", dateUtil.toISOString(now))
determineBasalResultSMB.inputConstraints = inputConstraints
lastDetermineBasalAdapter = determineBasalAdapterSMBJS
lastAPSResult = determineBasalResultSMB as DetermineBasalResultSMB
lastAPSRun = now
}
}
rxBus.send(EventOpenAPSUpdateGui())
}
override fun isSuperBolusEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
value.set(aapsLogger, false)
return value
}
fun provideDetermineBasalAdapter(): DetermineBasalAdapterInterface = DetermineBasalAdapterSMBJS(ScriptReader(context), injector)
}
|
agpl-3.0
|
4db3b27a0e4d297edcda57abe3e82726
| 49.896552 | 225 | 0.693148 | 4.648425 | false | false | false | false |
exponentjs/exponent
|
packages/expo-dev-launcher/android/src/debug/java/expo/modules/devlauncher/modules/DevLauncherDevMenuExtensions.kt
|
2
|
1629
|
package expo.modules.devlauncher.modules
import android.view.KeyEvent
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import expo.interfaces.devmenu.DevMenuExtensionInterface
import expo.interfaces.devmenu.DevMenuExtensionSettingsInterface
import expo.interfaces.devmenu.items.DevMenuItemImportance
import expo.interfaces.devmenu.items.DevMenuItemsContainer
import expo.interfaces.devmenu.items.DevMenuItemsContainerInterface
import expo.interfaces.devmenu.items.KeyCommand
import expo.modules.devlauncher.DevLauncherController
import expo.modules.devlauncher.koin.devLauncherKoin
import expo.modules.devlauncher.launcher.DevLauncherControllerInterface
class DevLauncherDevMenuExtensions(
reactContext: ReactApplicationContext?
) : ReactContextBaseJavaModule(reactContext),
DevMenuExtensionInterface {
override fun getName(): String {
return "ExpoDevLauncherDevMenuExtensions"
}
override fun devMenuItems(settings: DevMenuExtensionSettingsInterface): DevMenuItemsContainerInterface =
DevMenuItemsContainer.export {
val controller = devLauncherKoin().getOrNull<DevLauncherControllerInterface>()
if (controller?.mode == DevLauncherController.Mode.LAUNCHER) {
return@export
}
action("dev-launcher-back-to-launcher", {
controller?.navigateToLauncher()
}) {
isEnabled = { true }
label = { "Back to Launcher" }
glyphName = { "exit-to-app" }
importance = DevMenuItemImportance.MEDIUM.value
keyCommand = KeyCommand(KeyEvent.KEYCODE_L, false)
}
}
}
|
bsd-3-clause
|
d7baabb782a35107da31d28a3a5689f8
| 36.883721 | 106 | 0.788214 | 4.906627 | false | false | false | false |
AAkira/ExpandableLayout
|
library-ui-test/src/main/kotlin/com/github/aakira/expandablelayout/uitest/ExpandableRecyclerViewActivity.kt
|
2
|
6864
|
package com.github.aakira.expandablelayout.uitest
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.SparseBooleanArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.RelativeLayout
import android.widget.TextView
import com.github.aakira.expandablelayout.ExpandableLayout
import com.github.aakira.expandablelayout.ExpandableLayoutListenerAdapter
import com.github.aakira.expandablelayout.ExpandableLinearLayout
import com.github.aakira.expandablelayout.Utils
import java.util.*
import kotlin.properties.Delegates
class ExpandableRecyclerViewActivity : AppCompatActivity() {
companion object {
const val DURATION = 200L
@JvmStatic fun startActivity(context: Context) {
context.startActivity(Intent(context, ExpandableRelativeLayoutActivity3::class.java))
}
}
private var recyclerView: RecyclerView by Delegates.notNull()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_expandable_recycler_view)
supportActionBar?.title = ExpandableRelativeLayoutActivity3::class.java.simpleName
val colors = arrayListOf(
R.color.material_red_500 to R.color.material_red_300,
R.color.material_pink_500 to R.color.material_pink_300,
R.color.material_purple_500 to R.color.material_purple_300,
R.color.material_deep_purple_500 to R.color.material_deep_purple_300,
R.color.material_indigo_500 to R.color.material_indigo_300,
R.color.material_blue_500 to R.color.material_blue_300,
R.color.material_light_blue_500 to R.color.material_light_blue_300,
R.color.material_cyan_500 to R.color.material_cyan_300,
R.color.material_cyan_500 to R.color.material_cyan_300
)
val texts = arrayListOf(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" +
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccc" +
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccc" +
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
"dddddddddddddddddddddddddddddddddddddddddddddddddddddddd" +
"dddddddddddddddddddddddddddddddddddddddddddddddddddddddd" +
"dddddddddddddddddddddddddddddddddddddddddddddddddddddddd" +
"dddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
)
val data = ArrayList<ItemModel>()
IntRange(0, 100).forEach {
val color = colors[it % colors.size]
data.add(ItemModel(" ------------------ $it ------------------",
texts[it % texts.size], color.first, color.second))
}
recyclerView = findViewById(R.id.recyclerView) as RecyclerView
recyclerView.layoutManager = LinearLayoutManager(this);
recyclerView.adapter = RecyclerViewAdapter(data)
}
data class ItemModel(val title: String, val description: String, var colorId1: Int, val colorId2: Int)
class RecyclerViewAdapter(private val data: List<ItemModel>) : RecyclerView.Adapter<RecyclerViewAdapter.ExpandableViewHolder>() {
private var context: Context? = null
private val expandState = SparseBooleanArray()
init {
for (i in data.indices) {
expandState.append(i, false)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExpandableViewHolder {
this.context = parent.context
return ExpandableViewHolder(LayoutInflater.from(context).inflate(R.layout.recycler_view_list_row, parent, false))
}
override fun onBindViewHolder(holder: ExpandableViewHolder, position: Int) {
val item = data[position]
holder.setIsRecyclable(false)
holder.title.text = item.title
holder.description.text = item.description
holder.itemView.setBackgroundColor(ContextCompat.getColor(context, item.colorId1))
holder.expandableLayout.setInRecyclerView(true)
holder.expandableLayout.setBackgroundColor(ContextCompat.getColor(context, item.colorId2))
holder.expandableLayout.setInterpolator(LinearInterpolator())
holder.expandableLayout.isExpanded = expandState.get(position)
holder.expandableLayout.setListener(object : ExpandableLayoutListenerAdapter() {
override fun onPreOpen() {
createRotateAnimator(holder.buttonLayout, 0f, 180f).start()
expandState.put(position, true)
}
override fun onPreClose() {
createRotateAnimator(holder.buttonLayout, 180f, 0f).start()
expandState.put(position, false)
}
})
holder.buttonLayout.rotation = if (expandState.get(position)) 180f else 0f
holder.buttonLayout.setOnClickListener { onClickButton(holder.expandableLayout) }
}
private fun onClickButton(expandableLayout: ExpandableLayout) {
expandableLayout.toggle()
}
override fun getItemCount(): Int {
return data.size
}
class ExpandableViewHolder(v: View) : RecyclerView.ViewHolder(v) {
var title: TextView
var description: TextView
var buttonLayout: RelativeLayout
var expandableLayout: ExpandableLinearLayout
init {
title = v.findViewById(R.id.titleText) as TextView
description = v.findViewById(R.id.descriptionText) as TextView
buttonLayout = v.findViewById(R.id.button) as RelativeLayout
expandableLayout = v.findViewById(R.id.expandableLayout) as ExpandableLinearLayout
}
}
fun createRotateAnimator(target: View, from: Float, to: Float): ObjectAnimator {
val animator = ObjectAnimator.ofFloat(target, "rotation", from, to)
animator.duration = DURATION
animator.interpolator = Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR)
return animator
}
}
}
|
apache-2.0
|
31d60297e4967bd0c7d25578dcf2b498
| 45.385135 | 133 | 0.673951 | 5.017544 | false | false | false | false |
abigpotostew/easypolitics
|
db/src/main/kotlin/bz/stewart/bracken/db/leglislators/LegislatorRuntime.kt
|
1
|
4109
|
package bz.stewart.bracken.db.leglislators
import bz.stewart.bracken.db.DbRuntime
import bz.stewart.bracken.db.database.ClientBuilder
import bz.stewart.bracken.db.database.Database
import bz.stewart.bracken.db.database.DatabaseClient
import bz.stewart.bracken.db.database.index.SyncIndex
import bz.stewart.bracken.db.database.mongo.AbstractMongoDb
import bz.stewart.bracken.db.database.mongo.CollectionWriter
import bz.stewart.bracken.db.database.mongo.emptyDatabaseWriter
import bz.stewart.bracken.db.leglislators.data.LegislatorData
import bz.stewart.bracken.db.leglislators.data.SocialMapper
import bz.stewart.bracken.db.leglislators.index.LegislatorIndexDefinition
import com.mongodb.MongoClient
import mu.KLogging
import org.litote.kmongo.find
import org.litote.kmongo.formatJson
import org.litote.kmongo.json
class LegislatorRuntime(private val args: LegislatorArguments) : DbRuntime {
companion object : KLogging()
private var db: LegislatorCreateDb? = null
override fun validateArgs() {
return //TODO
}
override fun run() {
val writer: CollectionWriter<LegislatorData, AbstractMongoDb<LegislatorData>> = if (args.testMode) {
emptyDatabaseWriter<LegislatorData, Database<LegislatorData>>()
} else {
LegislatorDbWriter()
}
val client = getClient()
db = LegislatorCreateDb(client, writer)
val runDb = db!!
val socialMapper = if (args.socialFile != null) {
SocialMapper(ParserSocialJson().parseData(
args.socialFile!!.toPath()))
} else {
SocialMapper(emptyList())
}
runDb.use {
executeCurrentLegislators(socialMapper)
}
runDb.use {
indexCollection(runDb)
}
if (args.testMode == true) {
logger.info { "Completed database update. Test mode enabled. No data was updated." }
} else {
logger.info { "Completed legislators database update." }
}
}
private fun executeCurrentLegislators(socialMapper: SocialMapper) {
val collName = db?.getCollectionName() ?: "legislators"
val db: LegislatorCreateDb = db!!
db.openDatabase()
val writer = db.getWriter()
if (this.args.resetMode) {
writer.before(db)
writer.drop(collName, db)
logger.info { "Dropped collection '$collName' in preparation to load fresh data." }
writer.after(db)
}
//parse data
val legislators = ParserLegislatorJson().parseData(args.files.map { it.toPath() })
socialMapper.associateSocialToPeople(legislators)
//write to database
writer.before(db)
for (legislator in legislators) {
writeDataIfNecessary(legislator, writer, collName, db)
}
writer.after(db)
logger.info { "Successfully wrote ${legislators.size} current legislators to database." }
}
private fun indexCollection(db: LegislatorCreateDb) {
SyncIndex(db, { LegislatorIndexDefinition(it) }).doSync(this.args.testMode)
}
private fun getClient(): DatabaseClient<MongoClient> {
return ClientBuilder(this.args.dbName,
this.args.hostname,
this.args.port,
this.args.username,
this.args.password).createClient()
}
private fun writeDataIfNecessary(legislatorData: LegislatorData,
writer: CollectionWriter<LegislatorData, AbstractMongoDb<LegislatorData>>,
collName: String,
db: LegislatorCreateDb) {
var existing: LegislatorData? = null
db.queryCollection(collName, {
val id = legislatorData.id.bioguide.json
val found = find(
"{\"id.buiguide\":$id }".formatJson())
existing = found.first()
})
if (existing == null || (existing != null && existing != legislatorData)) {
writer.write(legislatorData, collName, db)
}
}
}
|
apache-2.0
|
e92bf547c6a72a7288ce7c6b99b7ed20
| 34.431034 | 111 | 0.641032 | 4.352754 | false | false | false | false |
k9mail/k-9
|
app/core/src/main/java/com/fsck/k9/search/AccountSearchConditions.kt
|
2
|
4256
|
package com.fsck.k9.search
import com.fsck.k9.Account
import com.fsck.k9.Account.FolderMode
import com.fsck.k9.mail.FolderClass
import com.fsck.k9.search.SearchSpecification.Attribute
import com.fsck.k9.search.SearchSpecification.SearchCondition
import com.fsck.k9.search.SearchSpecification.SearchField
class AccountSearchConditions {
/**
* Modify the supplied [LocalSearch] instance to limit the search to displayable folders.
*
* This method uses the current folder display mode to decide what folders to include/exclude.
*
* @param search
* The `LocalSearch` instance to modify.
*
* @see .getFolderDisplayMode
*/
fun limitToDisplayableFolders(account: Account, search: LocalSearch) {
val displayMode = account.folderDisplayMode
when (displayMode) {
FolderMode.FIRST_CLASS -> {
// Count messages in the INBOX and non-special first class folders
search.and(SearchField.DISPLAY_CLASS, FolderClass.FIRST_CLASS.name, Attribute.EQUALS)
}
FolderMode.FIRST_AND_SECOND_CLASS -> {
// Count messages in the INBOX and non-special first and second class folders
search.and(SearchField.DISPLAY_CLASS, FolderClass.FIRST_CLASS.name, Attribute.EQUALS)
// TODO: Create a proper interface for creating arbitrary condition trees
val searchCondition = SearchCondition(
SearchField.DISPLAY_CLASS, Attribute.EQUALS, FolderClass.SECOND_CLASS.name
)
val root = search.conditions
if (root.mRight != null) {
root.mRight.or(searchCondition)
} else {
search.or(searchCondition)
}
}
FolderMode.NOT_SECOND_CLASS -> {
// Count messages in the INBOX and non-special non-second-class folders
search.and(SearchField.DISPLAY_CLASS, FolderClass.SECOND_CLASS.name, Attribute.NOT_EQUALS)
}
FolderMode.ALL, FolderMode.NONE -> {
// Count messages in the INBOX and non-special folders
}
}
}
/**
* Modify the supplied [LocalSearch] instance to exclude special folders.
*
* Currently the following folders are excluded:
*
* * Trash
* * Drafts
* * Spam
* * Outbox
* * Sent
*
* The Inbox will always be included even if one of the special folders is configured to point
* to the Inbox.
*
* @param search
* The `LocalSearch` instance to modify.
*/
fun excludeSpecialFolders(account: Account, search: LocalSearch) {
excludeSpecialFolder(search, account.trashFolderId)
excludeSpecialFolder(search, account.draftsFolderId)
excludeSpecialFolder(search, account.spamFolderId)
excludeSpecialFolder(search, account.outboxFolderId)
excludeSpecialFolder(search, account.sentFolderId)
account.inboxFolderId?.let { inboxFolderId ->
search.or(SearchCondition(SearchField.FOLDER, Attribute.EQUALS, inboxFolderId.toString()))
}
}
/**
* Modify the supplied [LocalSearch] instance to exclude "unwanted" folders.
*
* Currently the following folders are excluded:
*
* * Trash
* * Spam
* * Outbox
*
* The Inbox will always be included even if one of the special folders is configured to point
* to the Inbox.
*
* @param search
* The `LocalSearch` instance to modify.
*/
fun excludeUnwantedFolders(account: Account, search: LocalSearch) {
excludeSpecialFolder(search, account.trashFolderId)
excludeSpecialFolder(search, account.spamFolderId)
excludeSpecialFolder(search, account.outboxFolderId)
account.inboxFolderId?.let { inboxFolderId ->
search.or(SearchCondition(SearchField.FOLDER, Attribute.EQUALS, inboxFolderId.toString()))
}
}
private fun excludeSpecialFolder(search: LocalSearch, folderId: Long?) {
if (folderId != null) {
search.and(SearchField.FOLDER, folderId.toString(), Attribute.NOT_EQUALS)
}
}
}
|
apache-2.0
|
8dd587d3528049232c843970a8d20312
| 37.342342 | 106 | 0.639803 | 4.728889 | false | false | false | false |
abigpotostew/easypolitics
|
rest/src/main/kotlin/bz/stewart/bracken/rest/RestServiceRunner.kt
|
1
|
2238
|
package bz.stewart.bracken.rest
import bz.stewart.bracken.rest.conf.RuntimeContext
import bz.stewart.bracken.rest.data.bills.BillDAO
import bz.stewart.bracken.rest.http.CorsFilter
import bz.stewart.bracken.rest.route.ExecuteRoute
import bz.stewart.bracken.rest.route.RouteContextBuilder
import bz.stewart.bracken.rest.route.StandardRouteContext
import bz.stewart.bracken.rest.service.HomeService
import bz.stewart.bracken.rest.service.MultipleBillService
import bz.stewart.bracken.rest.service.SingleBillService
import bz.stewart.bracken.shared.rest.RestServices
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import mu.KLogging
import spark.Request
import spark.Spark
import spark.Spark.port
class RestServiceRunner(context: RuntimeContext) {
companion object : KLogging()
private val runtimeContext = context
private val mapper = jacksonObjectMapper()
private val billDao: BillDAO = BillDAO(context.client)
fun run() {
port(this.runtimeContext.servingPort)
CorsFilter().apply()
logger.info { "Starting Easypolitics Rest, serving on port ${this.runtimeContext.servingPort}" }
val routeContextCreator = RouteContextBuilder(this.mapper,this.billDao,logger)
Spark.path("/api/v1", {
Spark.get(RestServices.HOME.path) {req, response ->
val routeContext = routeContextCreator.build(req, response)
ExecuteRoute(HomeService()).execute(routeContext)
}
Spark.get(RestServices.MULTI_BILLS.path) { req, response ->
val routeContext = routeContextCreator.build(req, response)
ExecuteRoute(MultipleBillService()).execute(routeContext)
}
Spark.get(RestServices.SINGLE_BILL.path) { req, response ->
val routeContext = routeContextCreator.build(req, response)
ExecuteRoute(SingleBillService()).execute(routeContext)
}
})
Spark.get(RestServices.HOME.path) {req, response ->
val routeContext = routeContextCreator.build(req, response)
ExecuteRoute(HomeService()).execute(routeContext)
}
}
}
fun Request.qp(key: String): String? = this.queryParams(key)
|
apache-2.0
|
368546caecccf5505e8d1ef0b067bd3b
| 38.982143 | 104 | 0.713137 | 4.167598 | false | false | false | false |
Yubico/yubioath-desktop
|
android/app/src/test/java/com/yubico/authenticator/yubikit/SkyHelperTest.kt
|
1
|
8338
|
/*
* Copyright (C) 2022 Yubico.
*
* 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.yubico.authenticator.yubikit
import android.hardware.usb.UsbDevice
import com.yubico.authenticator.SdkVersion
import com.yubico.authenticator.TestUtil
import com.yubico.authenticator.device.Version
import com.yubico.yubikit.android.transport.nfc.NfcYubiKeyDevice
import com.yubico.yubikit.android.transport.usb.UsbYubiKeyDevice
import com.yubico.yubikit.core.UsbPid
import org.junit.Assert.*
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.`when`
class SkyHelperTest {
@Test
fun `passing NfcYubiKeyDevice will throw`() {
assertThrows(IllegalArgumentException::class.java) {
SkyHelper.getDeviceInfo(mock(NfcYubiKeyDevice::class.java))
}
}
@Test
fun `supports three specific UsbPids`() {
for (pid in UsbPid.values()) {
val ykDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(pid)
}
if (pid in listOf(UsbPid.YK4_FIDO, UsbPid.SKY_FIDO, UsbPid.NEO_FIDO)) {
// these will not throw
assertNotNull(SkyHelper.getDeviceInfo(ykDevice))
} else {
// all other will throw
assertThrows(IllegalArgumentException::class.java) {
SkyHelper.getDeviceInfo(ykDevice)
}
}
}
}
@Test
fun `handles NEO_FIDO versions`() {
TestUtil.mockSdkInt(23)
val ykDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.NEO_FIDO)
}
`when`(ykDevice.usbDevice.version).thenReturn("3.00")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(Version(3, 0, 0), it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("3.47")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(Version(3, 4, 7), it.version)
}
// lower than 3 should return 0.0.0
`when`(ykDevice.usbDevice.version).thenReturn("2.10")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
// greater or equal 4.0.0 should return 0.0.0
`when`(ykDevice.usbDevice.version).thenReturn("4.00")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.37")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
}
@Test
fun `handles SKY_FIDO versions`() {
TestUtil.mockSdkInt(23)
val ykDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.SKY_FIDO)
}
`when`(ykDevice.usbDevice.version).thenReturn("3.00")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(Version(3, 0, 0), it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("3.47")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(Version(3, 4, 7), it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.00")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(Version(4, 0, 0), it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.37")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(Version(4, 3, 7), it.version)
}
// lower than 3 should return 0.0.0
`when`(ykDevice.usbDevice.version).thenReturn("2.10")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
}
@Test
fun `handles YK4_FIDO versions`() {
TestUtil.mockSdkInt(23)
val ykDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.YK4_FIDO)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.00")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(Version(4, 0, 0), it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.37")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(Version(4, 3, 7), it.version)
}
// lower than 4 should return 0.0.0
`when`(ykDevice.usbDevice.version).thenReturn("3.47")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
}
@Test
fun `returns VERSION_0 for older APIs`() {
// below API 23, there is no UsbDevice.version
// therefore we expect deviceInfo to have VERSION_0
// for every FIDO key
TestUtil.mockSdkInt(22)
val neoFidoDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.NEO_FIDO)
}
`when`(neoFidoDevice.usbDevice.version).thenReturn("3.47") // valid NEO_FIDO version
SkyHelper.getDeviceInfo(neoFidoDevice).also {
assertEquals(VERSION_0, it.version)
}
val skyFidoDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.SKY_FIDO)
}
`when`(skyFidoDevice.usbDevice.version).thenReturn("3.47") // valid SKY_FIDO version
SkyHelper.getDeviceInfo(skyFidoDevice).also {
assertEquals(VERSION_0, it.version)
}
val yk4FidoDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.YK4_FIDO)
}
`when`(yk4FidoDevice.usbDevice.version).thenReturn("4.37") // valid YK4_FIDO version
SkyHelper.getDeviceInfo(yk4FidoDevice).also {
assertEquals(VERSION_0, it.version)
}
}
@Test
fun `returns VERSION_0 for invalid input`() {
val ykDevice = getUsbYubiKeyDeviceMock().also {
`when`(it.pid).thenReturn(UsbPid.SKY_FIDO)
}
`when`(ykDevice.usbDevice.version).thenReturn("")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("yubico")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("4")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.0")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
`when`(ykDevice.usbDevice.version).thenReturn("4.0.0")
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(VERSION_0, it.version)
}
}
@Test
fun `returns default product name`() {
val ykDevice = getUsbYubiKeyDeviceMock()
`when`(ykDevice.pid).thenReturn(UsbPid.SKY_FIDO)
`when`(ykDevice.usbDevice.version).thenReturn("5.50")
`when`(ykDevice.usbDevice.productName).thenReturn(null)
SkyHelper.getDeviceInfo(ykDevice).also {
assertEquals(it.name, "YubiKey Security Key")
}
}
companion object {
fun getUsbYubiKeyDeviceMock(): UsbYubiKeyDevice = mock(UsbYubiKeyDevice::class.java).also {
`when`(it.pid).thenReturn(UsbPid.YKS_OTP)
`when`(it.usbDevice).thenReturn(mock(UsbDevice::class.java))
`when`(it.usbDevice.productName).thenReturn("")
`when`(it.usbDevice.version).thenReturn("")
}
private val VERSION_0 = Version(0, 0, 0)
}
}
|
apache-2.0
|
21d45b0a115b1f82869d37999491c23e
| 31.830709 | 99 | 0.621972 | 3.772851 | false | true | false | false |
Maccimo/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt
|
1
|
19749
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations
import com.intellij.ide.IdeDeprecatedMessagesBundle
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.util.EditorHelper
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor
import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassHandler
import com.intellij.refactoring.rename.RenameUtil
import com.intellij.refactoring.util.NonCodeUsageInfo
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.refactoring.util.TextOccurrencesUtil
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import com.intellij.usageView.UsageViewUtil
import com.intellij.util.IncorrectOperationException
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.containers.HashingStrategy
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet
import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests
import org.jetbrains.kotlin.idea.core.deleteSingle
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory
import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit
import org.jetbrains.kotlin.idea.refactoring.move.*
import org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories.MoveKotlinClassHandler
import org.jetbrains.kotlin.idea.search.projectScope
import org.jetbrains.kotlin.idea.search.restrictByFileType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.utils.ifEmpty
import org.jetbrains.kotlin.utils.keysToMap
import kotlin.math.max
import kotlin.math.min
interface Mover : (KtNamedDeclaration, KtElement) -> KtNamedDeclaration {
object Default : Mover {
override fun invoke(originalElement: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration {
return when (targetContainer) {
is KtFile -> {
val declarationContainer: KtElement =
if (targetContainer.isScript()) targetContainer.script!!.blockExpression else targetContainer
declarationContainer.add(originalElement) as KtNamedDeclaration
}
is KtClassOrObject -> targetContainer.addDeclaration(originalElement)
else -> error("Unexpected element: ${targetContainer.getElementTextWithContext()}")
}.apply {
val container = originalElement.containingClassOrObject
if (container is KtObjectDeclaration &&
container.isCompanion() &&
container.declarations.singleOrNull() == originalElement &&
KotlinFindUsagesHandlerFactory(container.project).createFindUsagesHandler(container, false)
.findReferencesToHighlight(container, LocalSearchScope(container.containingFile)).isEmpty()
) {
container.deleteSingle()
} else {
originalElement.deleteSingle()
}
}
}
}
}
sealed class MoveSource {
abstract val elementsToMove: Collection<KtNamedDeclaration>
class Elements(override val elementsToMove: Collection<KtNamedDeclaration>) : MoveSource()
class File(val file: KtFile) : MoveSource() {
override val elementsToMove: Collection<KtNamedDeclaration>
get() = file.declarations.filterIsInstance<KtNamedDeclaration>()
}
}
fun MoveSource(declaration: KtNamedDeclaration) = MoveSource.Elements(listOf(declaration))
fun MoveSource(declarations: Collection<KtNamedDeclaration>) = MoveSource.Elements(declarations)
fun MoveSource(file: KtFile) = MoveSource.File(file)
class MoveDeclarationsDescriptor @JvmOverloads constructor(
val project: Project,
val moveSource: MoveSource,
val moveTarget: KotlinMoveTarget,
val delegate: MoveDeclarationsDelegate,
val searchInCommentsAndStrings: Boolean = true,
val searchInNonCode: Boolean = true,
val deleteSourceFiles: Boolean = false,
val moveCallback: MoveCallback? = null,
val openInEditor: Boolean = false,
val allElementsToMove: List<PsiElement>? = null,
val analyzeConflicts: Boolean = true,
val searchReferences: Boolean = true
)
class ConflictUsageInfo(element: PsiElement, val messages: Collection<String>) : UsageInfo(element)
private object ElementHashingStrategy : HashingStrategy<PsiElement> {
override fun equals(e1: PsiElement?, e2: PsiElement?): Boolean {
if (e1 === e2) return true
// Name should be enough to distinguish different light elements based on the same original declaration
if (e1 is KtLightDeclaration<*, *> && e2 is KtLightDeclaration<*, *>) {
return e1.kotlinOrigin == e2.kotlinOrigin && e1.name == e2.name
}
return false
}
override fun hashCode(e: PsiElement?): Int {
return when (e) {
null -> 0
is KtLightDeclaration<*, *> -> (e.kotlinOrigin?.hashCode() ?: 0) * 31 + (e.name?.hashCode() ?: 0)
else -> e.hashCode()
}
}
}
class MoveKotlinDeclarationsProcessor(
val descriptor: MoveDeclarationsDescriptor,
val mover: Mover = Mover.Default,
private val throwOnConflicts: Boolean = false
) : BaseRefactoringProcessor(descriptor.project) {
companion object {
const val REFACTORING_ID = "move.kotlin.declarations"
}
val project get() = descriptor.project
private var nonCodeUsages: Array<NonCodeUsageInfo>? = null
private val moveEntireFile = descriptor.moveSource is MoveSource.File
private val elementsToMove = descriptor.moveSource.elementsToMove.filter { e ->
e.parent != descriptor.moveTarget.getTargetPsiIfExists(e)
}
private val kotlinToLightElementsBySourceFile = elementsToMove
.groupBy { it.containingKtFile }
.mapValues { it.value.keysToMap { declaration -> declaration.toLightElements().ifEmpty { listOf(declaration) } } }
private val conflicts = MultiMap<PsiElement, String>()
override fun getRefactoringId() = REFACTORING_ID
override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor {
val targetContainerFqName = descriptor.moveTarget.targetContainerFqName?.let {
if (it.isRoot) IdeDeprecatedMessagesBundle.message("default.package.presentable.name") else it.asString()
} ?: IdeDeprecatedMessagesBundle.message("default.package.presentable.name")
return MoveMultipleElementsViewDescriptor(elementsToMove.toTypedArray(), targetContainerFqName)
}
fun getConflictsAsUsages(): List<UsageInfo> = conflicts.entrySet().map { ConflictUsageInfo(it.key, it.value) }
public override fun findUsages(): Array<UsageInfo> {
if (!descriptor.searchReferences || elementsToMove.isEmpty()) return UsageInfo.EMPTY_ARRAY
val newContainerName = descriptor.moveTarget.targetContainerFqName?.asString() ?: ""
fun getSearchScope(element: PsiElement): GlobalSearchScope? {
val projectScope = project.projectScope()
val ktDeclaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return projectScope
if (ktDeclaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) return projectScope
val moveTarget = descriptor.moveTarget
val (oldContainer, newContainer) = descriptor.delegate.getContainerChangeInfo(ktDeclaration, moveTarget)
val targetModule = moveTarget.getTargetModule(project) ?: return projectScope
if (oldContainer != newContainer || ktDeclaration.module != targetModule) return projectScope
// Check if facade class may change
if (newContainer is ContainerInfo.Package) {
val javaScope = projectScope.restrictByFileType(JavaFileType.INSTANCE)
val currentFile = ktDeclaration.containingKtFile
val newFile = when (moveTarget) {
is KotlinMoveTargetForExistingElement -> moveTarget.targetElement as? KtFile ?: return null
is KotlinMoveTargetForDeferredFile -> return javaScope
else -> return null
}
val currentFacade = currentFile.findFacadeClass()
val newFacade = newFile.findFacadeClass()
return if (currentFacade?.qualifiedName != newFacade?.qualifiedName) javaScope else null
}
return null
}
fun UsageInfo.intersectsWith(usage: UsageInfo): Boolean {
if (element?.containingFile != usage.element?.containingFile) return false
val firstSegment = segment ?: return false
val secondSegment = usage.segment ?: return false
return max(firstSegment.startOffset, secondSegment.startOffset) <= min(firstSegment.endOffset, secondSegment.endOffset)
}
fun collectUsages(kotlinToLightElements: Map<KtNamedDeclaration, List<PsiNamedElement>>, result: MutableCollection<UsageInfo>) {
kotlinToLightElements.values.flatten().flatMapTo(result) { lightElement ->
val searchScope = getSearchScope(lightElement) ?: return@flatMapTo emptyList()
val elementName = lightElement.name ?: return@flatMapTo emptyList()
val newFqName = StringUtil.getQualifiedName(newContainerName, elementName)
val foundReferences = HashSet<PsiReference>()
val results = ReferencesSearch
.search(lightElement, searchScope)
.mapNotNullTo(ArrayList()) { ref ->
if (foundReferences.add(ref) && elementsToMove.none { it.isAncestor(ref.element) }) {
createMoveUsageInfoIfPossible(ref, lightElement, addImportToOriginalFile = true, isInternal = false)
} else null
}
val name = lightElement.getKotlinFqName()?.quoteIfNeeded()?.asString()
if (name != null) {
fun searchForKotlinNameUsages(results: ArrayList<UsageInfo>) {
TextOccurrencesUtil.findNonCodeUsages(
lightElement,
searchScope,
name,
descriptor.searchInCommentsAndStrings,
descriptor.searchInNonCode,
FqName(newFqName).quoteIfNeeded().asString(),
results
)
}
val facadeContainer = lightElement.parent as? KtLightClassForFacade
if (facadeContainer != null) {
val oldFqNameWithFacade = StringUtil.getQualifiedName(facadeContainer.qualifiedName, elementName)
val newFqNameWithFacade = StringUtil.getQualifiedName(
StringUtil.getQualifiedName(newContainerName, facadeContainer.name),
elementName
)
TextOccurrencesUtil.findNonCodeUsages(
lightElement,
searchScope,
oldFqNameWithFacade,
descriptor.searchInCommentsAndStrings,
descriptor.searchInNonCode,
FqName(newFqNameWithFacade).quoteIfNeeded().asString(),
results
)
ArrayList<UsageInfo>().also { searchForKotlinNameUsages(it) }.forEach { kotlinNonCodeUsage ->
if (results.none { it.intersectsWith(kotlinNonCodeUsage) }) {
results.add(kotlinNonCodeUsage)
}
}
} else {
searchForKotlinNameUsages(results)
}
}
MoveClassHandler.EP_NAME.extensions.filter { it !is MoveKotlinClassHandler }.forEach { handler ->
handler.preprocessUsages(results)
}
results
}
}
val usages = ArrayList<UsageInfo>()
val conflictChecker = MoveConflictChecker(
project,
elementsToMove,
descriptor.moveTarget,
elementsToMove.first(),
allElementsToMove = descriptor.allElementsToMove
)
for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) {
val internalUsages = LinkedHashSet<UsageInfo>()
val externalUsages = LinkedHashSet<UsageInfo>()
if (moveEntireFile) {
val changeInfo = ContainerChangeInfo(
ContainerInfo.Package(sourceFile.packageFqName),
descriptor.moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage
)
internalUsages += sourceFile.getInternalReferencesToUpdateOnPackageNameChange(changeInfo)
} else {
kotlinToLightElements.keys.forEach {
val packageNameInfo = descriptor.delegate.getContainerChangeInfo(it, descriptor.moveTarget)
internalUsages += it.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo)
}
}
internalUsages += descriptor.delegate.findInternalUsages(descriptor)
collectUsages(kotlinToLightElements, externalUsages)
if (descriptor.analyzeConflicts) {
conflictChecker.checkAllConflicts(externalUsages, internalUsages, conflicts)
descriptor.delegate.collectConflicts(descriptor, internalUsages, conflicts)
}
usages += internalUsages
usages += externalUsages
}
return UsageViewUtil.removeDuplicatedUsages(usages.toTypedArray())
}
override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
return showConflicts(conflicts, refUsages.get())
}
override fun showConflicts(conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo>?): Boolean {
if (throwOnConflicts && !conflicts.isEmpty) throw RefactoringConflictsFoundException()
return super.showConflicts(conflicts, usages)
}
override fun performRefactoring(usages: Array<out UsageInfo>) = doPerformRefactoring(usages.toList())
internal fun doPerformRefactoring(usages: List<UsageInfo>) {
fun moveDeclaration(declaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): KtNamedDeclaration {
val targetContainer = moveTarget.getOrCreateTargetPsi(declaration)
descriptor.delegate.preprocessDeclaration(descriptor, declaration)
if (moveEntireFile) return declaration
return mover(declaration, targetContainer).apply {
addToBeShortenedDescendantsToWaitingSet()
}
}
val (oldInternalUsages, externalUsages) = usages.partition { it is KotlinMoveUsage && it.isInternal }
val newInternalUsages = ArrayList<UsageInfo>()
markInternalUsages(oldInternalUsages)
val usagesToProcess = ArrayList(externalUsages)
try {
descriptor.delegate.preprocessUsages(descriptor, usages)
val oldToNewElementsMapping = CollectionFactory.createCustomHashingStrategyMap<PsiElement, PsiElement>(ElementHashingStrategy)
val newDeclarations = ArrayList<KtNamedDeclaration>()
for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) {
for ((oldDeclaration, oldLightElements) in kotlinToLightElements) {
val elementListener = transaction?.getElementListener(oldDeclaration)
val newDeclaration = moveDeclaration(oldDeclaration, descriptor.moveTarget)
newDeclarations += newDeclaration
oldToNewElementsMapping[oldDeclaration] = newDeclaration
oldToNewElementsMapping[sourceFile] = newDeclaration.containingKtFile
elementListener?.elementMoved(newDeclaration)
for ((oldElement, newElement) in oldLightElements.asSequence().zip(newDeclaration.toLightElements().asSequence())) {
oldToNewElementsMapping[oldElement] = newElement
}
if (descriptor.openInEditor) {
EditorHelper.openInEditor(newDeclaration)
}
}
if (descriptor.deleteSourceFiles && sourceFile.declarations.isEmpty()) {
sourceFile.delete()
}
}
val internalUsageScopes: List<KtElement> = if (moveEntireFile) {
newDeclarations.asSequence().map { it.containingKtFile }.distinct().toList()
} else {
newDeclarations
}
internalUsageScopes.forEach { newInternalUsages += restoreInternalUsages(it, oldToNewElementsMapping) }
usagesToProcess += newInternalUsages
nonCodeUsages = postProcessMoveUsages(usagesToProcess, oldToNewElementsMapping).toTypedArray()
performDelayedRefactoringRequests(project)
} catch (e: IncorrectOperationException) {
nonCodeUsages = null
RefactoringUIUtil.processIncorrectOperation(myProject, e)
} finally {
cleanUpInternalUsages(newInternalUsages + oldInternalUsages)
}
}
override fun performPsiSpoilingRefactoring() {
nonCodeUsages?.let { nonCodeUsages -> RenameUtil.renameNonCodeUsages(myProject, nonCodeUsages) }
descriptor.moveCallback?.refactoringCompleted()
}
fun execute(usages: List<UsageInfo>) {
execute(usages.toTypedArray())
}
override fun doRun() {
try {
super.doRun()
} finally {
broadcastRefactoringExit(myProject, refactoringId)
}
}
override fun getCommandName(): String = KotlinBundle.message("command.move.declarations")
}
|
apache-2.0
|
b80ed8450d24a9f94c6969731135e5cb
| 47.286064 | 138 | 0.672945 | 5.867201 | false | false | false | false |
PolymerLabs/arcs
|
javatests/arcs/core/analysis/RecipeGraphFixpointIteratorTest.kt
|
1
|
10204
|
package arcs.core.analysis
import arcs.core.data.Annotation
import arcs.core.data.EntityType
import arcs.core.data.FieldType
import arcs.core.data.HandleConnectionSpec
import arcs.core.data.HandleMode
import arcs.core.data.ParticleSpec
import arcs.core.data.Recipe
import arcs.core.data.Schema
import arcs.core.data.SchemaFields
import arcs.core.data.SchemaName
import arcs.core.data.TypeVariable
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
/** A simple Fixpoint iterator for the purposes of testing. */
class TestAnalyzer(
val startNames: Set<String>
) : RecipeGraphFixpointIterator<AbstractSet<String>>(AbstractSet.getBottom<String>()) {
override fun getInitialValues(graph: RecipeGraph) = graph.nodes.filter {
startNames.contains(it.debugName)
}.associateWith {
AbstractSet<String>(setOf())
}
override fun nodeTransfer(handle: Recipe.Handle, input: AbstractSet<String>) =
input.set?.let { AbstractSet<String>(it + "h:${handle.name}") } ?: input
override fun nodeTransfer(particle: Recipe.Particle, input: AbstractSet<String>) =
input.set?.let { AbstractSet<String>(it + "p:${particle.spec.name}") } ?: input
override fun edgeTransfer(
fromHandle: Recipe.Handle,
toParticle: Recipe.Particle,
spec: HandleConnectionSpec,
input: AbstractSet<String>
) = input.set?.let {
AbstractSet<String>(it + "h:${fromHandle.name} -> p:${toParticle.spec.name}")
} ?: input
override fun edgeTransfer(
fromParticle: Recipe.Particle,
toHandle: Recipe.Handle,
spec: HandleConnectionSpec,
input: AbstractSet<String>
) = input.set?.let {
AbstractSet<String>(it + "p:${fromParticle.spec.name} -> h:${toHandle.name}")
} ?: input
override fun edgeTransfer(
fromHandle: Recipe.Handle,
toHandle: Recipe.Handle,
spec: RecipeGraph.JoinSpec,
input: AbstractSet<String>
) = input.set?.let {
AbstractSet<String>(it + "h:${fromHandle.name} -> h:${toHandle.name}")
} ?: input
}
@RunWith(JUnit4::class)
class RecipeGraphFixpointIteratorTest {
private val thing = Recipe.Handle("thing", Recipe.Handle.Fate.CREATE, TypeVariable("thing"))
private val thingType = EntityType(
Schema(
names = setOf(SchemaName("Thing")),
fields = SchemaFields(
singletons = mapOf("name" to FieldType.Text),
collections = emptyMap()
),
hash = ""
)
)
private val name = Recipe.Handle("name", Recipe.Handle.Fate.CREATE, TypeVariable("name"))
private val nameType = EntityType(
Schema(
names = setOf(SchemaName("Name")),
fields = SchemaFields(
singletons = mapOf("fullname" to FieldType.Text),
collections = emptyMap()
),
hash = ""
)
)
private val readConnection = HandleConnectionSpec("r", HandleMode.Read, TypeVariable("r"))
private val writeConnection = HandleConnectionSpec("w", HandleMode.Write, TypeVariable("w"))
private val readerSpec = ParticleSpec(
"Reader",
listOf(readConnection).associateBy { it.name },
"ReaderLocation"
)
private val writerSpec = ParticleSpec(
"Writer",
listOf(writeConnection).associateBy { it.name },
"WriterLocation"
)
private val anotherWriterSpec = ParticleSpec(
"AnotherWriter",
listOf(writeConnection).associateBy { it.name },
"WriterLocation"
)
private val readerParticle = Recipe.Particle(
readerSpec,
listOf(Recipe.Particle.HandleConnection(readConnection, thing, thingType))
)
private val writerParticle = Recipe.Particle(
writerSpec,
listOf(Recipe.Particle.HandleConnection(writeConnection, thing, nameType))
)
private val anotherWriterParticle = Recipe.Particle(
anotherWriterSpec,
listOf(Recipe.Particle.HandleConnection(writeConnection, thing, thingType))
)
private fun createGraph(
name: String,
handles: List<Recipe.Handle>,
particles: List<Recipe.Particle>
): RecipeGraph {
return RecipeGraph(
Recipe(
name,
handles.associateBy { it.name },
particles,
listOf(Annotation.createArcId("arcId"))
)
)
}
@Test
fun straightLineFlow() {
// [Writer] -> (thing) -> [Reader]
val graph = createGraph(
name = "StraightLine",
handles = listOf(thing),
particles = listOf(readerParticle, writerParticle)
)
val analyzer = TestAnalyzer(setOf("p:${writerParticle.spec.name}"))
val result = analyzer.computeFixpoint(graph)
with(result) {
assertThat(getValue(writerParticle).set).isEmpty()
assertThat(getValue(thing).set)
.containsExactly("p:Writer", "p:Writer -> h:thing")
assertThat(getValue(readerParticle).set)
.containsExactly(
"p:Writer",
"p:Writer -> h:thing",
"h:thing",
"h:thing -> p:Reader"
)
}
}
@Test
fun joinsFlow() {
// [Writer] ---------> (thing) -> [Reader]
// [AnotherWriter] ------^
val graph = createGraph(
name = "Join",
handles = listOf(thing),
particles = listOf(readerParticle, writerParticle, anotherWriterParticle)
)
val analyzer = TestAnalyzer(
setOf("p:${writerParticle.spec.name}", "p:${anotherWriterParticle.spec.name}")
)
val result = analyzer.computeFixpoint(graph)
with(result) {
assertThat(getValue(writerParticle).set).isEmpty()
assertThat(getValue(anotherWriterParticle).set).isEmpty()
assertThat(getValue(thing).set)
.containsExactly(
"p:Writer",
"p:AnotherWriter",
"p:Writer -> h:thing",
"p:AnotherWriter -> h:thing"
)
assertThat(getValue(readerParticle).set)
.containsExactly(
"p:Writer",
"p:AnotherWriter",
"p:Writer -> h:thing",
"p:AnotherWriter -> h:thing",
"h:thing",
"h:thing -> p:Reader"
)
}
}
@Test
fun unreachable() {
// [Writer] ----------> (thing) -> [Reader]
// [AnotherWriter] -------^
val graph = createGraph(
name = "Join",
handles = listOf(thing),
particles = listOf(readerParticle, writerParticle, anotherWriterParticle)
)
val analyzer = TestAnalyzer(setOf("p:${writerParticle.spec.name}"))
val result = analyzer.computeFixpoint(graph)
with(result) {
assertThat(getValue(writerParticle).set).isEmpty()
// AnotherWriter is unreachable as we don't mark it as a start node.
// Therefore, this should be bottom.
assertThat(getValue(anotherWriterParticle).isBottom).isTrue()
// AnotherWriter should not be in the following sets.
assertThat(getValue(thing).set)
.containsExactly(
"p:Writer",
"p:Writer -> h:thing"
)
assertThat(getValue(readerParticle).set)
.containsExactly(
"p:Writer",
"p:Writer -> h:thing",
"h:thing",
"h:thing -> p:Reader"
)
}
}
@Test
fun loops() {
// /---> [Reader]
// [Writer] -> (thing) -> [Recognizer] -> (name) -> [Tagger] -+
// ^-------------------------------------------+
val recognizerSpec = ParticleSpec(
"Recognizer",
listOf(writeConnection, readConnection).associateBy { it.name },
"RecognizerLocation"
)
val recognizerParticle = Recipe.Particle(
recognizerSpec,
listOf(
Recipe.Particle.HandleConnection(writeConnection, name, nameType),
Recipe.Particle.HandleConnection(readConnection, thing, thingType)
)
)
val taggerSpec = ParticleSpec(
"Tagger",
listOf(writeConnection, readConnection).associateBy { it.name },
"TaggerLocation"
)
val taggerParticle = Recipe.Particle(
taggerSpec,
listOf(
Recipe.Particle.HandleConnection(writeConnection, thing, thingType),
Recipe.Particle.HandleConnection(readConnection, name, nameType)
)
)
val graph = createGraph(
name = "Loop",
handles = listOf(thing, name),
particles = listOf(readerParticle, writerParticle, recognizerParticle, taggerParticle)
)
val analyzer = TestAnalyzer(setOf("p:${writerParticle.spec.name}"))
val result = analyzer.computeFixpoint(graph)
with(result) {
assertThat(getValue(writerParticle).set).isEmpty()
// The values for the nodes in the loop are all the same.
val expectedLoopValue = setOf(
"p:Writer",
"p:Recognizer",
"p:Tagger",
"h:thing",
"h:name",
"p:Writer -> h:thing",
"h:thing -> p:Recognizer",
"p:Recognizer -> h:name",
"h:name -> p:Tagger",
"p:Tagger -> h:thing"
)
assertThat(getValue(thing).set).isEqualTo(expectedLoopValue)
assertThat(getValue(recognizerParticle).set).isEqualTo(expectedLoopValue)
assertThat(getValue(name).set).isEqualTo(expectedLoopValue)
assertThat(getValue(taggerParticle).set).isEqualTo(expectedLoopValue)
assertThat(getValue(readerParticle).set)
.isEqualTo(expectedLoopValue + "h:thing -> p:Reader")
}
}
@Test
fun joinHandles() {
// recipe X
// thing: create
// name: create
// joined: join(thing, name)
// Reader
// r: reads joined
val joined = Recipe.Handle(
name = "joined",
fate = Recipe.Handle.Fate.JOIN,
type = TypeVariable("joined"),
associatedHandles = listOf(name, thing)
)
val joinReaderParticle = Recipe.Particle(
readerSpec,
listOf(Recipe.Particle.HandleConnection(readConnection, joined, thingType))
)
val graph = createGraph(
name = "JoinHandles",
handles = listOf(thing, name, joined),
particles = listOf(joinReaderParticle)
)
val analyzer = TestAnalyzer(setOf("h:thing", "h:name"))
val result = analyzer.computeFixpoint(graph)
print(result.toString())
with(result) {
assertThat(getValue(joinReaderParticle).set).containsExactly(
"h:thing",
"h:name",
"h:joined",
"h:name -> h:joined",
"h:thing -> h:joined",
"h:joined -> p:Reader"
)
}
}
}
|
bsd-3-clause
|
28677e25a27e736018e820d32693279e
| 30.109756 | 94 | 0.637691 | 4.124495 | false | false | false | false |
pyamsoft/pydroid
|
ui/src/main/java/com/pyamsoft/pydroid/ui/preference/Preferences.kt
|
1
|
6856
|
/*
* Copyright 2022 Peter Kenji Yamanaka
*
* 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.
*/
/** Allows Preferences to use VectorDrawables as icons on API < 21 */
package com.pyamsoft.pydroid.ui.preference
import androidx.annotation.CheckResult
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.vector.ImageVector
import java.util.UUID
/** A Preferences model */
public sealed class Preferences {
/** Key for rendering */
internal val renderKey: String = UUID.randomUUID().toString()
/** Name */
internal abstract val name: String
/** Enabled */
internal abstract val isEnabled: Boolean
/** Represents a single Preference item */
public abstract class Item protected constructor() : Preferences() {
/** Summary */
internal abstract val summary: String
/** Icon */
internal abstract val icon: ImageVector?
}
/** Represents a simple Preference item */
internal data class SimplePreference
internal constructor(
override val name: String,
override val isEnabled: Boolean,
override val summary: String,
override val icon: ImageVector?,
internal val onClick: (() -> Unit)?,
) : Item()
/** Represents a Custom Preference item */
internal data class CustomPreference
internal constructor(
override val isEnabled: Boolean,
override val name: String = "",
override val summary: String = "",
override val icon: ImageVector? = null,
internal val content: @Composable (isEnabled: Boolean) -> Unit,
) : Item()
/** Represents a In-App Purchase Preference item */
internal data class InAppPreference
internal constructor(
override val name: String,
override val isEnabled: Boolean,
override val summary: String,
override val icon: ImageVector?,
internal val onClick: (() -> Unit)?,
) : Item()
/** Represents a List Preference item */
internal data class ListPreference
internal constructor(
override val name: String,
override val isEnabled: Boolean,
override val summary: String,
override val icon: ImageVector?,
internal val value: String,
internal val entries: Map<String, String>,
internal val onPreferenceSelected: (key: String, value: String) -> Unit,
) : Item()
/** Represents a CheckBox Preference item */
internal data class CheckBoxPreference
internal constructor(
override val name: String,
override val isEnabled: Boolean,
override val summary: String,
override val icon: ImageVector?,
internal val checked: Boolean,
internal val onCheckedChanged: (checked: Boolean) -> Unit,
) : Item()
/** Represents a Switch Preference item */
internal data class SwitchPreference
internal constructor(
override val name: String,
override val isEnabled: Boolean,
override val summary: String,
override val icon: ImageVector?,
internal val checked: Boolean,
internal val onCheckedChanged: (checked: Boolean) -> Unit,
) : Item()
/** Represents a group of Preferences */
public data class Group
internal constructor(
override val name: String,
override val isEnabled: Boolean,
internal val preferences: List<Item>
) : Preferences()
}
/** Create a new Preference.Group */
@CheckResult
@JvmOverloads
public fun preferenceGroup(
name: String,
isEnabled: Boolean = true,
preferences: List<Preferences.Item>,
): Preferences.Group {
return Preferences.Group(
name = name,
isEnabled = isEnabled,
preferences = preferences,
)
}
/** Create a new Preference.CustomPreference */
@CheckResult
public fun customPreference(
isEnabled: Boolean = true,
content: @Composable (isEnabled: Boolean) -> Unit,
): Preferences.Item {
return Preferences.CustomPreference(
isEnabled = isEnabled,
content = content,
)
}
/** Create a new Preference.SimplePreference */
@CheckResult
@JvmOverloads
public fun preference(
name: String,
isEnabled: Boolean = true,
summary: String = "",
icon: ImageVector? = null,
onClick: (() -> Unit)? = null,
): Preferences.Item {
return Preferences.SimplePreference(
name = name,
isEnabled = isEnabled,
summary = summary,
icon = icon,
onClick = onClick,
)
}
/** Create a new Preference.InAppPreference */
@CheckResult
@JvmOverloads
public fun inAppPreference(
name: String,
isEnabled: Boolean = true,
summary: String = "",
icon: ImageVector? = null,
onClick: (() -> Unit)? = null,
): Preferences.Item {
return Preferences.InAppPreference(
name = name,
isEnabled = isEnabled,
summary = summary,
icon = icon,
onClick = onClick,
)
}
/** Create a new Preference.ListPreference */
@CheckResult
@JvmOverloads
public fun listPreference(
name: String,
value: String,
entries: Map<String, String>,
isEnabled: Boolean = true,
summary: String = "",
icon: ImageVector? = null,
onPreferenceSelected: (key: String, value: String) -> Unit,
): Preferences.Item {
return Preferences.ListPreference(
name = name,
isEnabled = isEnabled,
summary = summary,
value = value,
entries = entries,
icon = icon,
onPreferenceSelected = onPreferenceSelected,
)
}
/** Create a new Preference.CheckBoxPreference */
@CheckResult
@JvmOverloads
public fun checkBoxPreference(
name: String,
isEnabled: Boolean = true,
summary: String = "",
icon: ImageVector? = null,
checked: Boolean,
onCheckedChanged: (checked: Boolean) -> Unit,
): Preferences.Item {
return Preferences.CheckBoxPreference(
name = name,
isEnabled = isEnabled,
summary = summary,
icon = icon,
checked = checked,
onCheckedChanged = onCheckedChanged,
)
}
/** Create a new Preference.SwitchPreference */
@CheckResult
@JvmOverloads
public fun switchPreference(
name: String,
isEnabled: Boolean = true,
summary: String = "",
icon: ImageVector? = null,
checked: Boolean,
onCheckedChanged: (checked: Boolean) -> Unit,
): Preferences.Item {
return Preferences.SwitchPreference(
name = name,
isEnabled = isEnabled,
summary = summary,
icon = icon,
checked = checked,
onCheckedChanged = onCheckedChanged,
)
}
|
apache-2.0
|
8f8950329ca487c6e759ea552d29ee5f
| 26.645161 | 78 | 0.678676 | 4.679863 | false | false | false | false |
AcornUI/Acorn
|
acornui-core/src/main/kotlin/com/acornui/collection/ListUtils.kt
|
1
|
25264
|
/*
* 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", "ConvertTwoComparisonsToRangeCheck", "ReplaceRangeToWithUntil")
package com.acornui.collection
import com.acornui.math.clamp
import com.acornui.recycle.Clearable
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@Deprecated("Use kotlin copyInto methods", ReplaceWith("src.copyInto(dest, destPos, srcPos, length + destPos)"))
fun <E> arrayCopy(src: List<E>,
srcPos: Int,
dest: MutableList<E>,
destPos: Int = 0,
length: Int = src.size) {
if (destPos > srcPos) {
var destIndex = length + destPos - 1
for (i in srcPos + length - 1 downTo srcPos) {
dest.addOrSet(destIndex--, src[i])
}
} else {
var destIndex = destPos
for (i in srcPos..srcPos + length - 1) {
dest.addOrSet(destIndex++, src[i])
}
}
}
/**
* Copies this list or its subrange into the [destination] array and returns that array.
*
* It's allowed to pass the same array in the [destination] and even specify the subrange so that it overlaps with the
* destination range.
*
* @param destination the array to copy to.
* @param destinationOffset the position in the [destination] array to copy to, 0 by default.
* @param startIndex the beginning (inclusive) of the subrange to copy, 0 by default.
* @param endIndex the end (exclusive) of the subrange to copy, size of this array by default.
*
* @throws IndexOutOfBoundsException or [IllegalArgumentException] when [startIndex] or [endIndex] is out of range of
* this array indices or when `startIndex > endIndex`.
* @throws IndexOutOfBoundsException when [destinationOffset] < 0 or [destinationOffset] > destination.size
*
* Unlike [Array.copyInto] this can expand the size of [destination].
*
* @return the [destination] array.
*/
fun <T> List<T>.copyInto(destination: MutableList<T>, destinationOffset: Int = 0, startIndex: Int = 0, endIndex: Int = size): MutableList<T> {
if (startIndex == endIndex) return destination
if (endIndex < startIndex) throw IndexOutOfBoundsException("endIndex is expected to be greater than startIndex <$startIndex> but was: <$endIndex>")
if (endIndex > size || endIndex < 0) throw IndexOutOfBoundsException("endIndex is out of range")
if (startIndex >= size || startIndex < 0) throw IndexOutOfBoundsException("startIndex is out of range")
if (destinationOffset < 0 || destinationOffset > destination.size) throw IndexOutOfBoundsException("destinationOffset must be between 0 and destination size.")
val n = endIndex - startIndex
val destLastIndex = destinationOffset + n - 1
val destToSource = startIndex - destinationOffset
for (i in destination.size..destLastIndex) {
destination.add(this[i + destToSource])
}
if (destinationOffset > startIndex) {
var dest = destinationOffset + endIndex - startIndex
for (i in endIndex - 1 downTo startIndex) {
destination[--dest] = this[i]
}
} else {
var dest = destinationOffset
for (i in startIndex..endIndex - 1) {
destination[dest++] = this[i]
}
}
return destination
}
fun <E> Collection<E>.copy(): MutableList<E> {
val newList = ArrayList<E>(size)
newList.addAll(this)
return newList
}
/**
* Adds all the items in the [other] list that this list does not already contain.
* This uses List as opposed to Iterable to avoid allocation.
*/
fun <E> MutableList<in E>.addAllUnique(other: List<E>) {
for (i in 0..other.lastIndex) {
val item = other[i]
if (!contains(item)) {
add(item)
}
}
}
/**
* Adds all the items in the [other] list that this list does not already contain.
* This uses List as opposed to Iterable to avoid allocation.
*/
fun <E> MutableList<in E>.addAllUnique(other: Array<out E>) {
for (i in 0..other.lastIndex) {
val item = other[i]
if (!contains(item)) {
add(item)
}
}
}
/**
* @param element The element with which to calculate the insertion index.
*
* @param comparator A comparison function used to determine the sorting order of elements in the sorted
* list. A comparison function should take two arguments to compare. Given the elements A and B, the
* result of compareFunction can have a negative, 0, or positive value:
* A negative return value specifies that A appears before B in the sorted sequence.
* A return value of 0 specifies that A and B have the same sort order.
* A positive return value specifies that A appears after B in the sorted sequence.
* The compareFunction must never return return ambiguous results.
* That is, (A, B) != (B, A), unless == 0
*
* @param matchForwards If true, the returned index will be after comparisons of 0, if false, before.
*/
fun <K, E> List<E>.sortedInsertionIndex(element: K, fromIndex: Int = 0, toIndex: Int = size, matchForwards: Boolean = true, comparator: (K, E) -> Int): Int {
var indexA = fromIndex
var indexB = toIndex
while (indexA < indexB) {
val midIndex = (indexA + indexB) ushr 1
val comparison = comparator(element, this[midIndex])
if (comparison == 0) {
if (matchForwards) {
indexA = midIndex + 1
} else {
indexB = midIndex
}
} else if (comparison > 0) {
indexA = midIndex + 1
} else {
indexB = midIndex
}
}
return indexA
}
/**
* Given a sorted list of comparable objects, this finds the insertion index of the given element.
* If there are equal elements, the insertion index returned will be after.
*/
fun <E : Comparable<E>> List<E>.sortedInsertionIndex(element: E, fromIndex: Int = 0, toIndex: Int = size, matchForwards: Boolean = true): Int {
return sortedInsertionIndex(element, fromIndex, toIndex, matchForwards) { o1, o2 -> o1.compareTo(o2) }
}
/**
* @param comparator A comparison function used to determine the sorting order of elements in the sorted
* list. A return value of 1 will insert later in the list, -1 will insert earlier in the list, and a return value of
* 0 will be later if [matchForwards] is true, or earlier if [matchForwards] is false.
*
* @param matchForwards If true, the returned index will be after comparisons of 0, if false, before.
*/
fun <E> List<E>.sortedInsertionIndex(fromIndex: Int = 0, toIndex: Int = size, matchForwards: Boolean = true, comparator: (E) -> Int): Int {
return sortedInsertionIndex(null, fromIndex, toIndex, matchForwards) { _, o2 -> comparator(o2) }
}
/**
* Returns true if the given index is within range of this List.
*/
@Suppress("FunctionName")
fun List<*>.rangeCheck(index: Int): Boolean = index >= 0 && index < size
/**
* Adds an element to a sorted list based on the provided comparator function.
*/
fun <E> MutableList<E>.addSorted(element: E, matchForwards: Boolean = true, comparator: (o1: E, o2: E) -> Int): Int {
val index = sortedInsertionIndex(element, matchForwards = matchForwards, comparator = comparator)
add(index, element)
return index
}
/**
* Adds an element to a sorted list based on the element's compareTo.
*/
fun <E : Comparable<E>> MutableList<E>.addSorted(element: E, matchForwards: Boolean = true): Int {
val index = sortedInsertionIndex(element, matchForwards = matchForwards)
add(index, element)
return index
}
/**
* Adds all elements in the receiver list to the provided mutable list using a sorting comparator.
* This method does not clear the [out] list first.
*/
fun <E> List<E>.sortTo(out: MutableList<E>, matchForwards: Boolean = true, comparator: (o1: E, o2: E) -> Int) {
for (i in 0..lastIndex)
out.addSorted(this[i], matchForwards, comparator)
}
/**
* An iterator object for a simple List.
*/
open class ListIteratorImpl<out E>(
val list: List<E>
) : Clearable, ListIterator<E>, Iterable<E> {
var cursor: Int = 0 // index of next element to return
var lastRet: Int = -1 // index of last element returned; -1 if no such
override fun hasNext(): Boolean {
return cursor < list.size
}
override fun next(): E {
val i = cursor
if (i >= list.size)
throw Exception("Iterator does not have next.")
cursor = i + 1
lastRet = i
return list[i]
}
override fun nextIndex(): Int {
return cursor
}
override fun hasPrevious(): Boolean {
return cursor != 0
}
override fun previous(): E {
val i = cursor - 1
if (i < 0)
throw Exception("Iterator does not have previous.")
cursor = i
lastRet = i
return list[i]
}
override fun previousIndex(): Int {
return cursor - 1
}
/**
* Resets the iterator to the beginning.
*/
override fun clear() {
cursor = 0
lastRet = -1
}
override fun iterator(): Iterator<E> {
return this
}
}
fun <E> MutableList<E>.addOrSet(i: Int, value: E) {
if (i == size) add(value)
else set(i, value)
}
inline fun <E> MutableList<E>.fill(newSize: Int, factory: () -> E) {
for (i in size..newSize - 1) {
add(factory())
}
}
fun <E> Iterator<E>.toList(): List<E> = asSequence().toList()
inline fun <E> produceList(size: Int, factory: (index: Int) -> E): List<E> {
val a = ArrayList<E>(size)
for (i in 0..size - 1) {
a.add(factory(i))
}
return a
}
/**
* Returns the first element matching the given [predicate], or `null` if no such element was found.
* Does not cause allocation.
* @param startIndex The starting index to search from (inclusive).
* @param lastIndex The ending index to search to (inclusive).
* @param predicate The filter to use. If this returns true, iteration will stop and that element will be returned.
*/
inline fun <E> List<E>.firstOrNull(startIndex: Int, lastIndex: Int = this.lastIndex, predicate: Filter<E>): E? {
val index = indexOfFirst(startIndex, lastIndex, predicate)
return if (index == -1) null else this[index]
}
/**
* Returns the first element matching the given [predicate], or throws an exception if no such element was found.
* Does not cause allocation.
* @param startIndex The starting index to search from (inclusive).
* @param lastIndex The ending index to search to (inclusive).
* @param predicate The filter to use. If this returns true, iteration will stop and that element will be returned.
*/
inline fun <E> List<E>.first(startIndex: Int, lastIndex: Int = this.lastIndex, predicate: Filter<E>): E {
val index = indexOfFirst(startIndex, lastIndex, predicate)
return if (index == -1) throw Exception("Element not found matching predicate") else this[index]
}
/**
* Returns true if any of the elements match the given [predicate] within the bounds of [startIndex] and [lastIndex].
* @param startIndex The starting index to search from (inclusive).
* @param lastIndex The ending index to search to (inclusive).
* @param predicate The filter to use. If this returns true, iteration will stop and true will be returned.
*/
inline fun <E> List<E>.any(startIndex: Int, lastIndex: Int = this.lastIndex, predicate: Filter<E>): Boolean {
val index = indexOfFirst(startIndex, lastIndex, predicate)
return index != -1
}
/**
* Returns true if all of the elements match the given [predicate] within the bounds of [startIndex] and [lastIndex].
* @param startIndex The starting index to search from (inclusive).
* @param lastIndex The ending index to search to (inclusive).
* @param predicate The filter to use. If this returns true, iteration will stop and true will be returned.
*/
inline fun <E> List<E>.all(startIndex: Int, lastIndex: Int = this.lastIndex, predicate: Filter<E>): Boolean {
return any(startIndex, lastIndex) { !predicate(it) }
}
/**
* Returns index of the first element matching the given [predicate], or -1 if this list does not contain such element.
* Does not cause allocation.
* @param startIndex The starting index to search from (inclusive).
* @param lastIndex The ending index to search to (inclusive). lastIndex >= startIndex
*/
inline fun <E> List<E>.indexOfFirst(startIndex: Int, lastIndex: Int = this.lastIndex, predicate: Filter<E>): Int {
if (isEmpty()) return -1
if (startIndex == lastIndex) return if (predicate(this[startIndex])) startIndex else -1
for (i in startIndex..lastIndex) {
if (predicate(this[i]))
return i
}
return -1
}
/**
* Returns the first element matching the given [predicate], walking backwards from [lastIndex], or `null` if no such
* element was found.
* Does not cause allocation.
* @param lastIndex The starting index to search from (inclusive).
* @param startIndex The ending index to search to (inclusive).
* @param predicate The filter to use. If this returns true, iteration will stop and that element will be returned.
*/
inline fun <E> List<E>.lastOrNull(lastIndex: Int, startIndex: Int = 0, predicate: Filter<E>): E? {
val index = indexOfLast(lastIndex, startIndex, predicate)
return if (index == -1) null else this[index]
}
/**
* Returns the first element matching the given [predicate], walking backwards from [lastIndex], or throws an exception
* if no such element was found.
* Does not cause allocation.
* @param lastIndex The starting index to search from (inclusive).
* @param startIndex The ending index to search to (inclusive).
* @param predicate The filter to use. If this returns true, iteration will stop and that element will be returned.
*/
inline fun <E> List<E>.last(lastIndex: Int, startIndex: Int = 0, predicate: Filter<E>): E {
val index = indexOfLast(lastIndex, startIndex, predicate)
return if (index == -1) throw Exception("Element not found matching predicate") else this[index]
}
/**
* Returns index of the last element matching the given [predicate], or -1 if this list does not contain such element.
* The search goes in reverse starting from lastIndex downTo startIndex
* @param lastIndex The starting index to search from (inclusive).
* @param startIndex The ending index to search to (inclusive).
* @param predicate The filter to use. If this returns true, iteration will stop and the index of that element will be
* returned.
*/
inline fun <E> List<E>.indexOfLast(lastIndex: Int, startIndex: Int = 0, predicate: Filter<E>): Int {
if (isEmpty()) return -1
if (lastIndex == startIndex) return if (predicate(this[lastIndex])) lastIndex else -1
for (i in lastIndex downTo startIndex) {
if (predicate(this[i]))
return i
}
return -1
}
/**
* Performs the given [action] on each element.
* Does not cause allocation.
* @param startIndex The index (inclusive) to begin iteration.
* @param lastIndex The index (inclusive) to end iteration.
* @param action Each element within the range will be provided, in order.
*/
inline fun <E> List<E>.forEach(startIndex: Int, lastIndex: Int, action: (E) -> Unit) {
for (i in startIndex..lastIndex) action(this[i])
}
/**
* Performs the given [action] on each element.
* Does not cause allocation.
* @param lastIndex The index (inclusive) to begin iteration.
* @param startIndex The index (inclusive) to end iteration.
* @param action Each element within the range will be provided, in reverse order.
*/
inline fun <E> List<E>.forEachReversed(lastIndex: Int = this.lastIndex, startIndex: Int = 0, action: (E) -> Unit) {
for (i in lastIndex downTo startIndex) action(this[i])
}
/**
* Sums the float list for the specified range.
* Does not cause allocation.
*/
fun List<Double>.sum(startIndex: Int, lastIndex: Int): Double {
var t = 0.0
for (i in startIndex..lastIndex) {
t += this[i]
}
return t
}
typealias SortComparator<E> = (o1: E, o2: E) -> Int
fun <E> MutableList<E>.addAll(vararg elements: E) {
addAll(elements.toList())
}
/**
* Creates a wrapper to a target list that maps the elements on retrieval.
*/
class ListTransform<E, R>(private val target: List<E>, private val transform: (E) -> R) : AbstractList<R>() {
override val size: Int
get() = target.size
override fun get(index: Int): R {
return transform(target[index])
}
}
/**
* Returns the number of elements matching the given [predicate].
* Does not cause allocation.
* @param predicate A method that returns true if the counter should increment.
* @param startIndex The index to start counting form (inclusive)
* @param lastIndex The index to count until (inclusive)
* @return Returns a count representing the number of times [predicate] returned true. This will always be within the
* range 0 and (lastIndex - startIndex + 1)
*/
inline fun <E> List<E>.count(startIndex: Int, lastIndex: Int, predicate: Filter<E>): Int {
var count = 0
for (i in startIndex..lastIndex) if (predicate(this[i])) count++
return count
}
/**
* Removes the first element that matches [predicate].
* Does not cause allocation.
* @param predicate Returns true when the item should be removed. Iteration will continue until the end is reached
* or `true` is returned.
*/
inline fun <E> MutableList<E>.removeFirst(predicate: Filter<E>): E? {
val index = indexOfFirst(0, lastIndex, predicate)
if (index == -1) return null
return removeAt(index)
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
* Does not cause allocation.
*/
inline fun <E> List<E>.sumBy(startIndex: Int, lastIndex: Int = this.lastIndex, selector: (E) -> Int): Int {
var sum = 0
for (i in startIndex..lastIndex) {
sum += selector(this[i])
}
return sum
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
* Does not cause allocation.
*/
inline fun <E> List<E>.sumByDouble(startIndex: Int = 0, lastIndex: Int = this.lastIndex, selector: (E) -> Double): Double {
var sum = 0.0
for (i in startIndex..lastIndex) {
sum += selector(this[i])
}
return sum
}
/**
* Modifies this list to become the new size.
*/
fun <E> MutableList<E>.setSize(newSize: Int, factory: () -> E) {
if (newSize < size) {
for (i in 0 until size - newSize)
pop()
} else if (newSize > size) {
for (i in 0 until newSize - size)
add(factory())
}
}
/**
* Removes head elements of this list until it matches the new size.
* @throws IllegalArgumentException If maxSize > size
*/
fun <E> MutableList<E>.keepLast(n: Int) {
while (size > n) {
removeAt(0)
}
}
/**
* Removes tail elements of this list until it matches the new size.
* @throws IllegalArgumentException If maxSize > size
*/
fun <E> MutableList<E>.keepFirst(n: Int) {
while (size > n) {
removeAt(lastIndex)
}
}
/**
* Clones this list, replacing the value at the given index with the new value.
*/
fun <E> List<E>.replaceAt(index: Int, newValue: E): List<E> {
val newList = ArrayList<E>(size)
for (i in 0..lastIndex) {
newList.add(if (i == index) newValue else this[i])
}
return newList
}
/**
* Removes the element at the given index, returning a new list.
*/
fun <E> List<E>.removeAt(index: Int): List<E> {
if (index >= size) throw IndexOutOfBoundsException()
return subListSafe(0, index) + subListSafe(index + 1, size)
}
/**
* Adds the element at the given index, returning a new list.
*/
fun <E> List<E>.add(index: Int, element: E): List<E> {
if (index > size) throw IndexOutOfBoundsException()
val result = ArrayList<E>(size + 1)
result.addAll(subListSafe(0, index))
result.add(element)
result.addAll(subListSafe(index, size))
return result
}
/**
* Clones this list, replacing values that identity equals [oldValue] with [newValue].
* @throws Exception Throws exception when [oldValue] was not found.
*/
fun <E> List<E>.replace(oldValue: E, newValue: E): List<E> {
val newList = ArrayList<E>(size)
var found = false
for (i in 0..lastIndex) {
newList.add(if (this[i] === oldValue) {
found = true
newValue
} else this[i])
}
if (!found) throw Exception("Could not find $oldValue")
return newList
}
fun <E> List<E>.replaceFirstWhere(newValue: E, predicate: Filter<E>): List<E> {
val index = indexOfFirst(0, lastIndex, predicate)
return if (index == -1) throw Exception("Could not find a value matching the predicate")
else replaceAt(index, newValue)
}
/**
* Clones this list, replacing the given range with the new elements.
* @param startIndex The starting index of the replacement.
* @param endIndex The range [startIndex] to [endIndex] (exclusive) will not be added to the new list. Must not be less
* than startIndex
*/
fun <E> List<E>.replaceRange(startIndex: Int, endIndex: Int = startIndex, newElements: List<E>): List<E> {
require(endIndex <= size) { "endIndex ($endIndex) may not be greater than size ($size)" }
require(endIndex >= startIndex) { "endIndex ($endIndex) may not be less than startIndex ($startIndex)" }
if (endIndex == startIndex && newElements.isEmpty()) return copy()
val newSize = size - (endIndex - startIndex) + newElements.size
val newList = ArrayList<E>(newSize)
for (i in 0..startIndex - 1) {
newList.add(this[i])
}
for (i in 0..newElements.lastIndex) {
newList.add(newElements[i])
}
for (i in endIndex..lastIndex) {
newList.add(this[i])
}
return newList
}
/**
* Clears this list and adds all elements from [other].
*/
fun <E> MutableList<E>.setTo(other: List<E>) {
clear()
addAll(other)
}
/**
* Returns true if this list is currently sorted.
*/
fun <E : Comparable<E>> List<E>.isSorted(): Boolean {
for (i in 1..lastIndex) {
val a = this[i - 1]
val b = this[i]
if (a > b) return false
}
return true
}
/**
* Returns true if this list is currently descendingly sorted.
*/
fun <E : Comparable<E>> List<E>.isReverseSorted(): Boolean {
for (i in 1..lastIndex) {
val a = this[i - 1]
val b = this[i]
if (a < b) return false
}
return true
}
/**
* Adds an element to this list at the given position.
* If the element already exists in this list, it will be added to the new [index], then removed from the old position.
* If `(index == oldIndex || index == oldIndex + 1)` there will be no change.
* @param onReorder If an add or a reorder happens, [onReorder] will be called with the old index, and the new index.
*/
inline fun <E> MutableList<E>.addOrReorder(index: Int, element: E, onReorder: (oldIndex: Int, newIndex: Int) -> Unit = { _, _ -> }) {
contract { callsInPlace(onReorder, InvocationKind.AT_MOST_ONCE) }
val oldIndex = indexOf(element)
if (oldIndex == -1) {
add(index, element)
onReorder(oldIndex, index)
} else {
val newIndex = if (oldIndex < index) index - 1 else index
if (index == oldIndex || index == oldIndex + 1) return
removeAt(oldIndex)
add(newIndex, element)
onReorder(oldIndex, newIndex)
}
}
/**
* Calls [List.subListSafe], clamping [startIndex] (inclusive) and [toIndex] (exclusive) to the range of the list.
*/
fun <E> List<E>.subListSafe(startIndex: Int, toIndex: Int): List<E> {
val sI = clamp(startIndex, 0, size)
val tI = clamp(toIndex, 0, size)
if (tI <= sI) return emptyList()
return subList(sI, tI)
}
/**
* Adds an element after the provided element.
* @param element The element to add.
* @param after The element to find. This will then be immediately before [element].
* @throws IllegalArgumentException if [after] is not in this list.
*/
fun <E, T : E> MutableList<E>.addAfter(element: T, after: E): T {
val index = indexOf(after)
require(index != -1) { "element $element not found. " }
add(index + 1, element)
return element
}
/**
* Adds an element after the provided element.
* @param element The element to add.
* @param before The element to find. This will then be immediately after [element].
* @throws IllegalArgumentException if [before] is not in this list.
*/
fun <E, T : E> MutableList<E>.addBefore(element: T, before: E): T {
val index = indexOf(before)
require(index != -1) { "element $element not found. " }
add(index, element)
return element
}
/**
* A wrapper to a [DoubleArray] that provides list access.
* Unlike [DoubleArray.toList], this does not copy the original list.
*/
class DoubleArrayList(private val wrapped: DoubleArray) : AbstractList<Double>() {
override val size: Int
get() = wrapped.size
override fun get(index: Int): Double = wrapped[index]
}
/**
* Returns a List interface view to this array.
*/
fun DoubleArray.toListView() = DoubleArrayList(this)
fun DoubleArray.mutate(builder: (DoubleArray) -> Unit): DoubleArray {
val c = copyOf()
builder(c)
return c
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
*/
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
var sum = 0L
for (element in this) {
sum += selector(element)
}
return sum
}
inline fun <reified T> List<T>.ensureCapacity(newCapacity: Int, noinline factory: (index: Int) -> T): List<T> {
if (size >= newCapacity) return this
return this + Array(newCapacity - size, factory)
}
/**
* Removes the elements at the given indices.
*/
fun <T> List<T>.removeIndices(indices: Iterable<Int>): List<T> {
val newList = toMutableList()
val sortedIndices = indices.sorted()
for (i in sortedIndices.lastIndex downTo 0) {
val index = sortedIndices[i]
if (index < newList.size) {
newList.removeAt(index)
}
}
return newList
}
|
apache-2.0
|
569fdee536a61d5dd4b1b8cafe3d40a2
| 32.463576 | 160 | 0.701552 | 3.533427 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/test/java/org/wordpress/android/ui/posts/PostUtilsUploadProcessingTest.kt
|
1
|
2704
|
package org.wordpress.android.ui.posts
import org.assertj.core.api.Assertions
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.wordpress.android.ui.posts.mediauploadcompletionprocessors.TestContent
import org.wordpress.android.util.helpers.MediaFile
@RunWith(MockitoJUnitRunner::class)
class PostUtilsUploadProcessingTest {
private val mediaFile: MediaFile = mock()
@Before
fun before() {
whenever(mediaFile.mediaId).thenReturn(TestContent.remoteMediaId)
whenever(mediaFile.optimalFileURL).thenReturn(TestContent.remoteImageUrl)
whenever(mediaFile.getAttachmentPageURL(any())).thenReturn(TestContent.attachmentPageUrl)
}
@Test
fun `replaceMediaFileWithUrlInGutenbergPost replaces temporary local id and url for image block`() {
val processedContent = PostUtils.replaceMediaFileWithUrlInGutenbergPost(TestContent.oldImageBlock,
TestContent.localMediaId, mediaFile, TestContent.siteUrl)
Assertions.assertThat(processedContent).isEqualTo(TestContent.newImageBlock)
}
@Test
@Suppress("MaxLineLength")
fun `replaceMediaFileWithUrlInGutenbergPost replaces temporary local id and url for image block with colliding prefixes`() {
val oldContent = TestContent.oldImageBlock + TestContent.imageBlockWithPrefixCollision
val newContent = TestContent.newImageBlock + TestContent.imageBlockWithPrefixCollision
val processedContent = PostUtils.replaceMediaFileWithUrlInGutenbergPost(oldContent, TestContent.localMediaId,
mediaFile, TestContent.siteUrl)
Assertions.assertThat(processedContent).isEqualTo(newContent)
}
@Test
fun `replaceMediaFileWithUrlInGutenbergPost replaces temporary local id and url for media-text block`() {
val processedContent = PostUtils.replaceMediaFileWithUrlInGutenbergPost(TestContent.oldMediaTextBlock,
TestContent.localMediaId, mediaFile, TestContent.siteUrl)
Assertions.assertThat(processedContent).isEqualTo(TestContent.newMediaTextBlock)
}
@Test
fun `replaceMediaFileWithUrlInGutenbergPost also works with video`() {
whenever(mediaFile.optimalFileURL).thenReturn(TestContent.remoteVideoUrl)
val processedContent = PostUtils.replaceMediaFileWithUrlInGutenbergPost(TestContent.oldMediaTextBlockWithVideo,
TestContent.localMediaId, mediaFile, TestContent.siteUrl)
Assertions.assertThat(processedContent).isEqualTo(TestContent.newMediaTextBlockWithVideo)
}
}
|
gpl-2.0
|
fb0bd0335a6be40bc298def9ad0d0c8f
| 47.285714 | 128 | 0.783284 | 4.837209 | false | true | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspection.kt
|
1
|
8352
|
// 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.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.targetDescriptors
import org.jetbrains.kotlin.idea.highlighter.Fe10QuickFixProvider
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.ReplaceObsoleteLabelSyntaxFix
import org.jetbrains.kotlin.idea.quickfix.replaceWith.DeprecatedSymbolUsageFixBase
import org.jetbrains.kotlin.js.resolve.diagnostics.ErrorsJs
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
class KotlinCleanupInspection : LocalInspectionTool(), CleanupLocalInspectionTool {
// required to simplify the inspection registration in tests
override fun getDisplayName(): String = KotlinBundle.message("usage.of.redundant.or.deprecated.syntax.or.deprecated.symbols")
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<out ProblemDescriptor>? {
if (isOnTheFly || file !is KtFile || !RootKindFilter.projectSources.matches(file)) {
return null
}
val analysisResult = file.analyzeWithAllCompilerChecks()
if (analysisResult.isError()) {
return null
}
val diagnostics = analysisResult.bindingContext.diagnostics
val problemDescriptors = arrayListOf<ProblemDescriptor>()
val importsToRemove = importDirectivesToBeRemoved(file)
for (import in importsToRemove) {
val removeImportFix = RemoveImportFix(import)
val problemDescriptor = createProblemDescriptor(import, removeImportFix.text, listOf(removeImportFix), manager)
problemDescriptors.add(problemDescriptor)
}
file.forEachDescendantOfType<PsiElement> { element ->
for (diagnostic in diagnostics.forElement(element)) {
if (diagnostic.isCleanup()) {
val fixes = getCleanupFixes(element.project, diagnostic)
if (fixes.isNotEmpty()) {
problemDescriptors.add(diagnostic.toProblemDescriptor(fixes, file, manager))
}
}
}
}
return problemDescriptors.toTypedArray()
}
private fun importDirectivesToBeRemoved(file: KtFile): List<KtImportDirective> {
if (file.hasAnnotationToSuppressDeprecation()) return emptyList()
return file.importDirectives.filter { isImportToBeRemoved(it) }
}
private fun KtFile.hasAnnotationToSuppressDeprecation(): Boolean {
val suppressAnnotationEntry = annotationEntries.firstOrNull {
it.shortName?.asString() == "Suppress"
&& it.resolveToCall()?.resultingDescriptor?.containingDeclaration?.fqNameSafe == StandardNames.FqNames.suppress
} ?: return false
return suppressAnnotationEntry.valueArguments.any {
val text = (it.getArgumentExpression() as? KtStringTemplateExpression)?.entries?.singleOrNull()?.text ?: return@any false
text.equals("DEPRECATION", ignoreCase = true)
}
}
private fun isImportToBeRemoved(import: KtImportDirective): Boolean {
if (import.isAllUnder) return false
val targetDescriptors = import.targetDescriptors()
if (targetDescriptors.isEmpty()) return false
return targetDescriptors.all {
DeprecatedSymbolUsageFixBase.fetchReplaceWithPattern(it, import.project, null, false) != null
}
}
private fun Diagnostic.isCleanup() = factory in Holder.cleanupDiagnosticsFactories || isObsoleteLabel()
private object Holder {
val cleanupDiagnosticsFactories: Collection<DiagnosticFactory<*>> = setOf(
Errors.MISSING_CONSTRUCTOR_KEYWORD,
Errors.UNNECESSARY_NOT_NULL_ASSERTION,
Errors.UNNECESSARY_SAFE_CALL,
Errors.USELESS_CAST,
Errors.USELESS_ELVIS,
ErrorsJvm.POSITIONED_VALUE_ARGUMENT_FOR_JAVA_ANNOTATION,
Errors.DEPRECATION,
Errors.DEPRECATION_ERROR,
Errors.NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION,
Errors.OPERATOR_MODIFIER_REQUIRED,
Errors.INFIX_MODIFIER_REQUIRED,
Errors.DEPRECATED_TYPE_PARAMETER_SYNTAX,
Errors.MISPLACED_TYPE_PARAMETER_CONSTRAINTS,
Errors.COMMA_IN_WHEN_CONDITION_WITHOUT_ARGUMENT,
ErrorsJs.WRONG_EXTERNAL_DECLARATION,
Errors.YIELD_IS_RESERVED,
Errors.DEPRECATED_MODIFIER_FOR_TARGET,
Errors.DEPRECATED_MODIFIER
)
}
private fun Diagnostic.isObsoleteLabel(): Boolean {
val annotationEntry = psiElement.getNonStrictParentOfType<KtAnnotationEntry>() ?: return false
return ReplaceObsoleteLabelSyntaxFix.looksLikeObsoleteLabel(annotationEntry)
}
private fun getCleanupFixes(project: Project, diagnostic: Diagnostic): Collection<CleanupFix> {
val quickFixes = Fe10QuickFixProvider.getInstance(project).createQuickFixes(listOf(diagnostic))
return quickFixes[diagnostic].filterIsInstance<CleanupFix>()
}
private class Wrapper(val intention: IntentionAction) : IntentionWrapper(intention) {
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (intention.isAvailable(
project,
editor,
file
)
) { // we should check isAvailable here because some elements may get invalidated (or other conditions may change)
super.invoke(project, editor, file)
}
}
}
private fun Diagnostic.toProblemDescriptor(fixes: Collection<CleanupFix>, file: KtFile, manager: InspectionManager): ProblemDescriptor {
// TODO: i18n DefaultErrorMessages.render
@NlsSafe val message = DefaultErrorMessages.render(this)
return createProblemDescriptor(psiElement, message, fixes, manager)
}
private fun createProblemDescriptor(
element: PsiElement,
@Nls message: String,
fixes: Collection<CleanupFix>,
manager: InspectionManager
): ProblemDescriptor {
return manager.createProblemDescriptor(
element,
message,
false,
fixes.map { Wrapper(it) }.toTypedArray(),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
}
private class RemoveImportFix(import: KtImportDirective) : KotlinQuickFixAction<KtImportDirective>(import), CleanupFix {
override fun getFamilyName() = KotlinBundle.message("remove.deprecated.symbol.import")
@Nls
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.delete()
}
}
}
|
apache-2.0
|
b820106e12ec57dbef222c71e38a45b3
| 44.639344 | 158 | 0.715158 | 5.242938 | false | false | false | false |
mdaniel/intellij-community
|
plugins/git4idea/src/git4idea/log/GitDirectoryVirtualFile.kt
|
8
|
2007
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.log
import com.intellij.openapi.vcs.vfs.AbstractVcsVirtualFile
import com.intellij.openapi.vcs.vfs.VcsFileSystem
import com.intellij.openapi.vcs.vfs.VcsVirtualFile
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.VcsCommitMetadata
import git4idea.GitFileRevision
import git4idea.GitRevisionNumber
import git4idea.index.GitIndexUtil
import git4idea.repo.GitRepository
class GitDirectoryVirtualFile(
private val repo: GitRepository,
parent: VirtualFile?,
name: String,
private val commit: VcsCommitMetadata
) : AbstractVcsVirtualFile(parent, name, VcsFileSystem.getInstance()) {
override fun isDirectory(): Boolean = true
override fun contentsToByteArray(): ByteArray {
throw UnsupportedOperationException()
}
private val cachedChildren by lazy {
val gitRevisionNumber = GitRevisionNumber(commit.id.asString())
val dirPath = if (path.isEmpty()) "." else "$path/"
val tree = GitIndexUtil.listTreeForRawPaths(repo, listOf(dirPath), gitRevisionNumber)
val result = tree.map {
when (it) {
is GitIndexUtil.StagedDirectory -> GitDirectoryVirtualFile(repo, this, it.path.name, commit)
else -> VcsVirtualFile(this, it.path.name,
GitFileRevision(repo.project, repo.root, it.path, gitRevisionNumber),
VcsFileSystem.getInstance())
}
}
result.toTypedArray<VirtualFile>()
}
override fun getChildren(): Array<VirtualFile> = cachedChildren
override fun getLength(): Long = 0
override fun equals(other: Any?): Boolean {
val otherFile = other as? GitDirectoryVirtualFile ?: return false
return repo == otherFile.repo && path == otherFile.path && commit.id == otherFile.commit.id
}
override fun hashCode(): Int {
return repo.hashCode() * 31 * 31 + path.hashCode() * 31 + commit.id.hashCode()
}
}
|
apache-2.0
|
c5dd2aa1cae2fd7d65fb6d9c6d6dee2f
| 35.490909 | 120 | 0.724464 | 4.420705 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structuralsearch/visitor/KotlinCompilingVisitor.kt
|
1
|
19668
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.structuralsearch.visitor
import com.intellij.dupLocator.util.NodeFilter
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.structuralsearch.impl.matcher.CompiledPattern
import com.intellij.structuralsearch.impl.matcher.compiler.GlobalCompilingVisitor
import com.intellij.structuralsearch.impl.matcher.compiler.GlobalCompilingVisitor.OccurenceKind.CODE
import com.intellij.structuralsearch.impl.matcher.compiler.GlobalCompilingVisitor.OccurenceKind.COMMENT
import com.intellij.structuralsearch.impl.matcher.compiler.WordOptimizer
import com.intellij.structuralsearch.impl.matcher.handlers.MatchingHandler
import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler
import com.intellij.structuralsearch.impl.matcher.handlers.TopLevelMatchingHandler
import org.jetbrains.kotlin.idea.structuralsearch.getCommentText
import org.jetbrains.kotlin.idea.structuralsearch.handler.CommentedDeclarationHandler
import org.jetbrains.kotlin.idea.structuralsearch.withinHierarchyTextFilterSet
import org.jetbrains.kotlin.kdoc.lexer.KDocTokens
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink
import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
import org.jetbrains.kotlin.psi2ir.deparenthesize
import java.util.regex.Pattern
class KotlinCompilingVisitor(private val myCompilingVisitor: GlobalCompilingVisitor) : KotlinRecursiveElementVisitor() {
private val mySubstitutionPattern = Pattern.compile("\\b(_____\\w+)\\b")
fun compile(topLevelElements: Array<out PsiElement>?) {
val context = myCompilingVisitor.context
// When dumb the index is not used while editing pattern (e.g. no warning when zero hits in project).
val optimizer = if (DumbService.isDumb(context.project)) null else KotlinWordOptimizer()
val pattern = context.pattern
if (topLevelElements == null) return
for (element in topLevelElements) {
element.accept(this)
optimizer?.let { element.accept(it) }
pattern.setHandler(element, TopLevelMatchingHandler(pattern.getHandler(element)))
}
}
inner class KotlinWordOptimizer : KotlinRecursiveElementWalkingVisitor(), WordOptimizer {
override fun visitClass(klass: KtClass) {
if (!handleWord(klass.name, CODE, myCompilingVisitor.context)) return
super.visitClass(klass)
}
override fun visitNamedFunction(function: KtNamedFunction) {
if (!handleWord(function.name, CODE, myCompilingVisitor.context)) return
super.visitNamedFunction(function)
}
override fun visitParameter(parameter: KtParameter) {
if (!handleWord(parameter.name, CODE, myCompilingVisitor.context)) return
super.visitParameter(parameter)
}
override fun visitProperty(property: KtProperty) {
if (!handleWord(property.name, CODE, myCompilingVisitor.context)) return
super.visitProperty(property)
}
override fun visitReferenceExpression(expression: KtReferenceExpression) {
if (expression is KtNameReferenceExpression && expression.parent !is KtUserType)
if (!handleWord(expression.getReferencedName(), CODE, myCompilingVisitor.context)) return
super.visitReferenceExpression(expression)
}
override fun visitElement(element: PsiElement) {
if (element is KDocTag && !handleWord(element.name, CODE, myCompilingVisitor.context)) return
super.visitElement(element)
}
override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) {
val name = annotationEntry.shortName ?: return
if (!handleWord(name.identifier, CODE, myCompilingVisitor.context)) return
super.visitAnnotationEntry(annotationEntry)
}
}
private fun getHandler(element: PsiElement) = myCompilingVisitor.context.pattern.getHandler(element)
private fun setHandler(element: PsiElement, handler: MatchingHandler) =
myCompilingVisitor.context.pattern.setHandler(element, handler)
private fun processPatternStringWithFragments(element: PsiElement, text: String = element.text) {
if (mySubstitutionPattern.matcher(text).find()) {
myCompilingVisitor.processPatternStringWithFragments(text, COMMENT, mySubstitutionPattern)?.let {
element.putUserData(CompiledPattern.HANDLER_KEY, it)
}
}
}
override fun visitElement(element: PsiElement) {
myCompilingVisitor.handle(element)
super.visitElement(element)
}
override fun visitReferenceExpression(expression: KtReferenceExpression) {
visitElement(expression)
val handler = getHandler(expression)
getHandler(expression).filter =
if (handler is SubstitutionHandler) NodeFilter { it is PsiElement } // accept all
else ReferenceExpressionFilter
}
override fun visitLeafPsiElement(leafPsiElement: LeafPsiElement) {
getHandler(leafPsiElement).setFilter { it is LeafPsiElement }
when (leafPsiElement.elementType) {
KDocTokens.TEXT -> processPatternStringWithFragments(leafPsiElement)
KDocTokens.TAG_NAME -> {
val handler = getHandler(leafPsiElement)
if (handler is SubstitutionHandler) {
handler.findRegExpPredicate()?.setNodeTextGenerator { it.text.drop(1) }
if (handler.minOccurs != 1 || handler.maxOccurs != 1) {
setHandler(
leafPsiElement.parent, SubstitutionHandler(
"${handler.name}_",
false,
handler.minOccurs,
handler.maxOccurs,
false
).apply {
filter = NodeFilter { it is KDocTag }
}
)
leafPsiElement.resetCountFilter()
}
}
}
}
}
override fun visitExpression(expression: KtExpression) {
super.visitExpression(expression)
getHandler(expression).filter = ExpressionFilter
}
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
super.visitDotQualifiedExpression(expression)
getHandler(expression).filter = DotQualifiedExpressionFilter
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
super.visitBinaryExpression(expression)
getHandler(expression).filter = BinaryExpressionFilter
}
override fun visitUnaryExpression(expression: KtUnaryExpression) {
super.visitUnaryExpression(expression)
getHandler(expression).filter = UnaryExpressionFilter
}
override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) {
super.visitArrayAccessExpression(expression)
getHandler(expression).filter = ArrayAccessExpressionFilter
}
override fun visitCallExpression(expression: KtCallExpression) {
super.visitCallExpression(expression)
getHandler(expression).filter = CallExpressionFilter
}
override fun visitConstantExpression(expression: KtConstantExpression) {
super.visitConstantExpression(expression)
getHandler(expression).filter = ConstantExpressionFilter
}
override fun visitLiteralStringTemplateEntry(entry: KtLiteralStringTemplateEntry) {
super.visitLiteralStringTemplateEntry(entry)
processPatternStringWithFragments(entry)
getHandler(entry).setFilter { it is KtLiteralStringTemplateEntry }
}
override fun visitSimpleNameStringTemplateEntry(entry: KtSimpleNameStringTemplateEntry) {
super.visitSimpleNameStringTemplateEntry(entry)
getHandler(entry).filter = SimpleNameSTEFilter
val expression = entry.expression ?: return
val exprHandler = getHandler(expression)
// Apply the child SubstitutionHandler to the TemplateEntry
if (exprHandler is SubstitutionHandler) {
val newHandler = SubstitutionHandler(
"${exprHandler.name}_parent",
false,
exprHandler.minOccurs,
exprHandler.maxOccurs,
true
).apply {
setFilter { it is KtStringTemplateEntry }
val exprPredicate = exprHandler.predicate
if (exprPredicate != null) predicate = exprPredicate
}
setHandler(entry, newHandler)
}
}
override fun visitDeclaration(dcl: KtDeclaration) {
super.visitDeclaration(dcl)
getHandler(dcl).filter = DeclarationFilter
if (dcl.getChildOfType<PsiComment>() != null || PsiTreeUtil.skipWhitespacesBackward(dcl) is PsiComment) {
val handler = CommentedDeclarationHandler()
handler.filter = CommentedDeclarationFilter
setHandler(dcl, handler)
}
}
override fun visitNamedDeclaration(declaration: KtNamedDeclaration) {
super.visitNamedDeclaration(declaration)
declaration.nameIdentifier?.let { identifier ->
if (getHandler(identifier).withinHierarchyTextFilterSet && declaration.parent is KtClassBody) {
val klass = declaration.parent.parent
if (klass is KtClassOrObject) {
klass.nameIdentifier?.putUserData(WITHIN_HIERARCHY, true)
}
}
}
}
override fun visitParameter(parameter: KtParameter) {
super.visitParameter(parameter)
getHandler(parameter).filter = ParameterFilter
parameter.typeReference?.resetCountFilter()
parameter.typeReference?.typeElement?.resetCountFilter()
parameter.typeReference?.typeElement?.firstChild?.resetCountFilter()
parameter.typeReference?.typeElement?.firstChild?.firstChild?.resetCountFilter()
}
override fun visitComment(comment: PsiComment) {
super.visitComment(comment)
processPatternStringWithFragments(comment, getCommentText(comment).trim())
getHandler(comment).setFilter { it is PsiComment }
if (comment.parent is KtDeclaration || PsiTreeUtil.skipWhitespacesForward(comment) is KtDeclaration) {
val handler = CommentedDeclarationHandler()
handler.filter = CommentedDeclarationFilter
setHandler(comment, handler)
}
}
override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) {
super.visitAnnotationEntry(annotationEntry)
val calleeExpression = annotationEntry.calleeExpression ?: return
val handler = getHandler(calleeExpression)
if (handler is SubstitutionHandler) {
setHandler(
annotationEntry, SubstitutionHandler(
"${handler.name}_",
false,
handler.minOccurs,
handler.maxOccurs,
false
)
)
calleeExpression.resetCountFilter()
calleeExpression.constructorReferenceExpression?.resetCountFilter()
}
}
override fun visitTypeProjection(typeProjection: KtTypeProjection) {
super.visitTypeProjection(typeProjection)
val handler = getHandler(typeProjection)
if (handler is SubstitutionHandler) {
typeProjection.typeReference?.resetCountFilter()
typeProjection.typeReference?.typeElement?.resetCountFilter()
typeProjection.typeReference?.typeElement?.firstChild?.resetCountFilter()
typeProjection.typeReference?.typeElement?.firstChild?.firstChild?.resetCountFilter()
}
}
override fun visitModifierList(list: KtModifierList) {
super.visitModifierList(list)
list.setAbsenceOfMatchHandlerIfApplicable(true)
}
override fun visitParameterList(list: KtParameterList) {
super.visitParameterList(list)
list.setAbsenceOfMatchHandlerIfApplicable()
}
override fun visitValueArgumentList(list: KtValueArgumentList) {
super.visitValueArgumentList(list)
list.setAbsenceOfMatchHandlerIfApplicable()
}
override fun visitTypeParameterList(list: KtTypeParameterList) {
super.visitTypeParameterList(list)
list.setAbsenceOfMatchHandlerIfApplicable()
}
override fun visitTypeArgumentList(typeArgumentList: KtTypeArgumentList) {
super.visitTypeArgumentList(typeArgumentList)
typeArgumentList.setAbsenceOfMatchHandlerIfApplicable()
}
override fun visitClassBody(classBody: KtClassBody) {
super.visitClassBody(classBody)
classBody.setAbsenceOfMatchHandlerIfApplicable()
}
override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) {
super.visitPrimaryConstructor(constructor)
constructor.setAbsenceOfMatchHandlerIfApplicable()
}
override fun visitWhenEntry(ktWhenEntry: KtWhenEntry) {
super.visitWhenEntry(ktWhenEntry)
val condition = ktWhenEntry.firstChild.firstChild
if (condition is KtNameReferenceExpression) {
val handler = getHandler(condition)
if (handler !is SubstitutionHandler) return
setHandler(ktWhenEntry, SubstitutionHandler(handler.name, false, handler.minOccurs, handler.maxOccurs, false))
condition.parent.resetCountFilter()
condition.resetCountFilter()
condition.firstChild.resetCountFilter()
}
}
override fun visitWhenConditionWithExpression(condition: KtWhenConditionWithExpression) {
super.visitWhenConditionWithExpression(condition)
getHandler(condition).filter = WhenConditionFiler
}
override fun visitConstructorCalleeExpression(expression: KtConstructorCalleeExpression) {
super.visitConstructorCalleeExpression(expression)
val handler = getHandler(expression)
if (handler is SubstitutionHandler && handler.minOccurs == 0) {
setHandler(expression.parent, SubstitutionHandler("${expression.parent.hashCode()}_optional", false, 0, handler.maxOccurs, false))
expression.parent.parent.setAbsenceOfMatchHandlerIfApplicable()
}
}
// override fun visitSuperTypeEntry(specifier: KtSuperTypeEntry) {
// super.visitSuperTypeEntry(specifier)
// if (specifier.allowsAbsenceOfMatch) {
// specifier.parent.setAbsenceOfMatchHandler()
// specifier.parent.parent.setAbsenceOfMatchHandlerIfApplicable()
// }
// }
override fun visitKDoc(kDoc: KDoc) {
getHandler(kDoc).setFilter { it is KDoc }
}
override fun visitKDocLink(link: KDocLink) {
getHandler(link).setFilter { it is KDocLink }
}
override fun visitKDocTag(tag: KDocTag) {
getHandler(tag).setFilter { it is KDocTag }
}
private fun PsiElement.setAbsenceOfMatchHandler() {
setHandler(this, absenceOfMatchHandler(this))
}
private fun PsiElement.setAbsenceOfMatchHandlerIfApplicable(considerAllChildren: Boolean = false) {
val childrenAllowAbsenceOfMatch =
if (considerAllChildren) this.allChildren.all { it.allowsAbsenceOfMatch }
else this.children.all { it.allowsAbsenceOfMatch }
if (childrenAllowAbsenceOfMatch)
setAbsenceOfMatchHandler()
}
private fun absenceOfMatchHandler(element: PsiElement): SubstitutionHandler =
SubstitutionHandler("${element.hashCode()}_optional", false, 0, 1, false)
private val PsiElement.allowsAbsenceOfMatch: Boolean
get() {
val handler = getHandler(this)
return handler is SubstitutionHandler && handler.minOccurs == 0
}
private fun PsiElement.resetCountFilter() {
val handler = getHandler(this)
if (handler is SubstitutionHandler && (handler.minOccurs != 1 || handler.maxOccurs != 1)) {
val newHandler = SubstitutionHandler(handler.name, handler.isTarget, 1, 1, false)
val predicate = handler.predicate
if (predicate != null) newHandler.predicate = predicate
newHandler.filter = handler.filter
setHandler(this, newHandler)
}
}
companion object {
val WITHIN_HIERARCHY: Key<Boolean> = Key<Boolean>("withinHierarchy")
private fun deparIfNecessary(element: PsiElement): PsiElement =
if (element is KtParenthesizedExpression) element.deparenthesize() else element
val ExpressionFilter: NodeFilter = NodeFilter {
val element = deparIfNecessary(it)
element is KtExpression
}
val ArrayAccessExpressionFilter: NodeFilter = NodeFilter {
val element = deparIfNecessary(it)
element is KtArrayAccessExpression || element is KtDotQualifiedExpression
}
/** translated op matching */
val CallExpressionFilter: NodeFilter = NodeFilter {
val element = deparIfNecessary(it)
element is KtCallExpression || element is KtDotQualifiedExpression
}
/** translated op matching */
val UnaryExpressionFilter: NodeFilter = NodeFilter {
val element = deparIfNecessary(it)
element is KtUnaryExpression || element is KtDotQualifiedExpression
}
val BinaryExpressionFilter: NodeFilter = NodeFilter {
val element = deparIfNecessary(it)
element is KtBinaryExpression || element is KtDotQualifiedExpression || element is KtPrefixExpression
}
val ConstantExpressionFilter: NodeFilter = NodeFilter {
val element = deparIfNecessary(it)
element is KtConstantExpression || element is KtParenthesizedExpression
}
val DotQualifiedExpressionFilter: NodeFilter = NodeFilter {
val element = deparIfNecessary(it)
element is KtDotQualifiedExpression || element is KtReferenceExpression
}
val ReferenceExpressionFilter: NodeFilter = NodeFilter {
val element = deparIfNecessary(it)
element is KtReferenceExpression
}
val ParameterFilter: NodeFilter = NodeFilter {
it is KtDeclaration || it is KtUserType || it is KtNameReferenceExpression
}
val DeclarationFilter: NodeFilter = NodeFilter {
it is KtDeclaration || it is KtTypeProjection || it is KtTypeElement || it is KtNameReferenceExpression
}
val CommentedDeclarationFilter: NodeFilter = NodeFilter {
it is PsiComment || DeclarationFilter.accepts(it)
}
val WhenConditionFiler: NodeFilter = NodeFilter {
it is KtWhenCondition
}
val SimpleNameSTEFilter: NodeFilter = NodeFilter {
it is KtSimpleNameStringTemplateEntry || it is KtBlockStringTemplateEntry
}
}
}
|
apache-2.0
|
bb735aa45781f45ec14497ea56bd2a57
| 40.938166 | 158 | 0.685276 | 5.501538 | false | false | false | false |
ingokegel/intellij-community
|
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SourceEntityImpl.kt
|
1
|
9068
|
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.util.*
import java.util.UUID
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SourceEntityImpl : SourceEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(SourceEntity::class.java, ChildSourceEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
@JvmField
var _data: String? = null
override val data: String
get() = _data!!
override val children: List<ChildSourceEntity>
get() = snapshot.extractOneToManyChildren<ChildSourceEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SourceEntityData?) : ModifiableWorkspaceEntityBase<SourceEntity>(), SourceEntity.Builder {
constructor() : this(SourceEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SourceEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field SourceEntity#data should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field SourceEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field SourceEntity#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SourceEntity
this.entitySource = dataSource.entitySource
this.data = dataSource.data
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
// List of non-abstract referenced types
var _children: List<ChildSourceEntity>? = emptyList()
override var children: List<ChildSourceEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ChildSourceEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<ChildSourceEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildSourceEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override fun getEntityData(): SourceEntityData = result ?: super.getEntityData() as SourceEntityData
override fun getEntityClass(): Class<SourceEntity> = SourceEntity::class.java
}
}
class SourceEntityData : WorkspaceEntityData<SourceEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SourceEntity> {
val modifiable = SourceEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SourceEntity {
val entity = SourceEntityImpl()
entity._data = data
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SourceEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SourceEntity(data, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SourceEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SourceEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
|
apache-2.0
|
dcf44b242631807122b64a466e4a2a56
| 34.284047 | 184 | 0.68273 | 5.346698 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/code-insight/inspections-shared/tests/k2/test/org/jetbrains/kotlin/idea/k2/codeInsight/intentions/shared/UnclearPrecedenceOfBinaryExpressionInspectionTest.kt
|
3
|
4838
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeInsight.intentions.shared
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeInsight.inspections.shared.UnclearPrecedenceOfBinaryExpressionInspection
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
class UnclearPrecedenceOfBinaryExpressionInspectionTest : KotlinLightCodeInsightFixtureTestCase() {
fun `test elvis elvis`() = doTest("fun foo(i: Int?, j: Int?, k: Int?) = i ?: j <caret>?: k")
fun `test elvis as`() = doTest(
"fun foo(i: Int?, j: Int?) = i ?: j<caret> as String?",
"fun foo(i: Int?, j: Int?) = i ?: (j as String?)"
)
fun `test elvis eqeq`() = doTest(
"fun foo(a: Int?, b: Int?, c: Int?) = <warning>a ?: b<caret> == c</warning>",
"fun foo(a: Int?, b: Int?, c: Int?) = (a ?: b) == c"
)
fun `test comments`() = doTest(
"fun test(i: Int?, b: Boolean?) = <warning>b /* a */ <caret>?: /* b */ i /* c */ == /* d */ null</warning>",
"fun test(i: Int?, b: Boolean?) = (b /* a */ ?: /* b */ i) /* c */ == /* d */ null"
)
fun `test quickfix is absent for same priority tokens`() = doTest("fun foo() = 1 + 2 <caret>+ 3")
fun `test put parentheses through already presented parentheses`() = doTest(
"fun foo(a: Int?) = a ?<caret>: (1 + 2 * 4)",
"fun foo(a: Int?) = a ?: (1 + (2 * 4))"
)
fun `test obvious arithmetic is reported with reportEvenObviousCases flag is on`() = doTest(
"fun foo() = <warning>1 + 2<caret> * 4</warning>",
"fun foo() = 1 + (2 * 4)",
reportEvenObviousCases = true
)
fun `test parentheses should be everywhere if reportEvenObviousCases flag is on`() = doTest(
"fun foo(a: Int?) = <warning>a ?: 1 + <caret>2 * 4</warning>",
"fun foo(a: Int?) = a ?: (1 + (2 * 4))",
reportEvenObviousCases = true
)
fun `test only non obvious parentheses should be put if reportEvenObviousCases flag is off`() = doTest(
"fun foo(a: Int?) = <warning>a ?: 1 + <caret>2 * 4</warning>",
"fun foo(a: Int?) = a ?: (1 + 2 * 4)"
)
fun `test elvis is`() = doTest(
"fun foo(a: Boolean?, b: Any) = <warning>a ?: <caret>b is Int</warning>",
"fun foo(a: Boolean?, b: Any) = (a ?: b) is Int"
)
fun `test elvis plus`() = doTest(
"fun foo(a: Int?) = <warning>a ?: <caret>1 + 2</warning>",
"fun foo(a: Int?) = a ?: (1 + 2)"
)
fun `test top level presented parentheses`() = doTest(
"fun foo() = <warning>(if (true) 1 else null) ?: <caret>1 xor 2</warning>",
"fun foo() = (if (true) 1 else null) ?: (1 xor 2)"
)
fun `test eq elvis`() = doTest("fun test(i: Int?): Int { val y: Int; y = i <caret>?: 1; return y}")
fun `test already has parentheses`() = doTest("fun foo(i: Int?) = (i <caret>?: 0) + 1")
fun `test infixFun plus`() = doTest(
"fun foo() = 1 xor 2 <caret>+ 8",
"fun foo() = 1 xor (2 + 8)"
)
fun `test plus range`() = doTest(
"fun foo() = 1 + <caret>2..4",
"fun foo() = (1 + 2)..4"
)
fun `test braces inside braces`() = doTest(
"fun foo() = ((1 + <caret>2))..4"
)
fun `test infixFun elvis`() = doTest(
"fun foo(a: Int?) = <warning>a ?: 1 <caret>xor 2</warning>",
"fun foo(a: Int?) = a ?: (1 xor 2)"
)
fun `test multiple infixFun`() = doTest(
"fun foo() = 0 xor 10<caret> and 2"
)
private fun doTest(before: String, after: String? = null, reportEvenObviousCases: Boolean = false) {
require(before.contains("<caret>"))
val unclearPrecedenceOfBinaryExpressionInspection = UnclearPrecedenceOfBinaryExpressionInspection()
unclearPrecedenceOfBinaryExpressionInspection.reportEvenObviousCases = reportEvenObviousCases
myFixture.enableInspections(unclearPrecedenceOfBinaryExpressionInspection)
try {
myFixture.configureByText("foo.kt", before)
myFixture.checkHighlighting(true, false, false)
val intentionMsg = KotlinBundle.message("unclear.precedence.of.binary.expression.quickfix")
if (after != null) {
val intentionAction = myFixture.findSingleIntention(intentionMsg)
myFixture.launchAction(intentionAction)
myFixture.checkResult(after)
} else {
TestCase.assertTrue(myFixture.filterAvailableIntentions(intentionMsg).isEmpty())
}
} finally {
myFixture.disableInspections(unclearPrecedenceOfBinaryExpressionInspection)
}
}
override fun isFirPlugin(): Boolean = true
}
|
apache-2.0
|
9bb9d9aa2aa30f139815341b96cb881f
| 40.715517 | 120 | 0.587433 | 3.882825 | false | true | false | false |
se-bastiaan/Marietje-Android
|
app/src/test/java/eu/se_bastiaan/marietje/data/ControlDataManagerTest.kt
|
1
|
8731
|
package eu.se_bastiaan.marietje.data
import eu.se_bastiaan.marietje.data.local.PreferencesHelper
import eu.se_bastiaan.marietje.data.model.Empty
import eu.se_bastiaan.marietje.data.model.Permissions
import eu.se_bastiaan.marietje.data.model.Queue
import eu.se_bastiaan.marietje.data.remote.ControlService
import eu.se_bastiaan.marietje.test.common.TestDataFactory
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
import rx.Observable
import rx.observers.TestSubscriber
@RunWith(MockitoJUnitRunner::class)
class ControlDataManagerTest {
@Mock
lateinit var mockControlService: ControlService
@Mock
lateinit var mockPreferencesHelper: PreferencesHelper
lateinit var dataManager: ControlDataManager
@Before
fun setUp() {
dataManager = ControlDataManager(mockControlService, mockPreferencesHelper)
}
@Test
fun csrfEmitsValues() {
val csrfToken = "csrf_token"
`when`(mockPreferencesHelper.csrfToken)
.thenReturn(csrfToken)
val response = TestDataFactory.makeNormalCsrfResponse()
`when`(mockControlService.csrf())
.thenReturn(Observable.just(response))
val result = TestSubscriber<String>()
dataManager.csrf().subscribe(result)
result.assertNoErrors()
result.assertReceivedOnNext(listOf(csrfToken))
}
@Test
fun queueEmitsValues() {
val response = TestDataFactory.makeQueueResponse()
`when`(mockControlService.queue())
.thenReturn(Observable.just(response))
val result = TestSubscriber<Queue>()
dataManager.queue().subscribe(result)
result.assertNoErrors()
result.assertReceivedOnNext(listOf(response))
}
@Test
fun skipEmitsValues() {
val response = Empty()
`when`(mockControlService.skip())
.thenReturn(Observable.just(response))
val result = TestSubscriber<Empty>()
dataManager.skip().subscribe(result)
result.assertNoErrors()
result.assertReceivedOnNext(listOf(response))
}
@Test
fun moveUpEmitsValues() {
val response = Empty()
`when`(mockControlService.moveUp(0))
.thenReturn(Observable.just(response))
val result = TestSubscriber<Empty>()
dataManager.moveUp(0).subscribe(result)
result.assertNoErrors()
result.assertReceivedOnNext(listOf(response))
}
@Test
fun moveDownEmitsValues() {
val response = Empty()
`when`(mockControlService.moveDown(0))
.thenReturn(Observable.just(response))
val result = TestSubscriber<Empty>()
dataManager.moveDown(0).subscribe(result)
result.assertNoErrors()
result.assertReceivedOnNext(listOf(response))
}
@Test
fun cancelEmitsValues() {
val response = Empty()
`when`(mockControlService.cancel(0))
.thenReturn(Observable.just(response))
val result = TestSubscriber<Empty>()
dataManager.cancel(0).subscribe(result)
result.assertNoErrors()
result.assertReceivedOnNext(listOf(response))
}
@Test
fun requestEmitsValues() {
val response = Empty()
`when`(mockControlService.request(0))
.thenReturn(Observable.just(response))
val result = TestSubscriber<Empty>()
dataManager.request(0).subscribe(result)
result.assertNoErrors()
result.assertReceivedOnNext(listOf(response))
}
@Test
fun volumeDownEmitsValues() {
val response = Empty()
`when`(mockControlService.volumeDown())
.thenReturn(Observable.just(response))
val result = TestSubscriber<Empty>()
dataManager.volumeDown().subscribe(result)
result.assertNoErrors()
result.assertReceivedOnNext(listOf(response))
}
@Test
fun volumeUpEmitsValues() {
val response = Empty()
`when`(mockControlService.volumeUp())
.thenReturn(Observable.just(response))
val result = TestSubscriber<Empty>()
dataManager.volumeUp().subscribe(result)
result.assertNoErrors()
result.assertReceivedOnNext(listOf(response))
}
@Test
fun permissionsEmitsValues() {
val response = TestDataFactory.makePermissionsResponse()
`when`(mockControlService.permissions())
.thenReturn(Observable.just(response))
val result = TestSubscriber<Permissions>()
dataManager.permissions().subscribe(result)
result.assertNoErrors()
result.assertReceivedOnNext(listOf(response))
}
@Test
fun csrfCallsApi() {
val response = TestDataFactory.makeNormalCsrfResponse()
`when`(mockControlService.csrf())
.thenReturn(Observable.just(response))
dataManager.csrf().subscribe()
verify<ControlService>(mockControlService).csrf()
}
@Test
fun queueCallsApi() {
val response = TestDataFactory.makeQueueResponse()
`when`(mockControlService.queue())
.thenReturn(Observable.just(response))
dataManager.queue().subscribe()
verify<ControlService>(mockControlService).queue()
}
@Test
fun skipCallsApi() {
val response = Empty()
`when`(mockControlService.skip())
.thenReturn(Observable.just(response))
dataManager.skip().subscribe()
verify<ControlService>(mockControlService).skip()
}
@Test
fun moveDownCallsApi() {
val response = Empty()
`when`(mockControlService.moveDown(0))
.thenReturn(Observable.just(response))
dataManager.moveDown(0).subscribe()
verify<ControlService>(mockControlService).moveDown(0)
}
@Test
fun moveUpCallsApi() {
val response = Empty()
`when`(mockControlService.moveUp(0))
.thenReturn(Observable.just(response))
dataManager.moveUp(0).subscribe()
verify<ControlService>(mockControlService).moveUp(0)
}
@Test
fun cancelCallsApi() {
val response = Empty()
`when`(mockControlService.cancel(0))
.thenReturn(Observable.just(response))
dataManager.cancel(0).subscribe()
verify<ControlService>(mockControlService).cancel(0)
}
@Test
fun requestCallsApi() {
val response = Empty()
`when`(mockControlService.request(0))
.thenReturn(Observable.just(response))
dataManager.request(0).subscribe()
verify<ControlService>(mockControlService).request(0)
}
@Test
fun volumeUpCallsApi() {
val response = Empty()
`when`(mockControlService.volumeUp())
.thenReturn(Observable.just(response))
dataManager.volumeUp().subscribe()
verify<ControlService>(mockControlService).volumeUp()
}
@Test
fun volumeDownCallsApi() {
val response = Empty()
`when`(mockControlService.volumeDown())
.thenReturn(Observable.just(response))
dataManager.volumeDown().subscribe()
verify<ControlService>(mockControlService).volumeDown()
}
@Test
fun permissionsCallsApi() {
val response = TestDataFactory.makePermissionsResponse()
`when`(mockControlService.permissions())
.thenReturn(Observable.just(response))
dataManager.permissions().subscribe()
verify<ControlService>(mockControlService).permissions()
}
@Test
fun csrfCallsPreferencesHelper() {
`when`(mockPreferencesHelper.csrfToken)
.thenReturn("csrf_token")
`when`(mockControlService.csrf())
.thenReturn(Observable.just(TestDataFactory.makeNormalCsrfResponse()))
dataManager.csrf().subscribe()
`when`(mockPreferencesHelper.csrfToken)
.thenReturn("csrf_token")
`when`(mockControlService.csrf())
.then {
`when`(mockPreferencesHelper.csrfToken)
.thenReturn("")
Observable.just(TestDataFactory.makeNormalCsrfResponse())
}
dataManager.csrf().subscribe()
verify<PreferencesHelper>(mockPreferencesHelper, times(2)).setCsrftoken("")
verify<PreferencesHelper>(mockPreferencesHelper, times(4)).csrfToken
verify<PreferencesHelper>(mockPreferencesHelper).setCsrftoken("csrf_token")
verify<ControlService>(mockControlService, times(2)).csrf()
}
}
|
apache-2.0
|
e7cba6a896dfe11ae1aaaf481e7a9b45
| 28.798635 | 86 | 0.645631 | 4.737385 | false | true | false | false |
ChristopherGittner/OSMBugs
|
app/src/main/java/org/gittner/osmbugs/keepright/KeeprightApi.kt
|
1
|
2815
|
package org.gittner.osmbugs.keepright
import android.net.Uri
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.coroutines.awaitStringResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.gittner.osmbugs.statics.Settings
import org.koin.core.KoinComponent
import org.osmdroid.api.IGeoPoint
class KeeprightApi : KoinComponent {
private val mSettings = Settings.getInstance()
suspend fun download(
center: IGeoPoint,
showIgnored: Boolean,
showTempIgnored: Boolean,
langGerman: Boolean
): ArrayList<KeeprightError> = withContext(Dispatchers.IO) {
val url = Uri.Builder()
.scheme("https")
.authority("keepright.at")
.appendPath("points.php")
.appendQueryParameter("show_ign", if (showIgnored) "1" else "0")
.appendQueryParameter("show_tmpign", if (showTempIgnored) "1" else "0")
.appendQueryParameter("ch", getSelectionString())
.appendQueryParameter("lat", center.latitude.toString())
.appendQueryParameter("lon", center.longitude.toString())
.appendQueryParameter("lang", if (langGerman) "de" else "en")
.build()
val response = Fuel.get(url.toString()).awaitStringResponse()
if (response.second.statusCode != 200) {
throw RuntimeException("Invalid Status Code: ${response.second.statusCode}")
}
KeeprightParser().parse(response.third)
}
suspend fun comment(schema: Long, id: Long, comment: String, state: KeeprightError.STATE) = withContext(Dispatchers.IO) {
val sState: String = when (state) {
KeeprightError.STATE.OPEN -> ""
KeeprightError.STATE.IGNORED -> "ignore"
KeeprightError.STATE.IGNORED_TMP -> "ignore_t"
}
val url = Uri.Builder()
.scheme("https")
.authority("keepright.at")
.appendPath("comment.php")
.appendQueryParameter("st", sState)
.appendQueryParameter("co", comment)
.appendQueryParameter("schema", schema.toString())
.appendQueryParameter("id", id.toString())
.build()
val response = Fuel.post(url.toString()).awaitStringResponse()
if (response.second.statusCode != 200) {
throw RuntimeException("Invalid Response: ${response.second.statusCode}")
}
}
private fun getSelectionString(): String {
// Unknown what 0 stands for but it's here for compatibility Reasons
var result = "0"
KeeprightError.ERROR_TYPE.values().forEach {
if (mSettings.Keepright.GetTypeEnabled(it)) {
result += ",${it.Type}"
}
}
return result
}
}
|
mit
|
8e465c8d7f21b8c42443be9467aaa666
| 35.571429 | 125 | 0.628774 | 4.555016 | false | false | false | false |
micolous/metrodroid
|
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/en1545/En1545Transaction.kt
|
1
|
11152
|
/*
* En1545Transaction.kt
*
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.en1545
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.transit.*
abstract class En1545Transaction : Transaction() {
abstract val parsed: En1545Parsed
protected open val routeNumber: Int?
get() = parsed.getInt(EVENT_ROUTE_NUMBER)
protected val routeVariant: Int?
get() = parsed.getInt(EVENT_ROUTE_VARIANT)
// Get the line name from the station.
override val routeNames: List<FormattedString>?
get() {
val route = lookup.getRouteName(
routeNumber,
routeVariant,
agency, transport)
if (route != null) {
return listOf(route)
}
val st = station ?: return emptyList()
return st.lineNames
}
// Get the line name from the station.
override val humanReadableLineIDs: List<String>
get() {
val route = lookup.getHumanReadableRouteId(
routeNumber,
routeVariant,
agency, transport)
if (route != null) {
return listOf(route)
}
val st = station ?: return emptyList()
return st.humanReadableLineIds
}
override val passengerCount: Int
get() = parsed.getIntOrZero(EVENT_PASSENGER_COUNT)
override val vehicleID: String?
get() {
val id = parsed.getIntOrZero(EVENT_VEHICLE_ID)
return if (id == 0) null else id.toString()
}
override val machineID: String?
get() {
val id = parsed.getIntOrZero(EVENT_DEVICE_ID)
return if (id == 0) null else id.toString()
}
private val eventCode: Int
get() = parsed.getIntOrZero(EVENT_CODE)
protected open val transport: Int
get() = getTransport(eventCode)
protected open val agency: Int?
get() = parsed.getInt(EVENT_SERVICE_PROVIDER)
override val station: Station?
get() = getStation(stationId)
override val timestamp
get() = parsed.getTimeStamp(EVENT, lookup.timeZone)
override val mode: Trip.Mode
get() = parsed.getInt(EVENT_CODE)?.let { eventCodeToMode(it) }
?: lookup.getMode(agency, parsed.getInt(EVENT_ROUTE_NUMBER))
protected abstract val lookup: En1545Lookup
override val fare: TransitCurrency?
get() {
val x = parsed.getInt(EVENT_PRICE_AMOUNT) ?: return null
return lookup.parseCurrency(x)
}
protected open val eventType: Int
get() = eventCode and 0xf
override val isTapOn: Boolean
get() {
val eventCode = eventType
return eventCode == EVENT_TYPE_BOARD || eventCode == EVENT_TYPE_BOARD_TRANSFER
}
override val isTapOff: Boolean
get() {
val eventCode = eventType
return eventCode == EVENT_TYPE_EXIT || eventCode == EVENT_TYPE_EXIT_TRANSFER
}
override val isTransfer: Boolean
get() {
val eventCode = eventType
return eventCode == EVENT_TYPE_BOARD_TRANSFER || eventCode == EVENT_TYPE_EXIT_TRANSFER
}
protected open val stationId: Int?
get() = parsed.getInt(EVENT_LOCATION_ID)
// 0x2: The tap-on was rejected (insufficient funds, Adelaide Metrocard).
// 0xb: The tap-on was rejected (outside of validity zone, RicaricaMi).
// Successful events don't set EVENT_RESULT or set it to 0.
override val isRejected: Boolean
get() = parsed.getIntOrZero(EVENT_RESULT) != 0
override fun getAgencyName(isShort: Boolean) = lookup.getAgencyName(agency, isShort)
open fun getStation(station: Int?): Station? {
return if (station == null) null else lookup.getStation(station, agency, transport)
}
override fun isSameTrip(other: Transaction): Boolean {
if (other !is En1545Transaction)
return false
return (transport == other.transport
&& parsed.getIntOrZero(EVENT_SERVICE_PROVIDER) == other.parsed.getIntOrZero(EVENT_SERVICE_PROVIDER)
&& parsed.getIntOrZero(EVENT_ROUTE_NUMBER) == other.parsed.getIntOrZero(EVENT_ROUTE_NUMBER)
&& parsed.getIntOrZero(EVENT_ROUTE_VARIANT) == other.parsed.getIntOrZero(EVENT_ROUTE_VARIANT))
}
override fun getRawFields(level: TransitData.RawLevel): String? = parsed.makeString(",",
when (level) {
TransitData.RawLevel.UNKNOWN_ONLY -> setOf(
En1545FixedInteger.dateName(EVENT),
En1545FixedInteger.datePackedName(EVENT),
En1545FixedInteger.timePacked11LocalName(EVENT),
En1545FixedInteger.timeLocalName(EVENT),
En1545FixedInteger.timeName(EVENT),
En1545FixedInteger.dateTimeName(EVENT),
En1545FixedInteger.dateTimeLocalName(EVENT),
En1545FixedInteger.dateName(EVENT_FIRST_STAMP),
En1545FixedInteger.timePacked11LocalName(EVENT_FIRST_STAMP),
En1545FixedInteger.timeLocalName(EVENT_FIRST_STAMP),
En1545FixedInteger.dateTimeName(EVENT_FIRST_STAMP),
En1545FixedInteger.dateTimeLocalName(EVENT_FIRST_STAMP),
En1545FixedInteger.datePackedName(En1545Subscription.CONTRACT_END),
En1545FixedInteger.timePacked11LocalName(En1545Subscription.CONTRACT_END),
EVENT_ROUTE_NUMBER,
EVENT_ROUTE_VARIANT,
EVENT_CONTRACT_POINTER,
EVENT_SERVICE_PROVIDER,
EVENT_AUTHENTICATOR,
EVENT_CODE,
EVENT_DEVICE_ID,
EVENT_VEHICLE_ID,
EVENT_FIRST_LOCATION_ID,
EVENT_PRICE_AMOUNT,
EVENT_LOCATION_ID
)
else -> setOf()
})
override fun toString(): String = "En1545Transaction: $parsed"
companion object {
const val EVENT_ROUTE_NUMBER = "EventRouteNumber"
const val EVENT_ROUTE_VARIANT = "EventRouteVariant"
const val EVENT_PASSENGER_COUNT = "EventPassengerCount"
const val EVENT_VEHICLE_ID = "EventVehicleId"
const val EVENT_CODE = "EventCode"
const val EVENT_SERVICE_PROVIDER = "EventServiceProvider"
const val EVENT = "Event"
const val EVENT_PRICE_AMOUNT = "EventPriceAmount"
const val EVENT_LOCATION_ID = "EventLocationId"
const val EVENT_UNKNOWN_A = "EventUnknownA"
const val EVENT_UNKNOWN_B = "EventUnknownB"
const val EVENT_UNKNOWN_C = "EventUnknownC"
const val EVENT_UNKNOWN_D = "EventUnknownD"
const val EVENT_UNKNOWN_E = "EventUnknownE"
const val EVENT_UNKNOWN_F = "EventUnknownF"
const val EVENT_UNKNOWN_G = "EventUnknownG"
const val EVENT_UNKNOWN_H = "EventUnknownH"
const val EVENT_UNKNOWN_I = "EventUnknownI"
const val EVENT_CONTRACT_POINTER = "EventContractPointer"
const val EVENT_CONTRACT_TARIFF = "EventContractTariff"
const val EVENT_SERIAL_NUMBER = "EventSerialNumber"
const val EVENT_AUTHENTICATOR = "EventAuthenticator"
const val EVENT_NETWORK_ID = "EventNetworkId"
const val EVENT_FIRST_STAMP = "EventFirstStamp"
const val EVENT_FIRST_LOCATION_ID = "EventFirstLocationId"
const val EVENT_DEVICE_ID = "EventDeviceId"
const val EVENT_RESULT = "EventResult"
const val EVENT_DISPLAY_DATA = "EventDisplayData"
const val EVENT_NOT_OK_COUNTER = "EventNotOkCounter"
const val EVENT_DESTINATION = "EventDestination"
const val EVENT_LOCATION_GATE = "EventLocationGate"
const val EVENT_DEVICE = "EventDevice"
const val EVENT_JOURNEY_RUN = "EventJourneyRun"
const val EVENT_VEHICULE_CLASS = "EventVehiculeClass"
const val EVENT_LOCATION_TYPE = "EventLocationType"
const val EVENT_EMPLOYEE = "EventEmployee"
const val EVENT_LOCATION_REFERENCE = "EventLocationReference"
const val EVENT_JOURNEY_INTERCHANGES = "EventJourneyInterchanges"
const val EVENT_PERIOD_JOURNEYS = "EventPeriodJourneys"
const val EVENT_TOTAL_JOURNEYS = "EventTotalJourneys"
const val EVENT_JOURNEY_DISTANCE = "EventJourneyDistance"
const val EVENT_PRICE_UNIT = "EventPriceUnit"
const val EVENT_DATA_SIMULATION = "EventDataSimulation"
const val EVENT_DATA_TRIP = "EventDataTrip"
const val EVENT_DATA_ROUTE_DIRECTION = "EventDataRouteDirection"
private const val EVENT_TYPE_BOARD = 1
private const val EVENT_TYPE_EXIT = 2
private const val EVENT_TYPE_BOARD_TRANSFER = 6
private const val EVENT_TYPE_EXIT_TRANSFER = 7
const val EVENT_TYPE_TOPUP = 13
const val EVENT_TYPE_CANCELLED = 9
const val TRANSPORT_UNSPECIFIED = 0
const val TRANSPORT_BUS = 1
private const val TRANSPORT_INTERCITY_BUS = 2
const val TRANSPORT_METRO = 3
const val TRANSPORT_TRAM = 4
const val TRANSPORT_TRAIN = 5
private const val TRANSPORT_FERRY = 6
private const val TRANSPORT_PARKING = 8
private const val TRANSPORT_TAXI = 9
private const val TRANSPORT_TOPUP = 11
private const val TAG = "En1545Transaction"
private fun getTransport(eventCode: Int): Int {
return eventCode shr 4
}
private fun eventCodeToMode(ec: Int): Trip.Mode? {
if (ec and 0xf == EVENT_TYPE_TOPUP)
return Trip.Mode.TICKET_MACHINE
return when (getTransport(ec)) {
TRANSPORT_BUS, TRANSPORT_INTERCITY_BUS -> Trip.Mode.BUS
TRANSPORT_METRO -> Trip.Mode.METRO
TRANSPORT_TRAM -> Trip.Mode.TRAM
TRANSPORT_TRAIN -> Trip.Mode.TRAIN
TRANSPORT_FERRY -> Trip.Mode.FERRY
TRANSPORT_PARKING, TRANSPORT_TAXI -> Trip.Mode.OTHER
TRANSPORT_TOPUP -> Trip.Mode.TICKET_MACHINE
TRANSPORT_UNSPECIFIED -> null
else -> Trip.Mode.OTHER
}
}
}
}
|
gpl-3.0
|
52a5f93ea09c0516d844f4cab1e237ee
| 39.849817 | 115 | 0.61953 | 4.43949 | false | false | false | false |
eneim/android-UniversalMusicPlayer
|
media/src/main/java/com/example/android/uamp/media/library/MusicSource.kt
|
1
|
7829
|
/*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media.library
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.annotation.IntDef
import android.support.v4.media.MediaMetadataCompat
import android.util.Log
import com.example.android.uamp.media.MusicService
import com.example.android.uamp.media.extensions.album
import com.example.android.uamp.media.extensions.albumArtist
import com.example.android.uamp.media.extensions.artist
import com.example.android.uamp.media.extensions.containsCaseInsensitive
import com.example.android.uamp.media.extensions.genre
import com.example.android.uamp.media.extensions.title
/**
* Interface used by [MusicService] for looking up [MediaMetadataCompat] objects.
*
* Because Kotlin provides methods such as [Iterable.find] and [Iterable.filter],
* this is a convient interface to have on sources.
*/
interface MusicSource : Iterable<MediaMetadataCompat> {
/**
* Method which will perform a given action after this [MusicSource] is ready to be used.
*
* @param performAction A lambda expression to be called with a boolean parameter when
* the source is ready. `true` indicates the source was successfully prepared, `false`
* indicates an error occurred.
*/
fun whenReady(performAction: (Boolean) -> Unit): Boolean
fun search(query: String, extras: Bundle): List<MediaMetadataCompat>
}
@IntDef(STATE_CREATED,
STATE_INITIALIZING,
STATE_INITIALIZED,
STATE_ERROR)
@Retention(AnnotationRetention.SOURCE)
annotation class State
/**
* State indicating the source was created, but no initialization has performed.
*/
const val STATE_CREATED = 1
/**
* State indicating initialization of the source is in progress.
*/
const val STATE_INITIALIZING = 2
/**
* State indicating the source has been initialized and is ready to be used.
*/
const val STATE_INITIALIZED = 3
/**
* State indicating an error has occurred.
*/
const val STATE_ERROR = 4
/**
* Base class for music sources in UAMP.
*/
abstract class AbstractMusicSource : MusicSource {
@State
var state: Int = STATE_CREATED
set(value) {
if (value == STATE_INITIALIZED || value == STATE_ERROR) {
synchronized(onReadyListeners) {
field = value
onReadyListeners.forEach { listener ->
listener(state == STATE_INITIALIZED)
}
}
} else {
field = value
}
}
private val onReadyListeners = mutableListOf<(Boolean) -> Unit>()
/**
* Performs an action when this MusicSource is ready.
*
* This method is *not* threadsafe. Ensure actions and state changes are only performed
* on a single thread.
*/
override fun whenReady(performAction: (Boolean) -> Unit): Boolean =
when (state) {
STATE_CREATED, STATE_INITIALIZING -> {
onReadyListeners += performAction
false
}
else -> {
performAction(state != STATE_ERROR)
true
}
}
/**
* Handles searching a [MusicSource] from a focused voice search, often coming
* from the Google Assistant.
*/
override fun search(query: String, extras: Bundle): List<MediaMetadataCompat> {
// First attempt to search with the "focus" that's provided in the extras.
val focusSearchResult = when (extras[MediaStore.EXTRA_MEDIA_FOCUS]) {
MediaStore.Audio.Genres.ENTRY_CONTENT_TYPE -> {
// For a Genre focused search, only genre is set.
val genre = extras[EXTRA_MEDIA_GENRE]
Log.d(TAG, "Focused genre search: '$genre'")
filter { song ->
song.genre == genre
}
}
MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE -> {
// For an Artist focused search, only the artist is set.
val artist = extras[MediaStore.EXTRA_MEDIA_ARTIST]
Log.d(TAG, "Focused artist search: '$artist'")
filter { song ->
(song.artist == artist || song.albumArtist == artist)
}
}
MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE -> {
// For an Album focused search, album and artist are set.
val artist = extras[MediaStore.EXTRA_MEDIA_ARTIST]
val album = extras[MediaStore.EXTRA_MEDIA_ALBUM]
Log.d(TAG, "Focused album search: album='$album' artist='$artist")
filter { song ->
(song.artist == artist || song.albumArtist == artist) && song.album == album
}
}
MediaStore.Audio.Media.ENTRY_CONTENT_TYPE -> {
// For a Song (aka Media) focused search, title, album, and artist are set.
val title = extras[MediaStore.EXTRA_MEDIA_TITLE]
val album = extras[MediaStore.EXTRA_MEDIA_ALBUM]
val artist = extras[MediaStore.EXTRA_MEDIA_ARTIST]
Log.d(TAG, "Focused media search: title='$title' album='$album' artist='$artist")
filter { song ->
(song.artist == artist || song.albumArtist == artist) && song.album == album
&& song.title == title
}
}
else -> {
// There isn't a focus, so no results yet.
emptyList()
}
}
// If there weren't any results from the focused search (or if there wasn't a focus
// to begin with), try to find any matches given the 'query' provided, searching against
// a few of the fields.
// In this sample, we're just checking a few fields with the provided query, but in a
// more complex app, more logic could be used to find fuzzy matches, etc...
if (focusSearchResult.isEmpty()) {
return if (query.isNotBlank()) {
Log.d(TAG, "Unfocused search for '$query'")
filter { song ->
song.title.containsCaseInsensitive(query)
|| song.genre.containsCaseInsensitive(query)
}
} else {
// If the user asked to "play music", or something similar, the query will also
// be blank. Given the small catalog of songs in the sample, just return them
// all, shuffled, as something to play.
Log.d(TAG, "Unfocused search without keyword")
return shuffled()
}
} else {
return focusSearchResult
}
}
/**
* [MediaStore.EXTRA_MEDIA_GENRE] is missing on API 19. Hide this fact by using our
* own version of it.
*/
private val EXTRA_MEDIA_GENRE
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
MediaStore.EXTRA_MEDIA_GENRE
} else {
"android.intent.extra.genre"
}
}
private const val TAG = "MusicSource"
|
apache-2.0
|
d235c72376f2fd49597eac832945c6ff
| 37.377451 | 97 | 0.602248 | 4.693645 | false | false | false | false |
iPoli/iPoli-android
|
app/src/main/java/io/ipoli/android/common/text/DateFormatter.kt
|
1
|
2161
|
package io.ipoli.android.common.text
import android.content.Context
import io.ipoli.android.R
import io.ipoli.android.common.datetime.DateUtils
import org.threeten.bp.DayOfWeek
import org.threeten.bp.LocalDate
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.format.TextStyle
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by Venelin Valkov <[email protected]>
* on 8/22/17.
*/
object DateFormatter {
private val DEFAULT_EMPTY_VALUE = "Don't know"
private val DEFAULT_DATE_FORMAT = SimpleDateFormat("dd MMM yy", Locale.getDefault())
private val DAY_WEEK_FORMATTER = DateTimeFormatter.ofPattern("d MMM")
fun format(context: Context, date: LocalDate?): String {
if (date == null) {
return DEFAULT_EMPTY_VALUE
}
if (DateUtils.isToday(date)) {
return context.getString(R.string.today)
}
if(DateUtils.isYesterday(date)) {
return context.getString(R.string.yesterday)
}
return if (DateUtils.isTomorrow(date)) {
context.getString(R.string.tomorrow)
} else DEFAULT_DATE_FORMAT.format(DateUtils.toStartOfDay(date))
}
@JvmOverloads
fun formatWithoutYear(
context: Context,
date: LocalDate?,
emptyValue: String = DEFAULT_EMPTY_VALUE,
currentDate: LocalDate? = null
): String {
if (date == null) {
return emptyValue
}
if (DateUtils.isToday(date)) {
return context.getString(R.string.today)
}
if (DateUtils.isTomorrow(date)) {
return context.getString(R.string.tomorrow)
}
if (DateUtils.isYesterday(date)) {
return context.getString(R.string.yesterday)
}
if (currentDate != null) {
if (currentDate.with(DayOfWeek.MONDAY).isEqual(date.with(DayOfWeek.MONDAY))) {
return date.dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault())
}
}
return DAY_WEEK_FORMATTER.format(date)
}
fun formatDayWithWeek(date: LocalDate): String = DAY_WEEK_FORMATTER.format(date)
}
|
gpl-3.0
|
38bb02b676ef66944f07e4df5114c20e
| 31.757576 | 90 | 0.645997 | 4.228963 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/code-insight/api/src/org/jetbrains/kotlin/idea/codeinsight/api/applicators/AbstractKotlinDiagnosticBasedInspection.kt
|
4
|
1406
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeinsight.api.applicators
import org.jetbrains.kotlin.analysis.api.components.KtDiagnosticCheckerFilter
import org.jetbrains.kotlin.analysis.api.diagnostics.KtDiagnosticWithPsi
import org.jetbrains.kotlin.psi.KtElement
import kotlin.reflect.KClass
abstract class AbstractKotlinDiagnosticBasedInspection<PSI : KtElement, DIAGNOSTIC : KtDiagnosticWithPsi<PSI>, INPUT : KotlinApplicatorInput>(
elementType: KClass<PSI>,
) : AbstractKotlinApplicatorBasedInspection<PSI, INPUT>(elementType) {
abstract fun getDiagnosticType(): KClass<DIAGNOSTIC>
abstract fun getInputByDiagnosticProvider(): KotlinApplicatorInputByDiagnosticProvider<PSI, DIAGNOSTIC, INPUT>
final override fun getInputProvider(): KotlinApplicatorInputProvider<PSI, INPUT> = inputProvider { psi ->
val diagnostics = psi.getDiagnostics(KtDiagnosticCheckerFilter.ONLY_EXTENDED_CHECKERS)
val diagnosticType = getDiagnosticType()
val suitableDiagnostics = diagnostics.filterIsInstance(diagnosticType.java)
val diagnostic = suitableDiagnostics.firstOrNull() ?: return@inputProvider null
// TODO handle case with multiple diagnostics on single element
with(getInputByDiagnosticProvider()) { createInfo(diagnostic) }
}
}
|
apache-2.0
|
f172f97b4b83989c34230965d010e4ed
| 51.074074 | 142 | 0.794452 | 4.985816 | false | false | false | false |
AsamK/TextSecure
|
app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/review/MediaReviewFragment.kt
|
1
|
18910
|
package org.thoughtcrime.securesms.mediasend.v2.review
import android.animation.Animator
import android.animation.AnimatorSet
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import android.widget.ViewSwitcher
import androidx.activity.OnBackPressedCallback
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import app.cash.exhaustive.Exhaustive
import io.reactivex.rxjava3.disposables.CompositeDisposable
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.TransportOption
import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey
import org.thoughtcrime.securesms.conversation.mutiselect.forward.MultiselectForwardFragment
import org.thoughtcrime.securesms.conversation.mutiselect.forward.MultiselectForwardFragmentArgs
import org.thoughtcrime.securesms.mediasend.MediaSendActivityResult
import org.thoughtcrime.securesms.mediasend.v2.HudCommand
import org.thoughtcrime.securesms.mediasend.v2.MediaAnimations
import org.thoughtcrime.securesms.mediasend.v2.MediaSelectionNavigator
import org.thoughtcrime.securesms.mediasend.v2.MediaSelectionNavigator.Companion.requestPermissionsForGallery
import org.thoughtcrime.securesms.mediasend.v2.MediaSelectionState
import org.thoughtcrime.securesms.mediasend.v2.MediaSelectionViewModel
import org.thoughtcrime.securesms.mediasend.v2.MediaValidator
import org.thoughtcrime.securesms.mms.SentMediaQuality
import org.thoughtcrime.securesms.permissions.Permissions
import org.thoughtcrime.securesms.util.MediaUtil
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.fragments.requireListener
import org.thoughtcrime.securesms.util.views.TouchInterceptingFrameLayout
import org.thoughtcrime.securesms.util.visible
/**
* Allows the user to view and edit selected media.
*/
class MediaReviewFragment : Fragment(R.layout.v2_media_review_fragment) {
private val sharedViewModel: MediaSelectionViewModel by viewModels(
ownerProducer = { requireActivity() }
)
private lateinit var callback: Callback
private lateinit var drawToolButton: View
private lateinit var cropAndRotateButton: View
private lateinit var qualityButton: ImageView
private lateinit var saveButton: View
private lateinit var sendButton: View
private lateinit var addMediaButton: View
private lateinit var viewOnceButton: ViewSwitcher
private lateinit var viewOnceMessage: TextView
private lateinit var addMessageButton: TextView
private lateinit var addMessageEntry: TextView
private lateinit var recipientDisplay: TextView
private lateinit var pager: ViewPager2
private lateinit var controls: ConstraintLayout
private lateinit var selectionRecycler: RecyclerView
private lateinit var controlsShade: View
private lateinit var progress: ProgressBar
private lateinit var progressWrapper: TouchInterceptingFrameLayout
private val navigator = MediaSelectionNavigator(
toGallery = R.id.action_mediaReviewFragment_to_mediaGalleryFragment,
)
private var animatorSet: AnimatorSet? = null
private var disposables: CompositeDisposable? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
postponeEnterTransition()
callback = requireListener()
drawToolButton = view.findViewById(R.id.draw_tool)
cropAndRotateButton = view.findViewById(R.id.crop_and_rotate_tool)
qualityButton = view.findViewById(R.id.quality_selector)
saveButton = view.findViewById(R.id.save_to_media)
sendButton = view.findViewById(R.id.send)
addMediaButton = view.findViewById(R.id.add_media)
viewOnceButton = view.findViewById(R.id.view_once_toggle)
addMessageButton = view.findViewById(R.id.add_a_message)
addMessageEntry = view.findViewById(R.id.add_a_message_entry)
recipientDisplay = view.findViewById(R.id.recipient)
pager = view.findViewById(R.id.media_pager)
controls = view.findViewById(R.id.controls)
selectionRecycler = view.findViewById(R.id.selection_recycler)
controlsShade = view.findViewById(R.id.controls_shade)
viewOnceMessage = view.findViewById(R.id.view_once_message)
progress = view.findViewById(R.id.progress)
progressWrapper = view.findViewById(R.id.progress_wrapper)
DrawableCompat.setTint(progress.indeterminateDrawable, Color.WHITE)
progressWrapper.setOnInterceptTouchEventListener { true }
val pagerAdapter = MediaReviewFragmentPagerAdapter(this)
disposables = CompositeDisposable()
disposables?.add(
sharedViewModel.hudCommands.subscribe {
when (it) {
HudCommand.ResumeEntryTransition -> startPostponedEnterTransition()
else -> Unit
}
}
)
pager.adapter = pagerAdapter
drawToolButton.setOnClickListener {
sharedViewModel.sendCommand(HudCommand.StartDraw)
}
cropAndRotateButton.setOnClickListener {
sharedViewModel.sendCommand(HudCommand.StartCropAndRotate)
}
qualityButton.setOnClickListener {
QualitySelectorBottomSheetDialog.show(parentFragmentManager)
}
saveButton.setOnClickListener {
sharedViewModel.sendCommand(HudCommand.SaveMedia)
}
setFragmentResultListener(MultiselectForwardFragment.RESULT_KEY) { _, bundle ->
val parcelizedKeys: List<ContactSearchKey.ParcelableRecipientSearchKey> = bundle.getParcelableArrayList(MultiselectForwardFragment.RESULT_SELECTION)!!
val contactSearchKeys = parcelizedKeys.map { it.asRecipientSearchKey() }
performSend(contactSearchKeys)
}
sendButton.setOnClickListener {
if (sharedViewModel.isContactSelectionRequired) {
val args = MultiselectForwardFragmentArgs(false, title = R.string.MediaReviewFragment__send_to)
MultiselectForwardFragment.showFullScreen(parentFragmentManager, args)
} else {
performSend()
}
}
addMediaButton.setOnClickListener {
launchGallery()
}
viewOnceButton.setOnClickListener {
sharedViewModel.incrementViewOnceState()
}
addMessageButton.setOnClickListener {
AddMessageDialogFragment.show(parentFragmentManager, sharedViewModel.state.value?.message)
}
addMessageEntry.setOnClickListener {
AddMessageDialogFragment.show(parentFragmentManager, sharedViewModel.state.value?.message)
}
if (sharedViewModel.isReply) {
addMessageButton.setText(R.string.MediaReviewFragment__add_a_reply)
}
pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
sharedViewModel.setFocusedMedia(position)
}
})
val selectionAdapter = MappingAdapter()
MediaReviewAddItem.register(selectionAdapter) {
launchGallery()
}
MediaReviewSelectedItem.register(selectionAdapter) { media, isSelected ->
if (isSelected) {
sharedViewModel.removeMedia(media)
} else {
sharedViewModel.setFocusedMedia(media)
}
}
selectionRecycler.adapter = selectionAdapter
ItemTouchHelper(MediaSelectionItemTouchHelper(sharedViewModel)).attachToRecyclerView(selectionRecycler)
sharedViewModel.state.observe(viewLifecycleOwner) { state ->
pagerAdapter.submitMedia(state.selectedMedia)
selectionAdapter.submitList(
state.selectedMedia.map { MediaReviewSelectedItem.Model(it, state.focusedMedia == it) } + MediaReviewAddItem.Model
)
presentSendButton(state.transportOption)
presentPager(state)
presentAddMessageEntry(state.message)
presentImageQualityToggle(state.quality)
viewOnceButton.displayedChild = if (state.viewOnceToggleState == MediaSelectionState.ViewOnceToggleState.ONCE) 1 else 0
computeViewStateAndAnimate(state)
}
sharedViewModel.mediaErrors.observe(viewLifecycleOwner, this::handleMediaValidatorFilterError)
requireActivity().onBackPressedDispatcher.addCallback(
viewLifecycleOwner,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
callback.onPopFromReview()
}
}
)
}
override fun onResume() {
super.onResume()
sharedViewModel.kick()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults)
}
override fun onDestroyView() {
disposables?.dispose()
super.onDestroyView()
}
private fun handleMediaValidatorFilterError(error: MediaValidator.FilterError) {
@Exhaustive
when (error) {
MediaValidator.FilterError.ItemTooLarge -> Toast.makeText(requireContext(), R.string.MediaReviewFragment__one_or_more_items_were_too_large, Toast.LENGTH_SHORT).show()
MediaValidator.FilterError.ItemInvalidType -> Toast.makeText(requireContext(), R.string.MediaReviewFragment__one_or_more_items_were_invalid, Toast.LENGTH_SHORT).show()
MediaValidator.FilterError.TooManyItems -> Toast.makeText(requireContext(), R.string.MediaReviewFragment__too_many_items_selected, Toast.LENGTH_SHORT).show()
is MediaValidator.FilterError.NoItems -> {
if (error.cause != null) {
handleMediaValidatorFilterError(error.cause)
} else {
Toast.makeText(requireContext(), R.string.MediaReviewFragment__one_or_more_items_were_invalid, Toast.LENGTH_SHORT).show()
}
callback.onNoMediaSelected()
}
}
}
private fun launchGallery() {
val controller = findNavController()
requestPermissionsForGallery {
navigator.goToGallery(controller)
}
}
private fun performSend(selection: List<ContactSearchKey> = listOf()) {
progressWrapper.visible = true
progressWrapper.animate()
.setStartDelay(300)
.setInterpolator(MediaAnimations.interpolator)
.alpha(1f)
sharedViewModel
.send(selection.filterIsInstance(ContactSearchKey.RecipientSearchKey::class.java))
.subscribe(
{ result -> callback.onSentWithResult(result) },
{ error -> callback.onSendError(error) },
{ callback.onSentWithoutResult() }
)
}
private fun presentAddMessageEntry(message: CharSequence?) {
addMessageEntry.setText(message, TextView.BufferType.SPANNABLE)
}
private fun presentImageQualityToggle(quality: SentMediaQuality) {
qualityButton.setImageResource(
when (quality) {
SentMediaQuality.STANDARD -> R.drawable.ic_sq_36
SentMediaQuality.HIGH -> R.drawable.ic_hq_36
}
)
}
private fun presentSendButton(transportOption: TransportOption) {
val sendButtonTint = if (transportOption.type == TransportOption.Type.TEXTSECURE) {
R.color.core_ultramarine
} else {
R.color.core_grey_50
}
ViewCompat.setBackgroundTintList(sendButton, ColorStateList.valueOf(ContextCompat.getColor(requireContext(), sendButtonTint)))
}
private fun presentPager(state: MediaSelectionState) {
pager.isUserInputEnabled = state.isTouchEnabled
val indexOfSelectedItem = state.selectedMedia.indexOf(state.focusedMedia)
if (pager.currentItem == indexOfSelectedItem) {
return
}
if (indexOfSelectedItem != -1) {
pager.setCurrentItem(indexOfSelectedItem, false)
} else {
pager.setCurrentItem(0, false)
}
}
private fun computeViewStateAndAnimate(state: MediaSelectionState) {
this.animatorSet?.cancel()
val animators = mutableListOf<Animator>()
animators.addAll(computeAddMessageAnimators(state))
animators.addAll(computeViewOnceButtonAnimators(state))
animators.addAll(computeAddMediaButtonsAnimators(state))
animators.addAll(computeSendButtonAnimators(state))
animators.addAll(computeSaveButtonAnimators(state))
animators.addAll(computeQualityButtonAnimators(state))
animators.addAll(computeCropAndRotateButtonAnimators(state))
animators.addAll(computeDrawToolButtonAnimators(state))
animators.addAll(computeRecipientDisplayAnimators(state))
animators.addAll(computeControlsShadeAnimators(state))
val animatorSet = AnimatorSet()
animatorSet.playTogether(animators)
animatorSet.interpolator = MediaAnimations.interpolator
animatorSet.start()
this.animatorSet = animatorSet
}
private fun computeControlsShadeAnimators(state: MediaSelectionState): List<Animator> {
return if (state.isTouchEnabled) {
listOf(MediaReviewAnimatorController.getFadeInAnimator(controlsShade))
} else {
listOf(MediaReviewAnimatorController.getFadeOutAnimator(controlsShade))
}
}
private fun computeAddMessageAnimators(state: MediaSelectionState): List<Animator> {
return when {
!state.isTouchEnabled -> {
listOf(
MediaReviewAnimatorController.getFadeOutAnimator(viewOnceMessage),
MediaReviewAnimatorController.getFadeOutAnimator(addMessageButton),
MediaReviewAnimatorController.getFadeOutAnimator(addMessageEntry)
)
}
state.viewOnceToggleState == MediaSelectionState.ViewOnceToggleState.ONCE -> {
listOf(
MediaReviewAnimatorController.getFadeInAnimator(viewOnceMessage),
MediaReviewAnimatorController.getFadeOutAnimator(addMessageButton),
MediaReviewAnimatorController.getFadeOutAnimator(addMessageEntry)
)
}
state.message.isNullOrEmpty() -> {
listOf(
MediaReviewAnimatorController.getFadeOutAnimator(viewOnceMessage),
MediaReviewAnimatorController.getFadeInAnimator(addMessageButton),
MediaReviewAnimatorController.getFadeOutAnimator(addMessageEntry)
)
}
else -> {
listOf(
MediaReviewAnimatorController.getFadeOutAnimator(viewOnceMessage),
MediaReviewAnimatorController.getFadeInAnimator(addMessageEntry),
MediaReviewAnimatorController.getFadeOutAnimator(addMessageButton)
)
}
}
}
private fun computeViewOnceButtonAnimators(state: MediaSelectionState): List<Animator> {
return if (state.isTouchEnabled && state.selectedMedia.size == 1 && !state.isStory) {
listOf(MediaReviewAnimatorController.getFadeInAnimator(viewOnceButton))
} else {
listOf(MediaReviewAnimatorController.getFadeOutAnimator(viewOnceButton))
}
}
private fun computeAddMediaButtonsAnimators(state: MediaSelectionState): List<Animator> {
return when {
!state.isTouchEnabled || state.viewOnceToggleState == MediaSelectionState.ViewOnceToggleState.ONCE -> {
listOf(
MediaReviewAnimatorController.getFadeOutAnimator(addMediaButton),
MediaReviewAnimatorController.getFadeOutAnimator(selectionRecycler)
)
}
state.selectedMedia.size > 1 -> {
listOf(
MediaReviewAnimatorController.getFadeOutAnimator(addMediaButton),
MediaReviewAnimatorController.getFadeInAnimator(selectionRecycler)
)
}
else -> {
listOf(
MediaReviewAnimatorController.getFadeInAnimator(addMediaButton),
MediaReviewAnimatorController.getFadeOutAnimator(selectionRecycler)
)
}
}
}
private fun computeSendButtonAnimators(state: MediaSelectionState): List<Animator> {
val slideIn = listOf(
MediaReviewAnimatorController.getSlideInAnimator(sendButton),
)
return slideIn + if (state.isTouchEnabled) {
listOf(
MediaReviewAnimatorController.getFadeInAnimator(sendButton, state.canSend),
)
} else {
listOf(
MediaReviewAnimatorController.getFadeOutAnimator(sendButton, state.canSend),
)
}
}
private fun computeSaveButtonAnimators(state: MediaSelectionState): List<Animator> {
val slideIn = listOf(
MediaReviewAnimatorController.getSlideInAnimator(saveButton)
)
return slideIn + if (state.isTouchEnabled && !MediaUtil.isVideo(state.focusedMedia?.mimeType)) {
listOf(
MediaReviewAnimatorController.getFadeInAnimator(saveButton)
)
} else {
listOf(
MediaReviewAnimatorController.getFadeOutAnimator(saveButton)
)
}
}
private fun computeQualityButtonAnimators(state: MediaSelectionState): List<Animator> {
val slide = listOf(MediaReviewAnimatorController.getSlideInAnimator(qualityButton))
return slide + if (state.isTouchEnabled && state.selectedMedia.any { MediaUtil.isImageType(it.mimeType) }) {
listOf(MediaReviewAnimatorController.getFadeInAnimator(qualityButton))
} else {
listOf(MediaReviewAnimatorController.getFadeOutAnimator(qualityButton))
}
}
private fun computeCropAndRotateButtonAnimators(state: MediaSelectionState): List<Animator> {
val slide = listOf(MediaReviewAnimatorController.getSlideInAnimator(cropAndRotateButton))
return slide + if (state.isTouchEnabled && MediaUtil.isImageAndNotGif(state.focusedMedia?.mimeType ?: "")) {
listOf(MediaReviewAnimatorController.getFadeInAnimator(cropAndRotateButton))
} else {
listOf(MediaReviewAnimatorController.getFadeOutAnimator(cropAndRotateButton))
}
}
private fun computeDrawToolButtonAnimators(state: MediaSelectionState): List<Animator> {
val slide = listOf(MediaReviewAnimatorController.getSlideInAnimator(drawToolButton))
return slide + if (state.isTouchEnabled && MediaUtil.isImageAndNotGif(state.focusedMedia?.mimeType ?: "")) {
listOf(MediaReviewAnimatorController.getFadeInAnimator(drawToolButton))
} else {
listOf(MediaReviewAnimatorController.getFadeOutAnimator(drawToolButton))
}
}
private fun computeRecipientDisplayAnimators(state: MediaSelectionState): List<Animator> {
return if (state.isTouchEnabled && state.recipient != null) {
recipientDisplay.text = if (state.recipient.isSelf) requireContext().getString(R.string.note_to_self) else state.recipient.getDisplayName(requireContext())
listOf(MediaReviewAnimatorController.getFadeInAnimator(recipientDisplay))
} else {
listOf(MediaReviewAnimatorController.getFadeOutAnimator(recipientDisplay))
}
}
interface Callback {
fun onSentWithResult(mediaSendActivityResult: MediaSendActivityResult)
fun onSentWithoutResult()
fun onSendError(error: Throwable)
fun onNoMediaSelected()
fun onPopFromReview()
}
}
|
gpl-3.0
|
18f5f2bcaafbbfee12c319c1834882a6
| 37.279352 | 173 | 0.76166 | 4.777665 | false | false | false | false |
daviddenton/k2
|
src/main/kotlin/io/github/daviddenton/k2/contract/Body.kt
|
1
|
1807
|
package io.github.daviddenton.k2.contract
import io.github.daviddenton.k2.Extracted
import io.github.daviddenton.k2.Extraction
import io.github.daviddenton.k2.Extractor
import io.github.daviddenton.k2.Retrieval
import io.github.daviddenton.k2.contract.ParamType.StringParamType
import io.github.daviddenton.k2.http.Message
import io.github.daviddenton.k2.util.then
interface NamedWithExample : Named {
val example: String?
}
class ExtractableBody<in From, out Final>(private val exFn: (From) -> Extraction<Final>)
: Retrieval<From, Final>, Extractor<From, Final>, Iterable<NamedWithExample> {
override fun iterator(): Iterator<NamedWithExample> {
TODO("not implemented")
}
override fun from(from: From): Final = extract(from).orThrow { BrokenContract(it.errors) }
override fun extract(from: From): Extraction<Final> = exFn(from)
}
class Body<From : Message, T>(private val contentType: ContentType,
private val type: ParamType,
val deserialize: (String) -> Extraction<T>,
private val serialize: (T) -> String) {
fun <O> map(toNext: (T) -> O, fromNext: (O) -> T): Body<From, O> =
Body(contentType, type, { deserialize(it).map { toNext(it) } }, fromNext.then(serialize))
fun <O> flatMap(toNext: (T) -> Extraction<O>, fromNext: (O) -> T): Body<From, O> =
Body(contentType, type, { deserialize(it).flatMap { toNext(it) } }, fromNext.then(serialize))
companion object {
fun <From : Message, T> of(body: Body<From, T>): ExtractableBody<From, T> =
ExtractableBody({ body.deserialize(it.body) })
fun string(contentType: ContentType): Body<Message, String> = Body(contentType, StringParamType, { Extracted(it) }, { it })
}
}
|
apache-2.0
|
7304590764f5ead02221f1dfa453cc95
| 42.047619 | 131 | 0.665744 | 3.550098 | false | false | false | false |
cfieber/orca
|
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/PauseTaskHandlerTest.kt
|
1
|
2547
|
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.PAUSED
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.PauseStage
import com.netflix.spinnaker.orca.q.PauseTask
import com.netflix.spinnaker.orca.q.buildTasks
import com.netflix.spinnaker.orca.q.multiTaskStage
import com.netflix.spinnaker.q.Queue
import com.nhaarman.mockito_kotlin.*
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
object PauseTaskHandlerTest : SubjectSpek<PauseTaskHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
subject(GROUP) {
PauseTaskHandler(queue, repository)
}
fun resetMocks() = reset(queue, repository)
describe("when a task is paused") {
val pipeline = pipeline {
application = "foo"
stage {
type = multiTaskStage.type
multiTaskStage.buildTasks(this)
}
}
val message = PauseTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1")
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the task state in the stage") {
verify(repository).storeStage(check {
it.tasks.first().apply {
assertThat(status).isEqualTo(PAUSED)
assertThat(endTime).isNull()
}
})
}
it("pauses the stage") {
verify(queue).push(PauseStage(message))
}
}
})
|
apache-2.0
|
8d7fe95ea36f84e24dbcd596e46a4550
| 30.8375 | 95 | 0.733019 | 4.088283 | false | false | false | false |
cfieber/orca
|
orca-kayenta/src/main/kotlin/com/netflix/spinnaker/orca/kayenta/pipeline/KayentaCanaryStage.kt
|
1
|
6698
|
/*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.kayenta.pipeline
import com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
import com.fasterxml.jackson.module.kotlin.convertValue
import com.netflix.spinnaker.orca.ext.mapTo
import com.netflix.spinnaker.orca.ext.withTask
import com.netflix.spinnaker.orca.jackson.OrcaObjectMapper
import com.netflix.spinnaker.orca.kayenta.CanaryScope
import com.netflix.spinnaker.orca.kayenta.CanaryScopes
import com.netflix.spinnaker.orca.kayenta.model.KayentaCanaryContext
import com.netflix.spinnaker.orca.kayenta.model.RunCanaryContext
import com.netflix.spinnaker.orca.kayenta.tasks.AggregateCanaryResultsTask
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilder
import com.netflix.spinnaker.orca.pipeline.TaskNode
import com.netflix.spinnaker.orca.pipeline.WaitStage
import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilder
import com.netflix.spinnaker.orca.pipeline.model.Stage
import org.springframework.stereotype.Component
import java.time.Clock
import java.time.Duration
import java.time.Duration.ZERO
import java.time.Instant
import java.time.Instant.now
import java.time.temporal.ChronoUnit
import java.time.temporal.ChronoUnit.*
import java.util.*
import java.util.concurrent.TimeUnit
@Component
class KayentaCanaryStage(private val clock: Clock) : StageDefinitionBuilder {
private val mapper = OrcaObjectMapper
.newInstance()
.disable(WRITE_DATES_AS_TIMESTAMPS) // we want Instant serialized as ISO string
override fun taskGraph(stage: Stage, builder: TaskNode.Builder) {
builder.withTask<AggregateCanaryResultsTask>("aggregateCanaryResults")
}
override fun beforeStages(parent: Stage, graph: StageGraphBuilder) {
if (parent.context["deployments"] != null) {
graph.add {
it.type = DeployCanaryClustersStage.STAGE_TYPE
it.name = "Deploy Canary Clusters"
}
}
val canaryConfig = parent.mapTo<KayentaCanaryContext>("/canaryConfig")
if (canaryConfig.scopes.isEmpty()) {
throw IllegalArgumentException("Canary stage configuration must contain at least one scope.")
}
val lifetime: Duration = if (canaryConfig.endTime != null) {
Duration.ofMinutes((canaryConfig.startTime ?: now(clock))
.until(canaryConfig.endTime, MINUTES))
} else if (canaryConfig.lifetime != null) {
canaryConfig.lifetime
} else {
throw IllegalArgumentException("Canary stage configuration must include either `endTime` or `lifetimeDuration`.")
}
var canaryAnalysisInterval = canaryConfig.canaryAnalysisInterval ?: lifetime
if (canaryAnalysisInterval == ZERO || canaryAnalysisInterval > lifetime) {
canaryAnalysisInterval = lifetime
}
val numIntervals = (lifetime.toMinutes() / canaryAnalysisInterval.toMinutes()).toInt()
if (canaryConfig.beginCanaryAnalysisAfter > ZERO) {
graph.append {
it.type = WaitStage.STAGE_TYPE
it.name = "Warmup Wait"
it.context["waitTime"] = canaryConfig.beginCanaryAnalysisAfter.seconds
}
}
for (i in 1..numIntervals) {
// If an end time was explicitly specified, we don't need to synchronize
// the execution of the canary pipeline with the real time.
if (canaryConfig.endTime == null) {
graph.append {
it.type = WaitStage.STAGE_TYPE
it.name = "Interval Wait #$i"
it.context["waitTime"] = canaryAnalysisInterval.seconds
}
}
val runCanaryContext = RunCanaryContext(
canaryConfig.metricsAccountName,
canaryConfig.storageAccountName,
canaryConfig.canaryConfigId,
buildRequestScopes(canaryConfig, i, canaryAnalysisInterval),
canaryConfig.scoreThresholds
)
graph.append {
it.type = RunCanaryPipelineStage.STAGE_TYPE
it.name = "Run Canary #$i"
it.context.putAll(mapper.convertValue<Map<String, Any>>(runCanaryContext))
it.context["continuePipeline"] = parent.context["continuePipeline"]
}
}
}
override fun afterStages(parent: Stage, graph: StageGraphBuilder) {
if (parent.context["deployments"] != null) {
graph.add {
it.type = CleanupCanaryClustersStage.STAGE_TYPE
it.name = "Cleanup Canary Clusters"
}
}
}
override fun onFailureStages(stage: Stage, graph: StageGraphBuilder) {
afterStages(stage, graph)
}
private fun buildRequestScopes(
config: KayentaCanaryContext,
interval: Int,
intervalDuration: Duration
): Map<String, CanaryScopes> {
val requestScopes = HashMap<String, CanaryScopes>()
config.scopes.forEach { scope ->
var start: Instant
val end: Instant
val warmup = config.beginCanaryAnalysisAfter
val offset = intervalDuration.multipliedBy(interval.toLong())
if (config.endTime == null) {
start = (config.startTime ?: now(clock)).plus(warmup)
end = (config.startTime ?: now(clock)).plus(warmup + offset)
} else {
start = (config.startTime ?: now(clock))
end = (config.startTime ?: now(clock)).plus(offset)
}
if (config.lookback > ZERO) {
start = end.minus(config.lookback)
}
val controlScope = CanaryScope(
scope.controlScope,
scope.controlLocation,
start,
end,
config.step.seconds,
scope.extendedScopeParams
)
val experimentScope = controlScope.copy(
scope = scope.experimentScope,
location = scope.experimentLocation
)
requestScopes[scope.scopeName] = CanaryScopes(
controlScope = controlScope,
experimentScope = experimentScope
)
}
return requestScopes
}
override fun getType() = STAGE_TYPE
companion object {
@JvmStatic
val STAGE_TYPE = "kayentaCanary"
}
}
private val KayentaCanaryContext.endTime: Instant?
get() = scopes.first().endTime
private val KayentaCanaryContext.startTime: Instant?
get() = scopes.first().startTime
private val KayentaCanaryContext.step: Duration
get() = Duration.ofSeconds(scopes.first().step)
|
apache-2.0
|
bbdfb43b26c985cefb65a114ff339bab
| 33.173469 | 119 | 0.713198 | 4.32408 | false | true | false | false |
jovr/imgui
|
core/src/main/kotlin/imgui/static/forwardDeclarations.kt
|
2
|
9774
|
package imgui.static
import gli_.has
import glm_.L
import glm_.f
import glm_.i
import imgui.*
import imgui.ImGui.createNewWindowSettings
import imgui.ImGui.findOrCreateWindowSettings
import imgui.ImGui.findWindowByID
import imgui.ImGui.findWindowSettings
import imgui.ImGui.io
import imgui.ImGui.style
import imgui.api.g
import imgui.classes.Context
import imgui.internal.classes.PoolIdx
import imgui.internal.classes.Rect
import imgui.internal.classes.Window
import imgui.internal.sections.SettingsHandler
import imgui.internal.sections.WindowSettings
import imgui.windowsIme.COMPOSITIONFORM
import imgui.windowsIme.DWORD
import imgui.windowsIme.HIMC
import imgui.windowsIme.imm
import org.lwjgl.system.MemoryUtil
import uno.glfw.HWND
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.StringSelection
import imgui.WindowFlag as Wf
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
//-------------------------------------------------------------------------
fun setCurrentWindow(window: Window?) {
g.currentWindow = window
g.currentTable = when {
window != null && window.dc.currentTableIdx != -1 -> g.tables.getByIndex(window.dc.currentTableIdx)
else -> null
}
if (window != null) {
g.fontSize = window.calcFontSize()
g.drawListSharedData.fontSize = g.fontSize
}
}
/** Find window given position, search front-to-back
FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
called, aka before the next Begin(). Moving window isn't affected.. */
fun findHoveredWindow() {
var hoveredWindow = g.movingWindow?.takeIf { it.flags hasnt Wf.NoMouseInputs }
var hoveredWindowIgnoringMovingWindow: Window? = null
val paddingRegular = style.touchExtraPadding // [JVM] careful, no copy
val paddingForResizeFromEdges = when { // [JVM] careful, no copy
io.configWindowsResizeFromEdges -> style.touchExtraPadding max WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS
else -> paddingRegular
}
for (window in g.windows.asReversed()) {
if (!window.active || window.hidden)
continue
if (window.flags has Wf.NoMouseInputs)
continue
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
val bb = Rect(window.outerRectClipped) // [JVM] we need a copy
bb expand when {
window.flags has (Wf._ChildWindow or Wf.NoResize or Wf.AlwaysAutoResize) -> paddingRegular
else -> paddingForResizeFromEdges
}
if (io.mousePos !in bb)
continue
// Support for one rectangular hole in any given window
// FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
if (window.hitTestHoleSize.x != 0) {
val holePos = window.pos + window.hitTestHoleOffset
val holeSize = window.hitTestHoleSize
if (Rect(holePos, holePos + holeSize).contains(io.mousePos))
continue
}
if (hoveredWindow == null)
hoveredWindow = window
val moving = g.movingWindow
if (hoveredWindowIgnoringMovingWindow == null && (moving == null || window.rootWindow != moving.rootWindow))
hoveredWindowIgnoringMovingWindow = window
if (hoveredWindow != null && hoveredWindowIgnoringMovingWindow != null)
break
}
g.hoveredWindow = hoveredWindow
g.hoveredRootWindow = g.hoveredWindow?.rootWindow
g.hoveredWindowUnderMovingWindow = hoveredWindow
}
// ApplyWindowSettings -> Window class
fun createNewWindow(name: String, flags: WindowFlags) = Window(g, name).apply {
//IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
// Create window the first time
this.flags = flags
g.windowsById[id] = this
// Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
pos put 60f
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
if (flags hasnt Wf.NoSavedSettings) {
findWindowSettings(id)?.let { settings ->
// Retrieve settings from .ini file
settingsOffset = g.settingsWindows.indexOf(settings)
setConditionAllowFlags(Cond.FirstUseEver.i, false)
applySettings(settings)
}
}
dc.cursorMaxPos put pos // So first call to CalcContentSize() doesn't return crazy values
dc.cursorStartPos put pos
if (flags has Wf.AlwaysAutoResize) {
autoFitFrames put 2
autoFitOnlyGrows = false
} else {
if (this.size.x <= 0f) autoFitFrames.x = 2
if (this.size.y <= 0f) autoFitFrames.y = 2
autoFitOnlyGrows = autoFitFrames.x > 0 || autoFitFrames.y > 0
}
g.windowsFocusOrder += this
if (flags has Wf.NoBringToFrontOnFocus)
g.windows.add(0, this) // Quite slow but rare and only once
else g.windows += this
}
// CheckStacksSize, CalcNextScrollFromScrollTargetAndClamp and AddWindowToSortBuffer are Window class methods
// AddDrawListToDrawData is a DrawList class method
/** ~GetViewportRect */
val viewportRect: Rect
get() = Rect(0f, 0f, io.displaySize.x.f, io.displaySize.y.f)
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
fun windowSettingsHandler_ClearAll(ctx: Context, handler: SettingsHandler) {
val g = ctx
g.windows.forEach { it.settingsOffset = -1 }
g.settingsWindows.clear()
}
fun windowSettingsHandler_ReadOpen(ctx: Context, settingsHandler: SettingsHandler, name: String): WindowSettings {
val settings = findOrCreateWindowSettings(name)
val id = settings.id
settings.clear() // Clear existing if recycling previous entry
settings.id = id
settings.wantApply = true
return settings
}
fun windowSettingsHandler_ReadLine(ctx: Context, settingsHandler: SettingsHandler, entry: Any, line: String) {
val settings = entry as WindowSettings
when {
line.startsWith("Pos") -> settings.pos put line.substring(4).split(",")
line.startsWith("Size") -> settings.size put line.substring(5).split(",")
line.startsWith("Collapsed") -> settings.collapsed = line.substring(10).toBoolean()
}
}
/** Apply to existing windows (if any) */
fun windowSettingsHandler_ApplyAll(ctx: Context, handler: SettingsHandler) {
val g = ctx
for (settings in g.settingsWindows)
if (settings.wantApply) {
findWindowByID(settings.id)?.applySettings(settings)
settings.wantApply = false
}
}
fun windowSettingsHandler_WriteAll(ctx: Context, handler: SettingsHandler, buf: StringBuilder) {
// Gather data from windows that were active during this session
// (if a window wasn't opened in this session we preserve its settings)
val g = ctx
for (window in g.windows) {
if (window.flags has Wf.NoSavedSettings)
continue
val settings = when {
window.settingsOffset != -1 -> g.settingsWindows[window.settingsOffset]
else -> findWindowSettings(window.id) ?: createNewWindowSettings(window.name).also {
window.settingsOffset = g.settingsWindows.indexOf(it)
}
}
assert(settings.id == window.id)
settings.pos put window.pos
settings.size put window.sizeFull
settings.collapsed = window.collapsed
}
// Write to text buffer
for (setting in g.settingsWindows)
// all numeric fields to ints to have full c++ compatibility
buf += """
|[${handler.typeName}][${setting.name}]
|Pos=${setting.pos.x.i},${setting.pos.y.i}
|Size=${setting.size.x.i},${setting.size.y.i}
|Collapsed=${setting.collapsed.i}
|""".trimMargin()
}
//-----------------------------------------------------------------------------
// Platform dependent default implementations
//-----------------------------------------------------------------------------
val getClipboardTextFn_DefaultImpl: (userData: Any?) -> String? = {
// Create a Clipboard object using getSystemClipboard() method
val clipboard = Toolkit.getDefaultToolkit().systemClipboard
// Get data stored in the clipboard that is in the form of a string (text)
clipboard.getData(DataFlavor.stringFlavor) as? String
}
val setClipboardTextFn_DefaultImpl: (userData: Any?, text: String) -> Unit = { _, text ->
val clipboard = Toolkit.getDefaultToolkit().systemClipboard
clipboard.setContents(StringSelection(text), null)
}
var imeSetInputScreenPosFn_Win32 = { x: Int, y: Int ->
// Notify OS Input Method Editor of text input position
val hwnd: HWND = io.imeWindowHandle
if (hwnd.L != MemoryUtil.NULL) {
val himc: HIMC = HIMC(imm.getContext(hwnd))
if (himc.L != MemoryUtil.NULL) {
val cf = COMPOSITIONFORM().apply {
ptCurrentPos.x = x.L
ptCurrentPos.y = y.L
dwStyle = DWORD(imm.CFS_FORCE_POSITION.L)
}
if (imm.setCompositionWindow(himc, cf) == 0)
System.err.println("imm.setCompositionWindow failed")
if (imm.releaseContext(hwnd, himc) == 0)
System.err.println("imm.releaseContext failed")
cf.free()
}
}
}
|
mit
|
f6166fc469284e6312293a6f4156681c
| 37.333333 | 144 | 0.647637 | 4.351736 | false | false | false | false |
nlgcoin/guldencoin-official
|
src/frontend/android/unity_wallet/app/src/main/java/com/gulden/barcodereader/CameraSourcePreview.kt
|
2
|
4517
|
/*
* Copyright (C) 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.
*
* This file contains modifications by The Gulden developers
* All modifications copyright (C) The Gulden developers
*/
package com.gulden.barcodereader
import android.Manifest
import android.content.Context
import android.content.res.Configuration
import android.graphics.SurfaceTexture
import android.util.AttributeSet
import android.util.Log
import android.view.TextureView
import androidx.annotation.RequiresPermission
import java.io.IOException
class CameraSourcePreview(private val mContext: Context, attrs: AttributeSet) : TextureView(mContext, attrs), TextureView.SurfaceTextureListener
{
private var textureHeight : Int = 0
private var textureWidth : Int = 0
var previewHeight : Int = 0
var previewWidth : Int = 0
private var mStartRequested: Boolean = false
private var mSurfaceAvailable: Boolean = false
private var mCameraSource: CameraSource? = null
private val isPortraitMode: Boolean
get()
{
val orientation = mContext.resources.configuration.orientation
if (orientation == Configuration.ORIENTATION_LANDSCAPE)
{
return false
}
if (orientation == Configuration.ORIENTATION_PORTRAIT)
{
return true
}
Log.d(TAG, "isPortraitMode returning false by default")
return false
}
init
{
mStartRequested = false
mSurfaceAvailable = false
surfaceTextureListener = this
}
/*Texture view listener overrides begin*/
override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int)
{
mSurfaceAvailable = true
textureHeight = height
textureWidth = width
try
{
startIfReady()
}
catch (e: IOException)
{
Log.e(TAG, "Could not start camera source.", e)
}
}
override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int)
{
textureHeight = height
textureWidth = width
}
override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean
{
mSurfaceAvailable = false
return true
}
override fun onSurfaceTextureUpdated(texture: SurfaceTexture)
{
}
/*Texture view listener overrides end*/
@RequiresPermission(Manifest.permission.CAMERA)
@Throws(IOException::class, SecurityException::class)
fun start(cameraSource: CameraSource?)
{
if (cameraSource == null)
{
stop()
}
mCameraSource = cameraSource
if (mCameraSource != null)
{
mStartRequested = true
startIfReady()
}
}
fun stop()
{
if (mCameraSource != null)
{
mCameraSource?.stop()
}
}
fun release()
{
if (mCameraSource != null)
{
mCameraSource?.release()
mCameraSource = null
}
}
@RequiresPermission(Manifest.permission.CAMERA)
@Throws(IOException::class, SecurityException::class)
private fun startIfReady()
{
if (mStartRequested && mSurfaceAvailable)
{
mCameraSource?.start(this)
mStartRequested = false
}
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int)
{
previewHeight = bottom - top
previewWidth = right - left
try
{
startIfReady()
}
catch (se: SecurityException)
{
Log.e(TAG, "Do not have permission to start the camera", se)
}
catch (e: IOException)
{
Log.e(TAG, "Could not start camera source.", e)
}
}
companion object
{
private const val TAG = "CameraSourcePreview"
}
}
|
mit
|
460556ac0962aee34707d8f196fb4693
| 25.261628 | 144 | 0.623865 | 4.915125 | false | false | false | false |
dhis2/dhis2-android-sdk
|
core/src/main/java/org/hisp/dhis/android/core/domain/aggregated/data/internal/AggregatedD2ProgressManager.kt
|
1
|
3705
|
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.domain.aggregated.data.internal
import org.hisp.dhis.android.core.arch.call.D2ProgressStatus
import org.hisp.dhis.android.core.arch.call.D2ProgressSyncStatus
import org.hisp.dhis.android.core.arch.call.internal.D2ProgressManager
import org.hisp.dhis.android.core.domain.aggregated.data.AggregatedD2Progress
internal class AggregatedD2ProgressManager(totalCalls: Int?) : D2ProgressManager(totalCalls) {
private var progress: AggregatedD2Progress
override fun getProgress(): AggregatedD2Progress {
return progress
}
override fun <T> increaseProgress(resourceClass: Class<T>, isComplete: Boolean): AggregatedD2Progress {
return progress.toBuilder()
.doneCalls(progress.doneCalls() + resourceClass.simpleName)
.isComplete(isComplete)
.build()
.also {
progress = it
}
}
fun setTotalCalls(totalCalls: Int): AggregatedD2Progress {
return progress.toBuilder()
.totalCalls(totalCalls)
.build()
.also { progress = it }
}
fun setDataSets(dataSets: Collection<String>): AggregatedD2Progress {
return progress.toBuilder()
.dataSets(dataSets.associateWith { D2ProgressStatus() })
.build()
.also { progress = it }
}
fun completeDataSet(dataSet: String, syncStatus: D2ProgressSyncStatus): AggregatedD2Progress {
val newDataSetStatus = (progress.dataSets()[dataSet] ?: D2ProgressStatus())
.copy(isComplete = true, syncStatus = syncStatus)
return progress.toBuilder()
.dataSets(progress.dataSets() + (dataSet to newDataSetStatus))
.build()
.also { progress = it }
}
fun complete(): AggregatedD2Progress {
return progress.toBuilder()
.dataSets(progress.dataSets().mapValues { it.value.copy(isComplete = true) })
.isComplete(true)
.build()
.also { progress = it }
}
init {
this.progress = AggregatedD2Progress.empty(totalCalls)
}
}
|
bsd-3-clause
|
8b9f62da27de8b0f7cf6d7c2822ea9bc
| 41.102273 | 107 | 0.700675 | 4.52381 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenCompilerImporter.kt
|
2
|
12980
|
// 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.jetbrains.idea.maven.importing
import com.intellij.compiler.CompilerConfiguration
import com.intellij.compiler.CompilerConfigurationImpl
import com.intellij.openapi.compiler.options.ExcludeEntryDescription
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.pom.java.LanguageLevel
import com.intellij.util.containers.ContainerUtil.addIfNotNull
import com.intellij.util.text.nullize
import org.jdom.Element
import org.jetbrains.idea.maven.MavenDisposable
import org.jetbrains.idea.maven.project.*
import org.jetbrains.idea.maven.server.MavenEmbedderWrapper
import org.jetbrains.idea.maven.server.NativeMavenProjectHolder
import org.jetbrains.idea.maven.utils.MavenLog
import org.jetbrains.idea.maven.utils.MavenProcessCanceledException
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions
/**
* @author Vladislav.Soroka
*/
class MavenCompilerImporter : MavenImporter("org.apache.maven.plugins", "maven-compiler-plugin") {
private val LOG = Logger.getInstance(MavenCompilerImporter::class.java)
override fun isApplicable(mavenProject: MavenProject?): Boolean {
return true
}
override fun processChangedModulesOnly(): Boolean {
return false
}
@Throws(MavenProcessCanceledException::class)
override fun resolve(project: Project,
mavenProject: MavenProject,
nativeMavenProject: NativeMavenProjectHolder,
embedder: MavenEmbedderWrapper,
context: ResolveContext) {
if (!super.isApplicable(mavenProject)) return
if (!Registry.`is`("maven.import.compiler.arguments", true)) return
val compilerExtension = MavenCompilerExtension.EP_NAME.extensions.find {
it.resolveDefaultCompiler(project, mavenProject, nativeMavenProject, embedder, context)
}
val autoDetectCompiler = MavenProjectsManager.getInstance(project).importingSettings.isAutoDetectCompiler
MavenLog.LOG.debug("maven compiler autodetect = ", autoDetectCompiler)
val backendCompiler = compilerExtension?.getCompiler(project) ?: return
val ideCompilerConfiguration = CompilerConfiguration.getInstance(project) as CompilerConfigurationImpl
if (ideCompilerConfiguration.defaultCompiler != backendCompiler && autoDetectCompiler) {
if (ideCompilerConfiguration.registeredJavaCompilers.contains(backendCompiler)) {
ideCompilerConfiguration.defaultCompiler = backendCompiler
project.putUserData(DEFAULT_COMPILER_IS_RESOLVED, true)
}
else {
LOG.error(backendCompiler.toString() + " is not registered.")
}
}
else {
project.putUserData(DEFAULT_COMPILER_IS_RESOLVED, true)
}
}
override fun preProcess(module: Module,
mavenProject: MavenProject,
changes: MavenProjectChanges,
modifiableModelsProvider: IdeModifiableModelsProvider) {
if (!super.isApplicable(mavenProject)) return
if (!Registry.`is`("maven.import.compiler.arguments", true)) return
val config = getConfig(mavenProject) ?: return
var compilers = modifiableModelsProvider.getUserData(COMPILERS)
if (compilers == null) {
compilers = mutableSetOf()
modifiableModelsProvider.putUserData(COMPILERS, compilers)
}
compilers.add(getCompilerId(config))
}
override fun process(modifiableModelsProvider: IdeModifiableModelsProvider,
module: Module,
rootModel: MavenRootModelAdapter?,
mavenModel: MavenProjectsTree,
mavenProject: MavenProject,
changes: MavenProjectChanges,
mavenProjectToModuleName: Map<MavenProject, String>,
postTasks: List<MavenProjectsProcessorTask>) {
val project = module.project
val compilers = modifiableModelsProvider.getUserData(COMPILERS)
val defaultCompilerId = if (compilers != null && compilers.size == 1) compilers.first() else JAVAC_ID
val mavenConfiguration: Lazy<MavenCompilerConfiguration> = lazy {
MavenCompilerConfiguration(mavenProject.properties[MAVEN_COMPILER_PARAMETERS]?.toString(), getConfig(mavenProject))
}
val compilerId = if (mavenProject.packaging != "pom") mavenConfiguration.value.pluginConfiguration?.let { getCompilerId(it) } else null
val ideCompilerConfiguration = CompilerConfiguration.getInstance(project) as CompilerConfigurationImpl
for (compilerExtension in MavenCompilerExtension.EP_NAME.extensions) {
if (!mavenConfiguration.value.isEmpty() && compilerId == compilerExtension.mavenCompilerId) {
importCompilerConfiguration(module, mavenConfiguration.value, compilerExtension, mavenProject)
}
else {
// cleanup obsolete options
(compilerExtension.getCompiler(project)?.options as? JpsJavaCompilerOptions)?.let {
ideCompilerConfiguration.setAdditionalOptions(it, module, emptyList())
}
}
if (project.getUserData(DEFAULT_COMPILER_IS_RESOLVED) != true &&
modifiableModelsProvider.getUserData(DEFAULT_COMPILER_IS_SET) == null &&
defaultCompilerId == compilerExtension.mavenCompilerId) {
val backendCompiler = compilerExtension.getCompiler(project)
val autoDetectCompiler = MavenProjectsManager.getInstance(project).importingSettings.isAutoDetectCompiler
MavenLog.LOG.debug("maven compiler autodetect = ", autoDetectCompiler)
if (backendCompiler != null && ideCompilerConfiguration.defaultCompiler != backendCompiler && autoDetectCompiler) {
if (ideCompilerConfiguration.registeredJavaCompilers.contains(backendCompiler)) {
ideCompilerConfiguration.defaultCompiler = backendCompiler
}
else {
LOG.error(backendCompiler.toString() + " is not registered.")
}
}
if (compilerId == null && !mavenConfiguration.value.isEmpty()) {
importCompilerConfiguration(module, mavenConfiguration.value, compilerExtension, mavenProject)
}
modifiableModelsProvider.putUserData(DEFAULT_COMPILER_IS_SET, true)
}
}
}
override fun postProcess(module: Module,
mavenProject: MavenProject,
changes: MavenProjectChanges,
modifiableModelsProvider: IdeModifiableModelsProvider) {
module.project.putUserData(DEFAULT_COMPILER_IS_RESOLVED, null)
configureCompilers(mavenProject, module)
}
private fun configureCompilers(mavenProject: MavenProject, module: Module) {
val project = module.project
val configuration = CompilerConfiguration.getInstance(project)
if (java.lang.Boolean.TRUE != module.getUserData(IGNORE_MAVEN_COMPILER_TARGET_KEY)) {
var level: LanguageLevel?
if (MavenModelUtil.isTestModule(module.name)) {
level = MavenModelUtil.getTargetTestLanguageLevel(mavenProject)
if (level == null) {
level = MavenModelUtil.getTargetLanguageLevel(mavenProject)
}
}
else {
level = MavenModelUtil.getTargetLanguageLevel(mavenProject)
}
if (level == null) {
level = MavenModelUtil.getDefaultLevel(mavenProject)
}
// default source and target settings of maven-compiler-plugin is 1.5, see details at http://maven.apache.org/plugins/maven-compiler-plugin!
configuration.setBytecodeTargetLevel(module, level.toJavaVersion().toString())
}
module.putUserData(IGNORE_MAVEN_COMPILER_TARGET_KEY, java.lang.Boolean.FALSE)
// Exclude src/main/archetype-resources
// Exclude src/main/archetype-resources
val dir = VfsUtil.findRelativeFile(mavenProject.directoryFile, "src", "main", "resources", "archetype-resources")
if (dir != null && !configuration.isExcludedFromCompilation(dir)) {
val cfg = configuration.excludedEntriesConfiguration
cfg.addExcludeEntryDescription(ExcludeEntryDescription(dir, true, false, MavenDisposable.getInstance(project)))
}
}
private fun importCompilerConfiguration(module: Module,
mavenCompilerConfiguration: MavenCompilerConfiguration,
extension: MavenCompilerExtension,
mavenProject: MavenProject) {
val compilerOptions = extension.getCompiler(module.project)?.options
val compilerArgs = collectCompilerArgs(mavenCompilerConfiguration)
extension.configureOptions(compilerOptions, module, mavenProject, compilerArgs)
}
companion object {
private val COMPILERS = Key.create<MutableSet<String>>("maven.compilers")
private val DEFAULT_COMPILER_IS_RESOLVED = Key.create<Boolean>("default.compiler.resolved")
private val DEFAULT_COMPILER_IS_SET = Key.create<Boolean>("default.compiler.updated")
private const val JAVAC_ID = "javac"
private const val MAVEN_COMPILER_PARAMETERS = "maven.compiler.parameters"
@JvmField
val IGNORE_MAVEN_COMPILER_TARGET_KEY = Key.create<Boolean>("idea.maven.skip.compiler.target.level")
private fun getCompilerId(config: Element): String {
val compilerId = config.getChildTextTrim("compilerId")
if (compilerId.isNullOrBlank() || JAVAC_ID == compilerId || hasUnresolvedProperty(compilerId)) return JAVAC_ID
else return compilerId
}
private const val propStartTag = "\${"
private const val propEndTag = "}"
private fun hasUnresolvedProperty(txt: String): Boolean {
val i = txt.indexOf(propStartTag)
return i >= 0 && findClosingBraceOrNextUnresolvedProperty(i + 1, txt) != -1
}
private fun findClosingBraceOrNextUnresolvedProperty(index: Int, s: String): Int {
if (index == -1) return -1
val pair = s.findAnyOf(listOf(propEndTag, propStartTag), index) ?: return -1
if (pair.second == propEndTag) return pair.first
val nextIndex = if (pair.second == propStartTag) pair.first + 2 else pair.first + 1
return findClosingBraceOrNextUnresolvedProperty(nextIndex, s)
}
private fun getResolvedText(txt: String?): String? {
val result = txt.nullize() ?: return null
if (hasUnresolvedProperty(result)) return null
return result
}
private fun getResolvedText(it: Element): String? {
return getResolvedText(it.textTrim)
}
private fun collectCompilerArgs(mavenCompilerConfiguration: MavenCompilerConfiguration): List<String> {
val options = mutableListOf<String>()
val pluginConfiguration = mavenCompilerConfiguration.pluginConfiguration
val parameters = pluginConfiguration?.getChild("parameters")
if (parameters?.textTrim?.toBoolean() == true) {
options += "-parameters"
}
else if (parameters == null && mavenCompilerConfiguration.propertyCompilerParameters?.toBoolean() == true) {
options += "-parameters"
}
if (pluginConfiguration == null) return options
val compilerArguments = pluginConfiguration.getChild("compilerArguments")
if (compilerArguments != null) {
val unresolvedArgs = mutableSetOf<String>()
val effectiveArguments = compilerArguments.children.map {
val key = it.name.run { if (startsWith("-")) this else "-$this" }
val value = getResolvedText(it)
if (value == null && hasUnresolvedProperty(it.textTrim)) {
unresolvedArgs += key
}
key to value
}.toMap()
effectiveArguments.forEach { key, value ->
if (key.startsWith("-A") && value != null) {
options.add("$key=$value")
}
else if (key !in unresolvedArgs) {
options.add(key)
addIfNotNull(options, value)
}
}
}
addIfNotNull(options, getResolvedText(pluginConfiguration.getChildTextTrim("compilerArgument")))
val compilerArgs = pluginConfiguration.getChild("compilerArgs")
if (compilerArgs != null) {
for (arg in compilerArgs.getChildren("arg")) {
addIfNotNull(options, getResolvedText(arg))
}
for (compilerArg in compilerArgs.getChildren("compilerArg")) {
addIfNotNull(options, getResolvedText(compilerArg))
}
}
return options
}
}
}
private data class MavenCompilerConfiguration(val propertyCompilerParameters: String?, val pluginConfiguration: Element?) {
fun isEmpty(): Boolean = propertyCompilerParameters == null && pluginConfiguration == null
}
|
apache-2.0
|
03a0bdafba2e4238a4fc03f7a5319cdd
| 43.604811 | 146 | 0.704237 | 5.011583 | false | true | false | false |
JonathanxD/CodeAPI
|
src/main/kotlin/com/github/jonathanxd/kores/base/InstanceOfCheck.kt
|
1
|
3061
|
/*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores.base
import com.github.jonathanxd.kores.Instruction
import com.github.jonathanxd.kores.Types
import com.github.jonathanxd.kores.builder.self
import java.lang.reflect.Type
/**
* Checks if [part] is `instanceof` [checkType].
*
* @property part Casted part
* @property checkType Type to check if part value is instance.
*/
data class InstanceOfCheck(val part: Instruction, val checkType: Type) : Typed,
Instruction {
override val type: Type
get() = Types.BOOLEAN
override fun builder(): Builder = Builder(this)
class Builder() :
Typed.Builder<InstanceOfCheck, Builder> {
lateinit var part: Instruction
lateinit var checkType: Type
constructor(defaults: InstanceOfCheck) : this() {
this.part = defaults.part
this.checkType = defaults.checkType
}
override fun type(value: Type): Builder = self()
/**
* See [InstanceOfCheck.part]
*/
fun part(value: Instruction): Builder {
this.part = value
return this
}
/**
* See [InstanceOfCheck.checkType]
*/
fun checkType(value: Type): Builder {
this.checkType = value
return this
}
override fun build(): InstanceOfCheck = InstanceOfCheck(this.part, this.checkType)
companion object {
@JvmStatic
fun builder(): Builder = Builder()
@JvmStatic
fun builder(defaults: InstanceOfCheck): Builder = Builder(defaults)
}
}
}
|
mit
|
75c34b2deb66eb51a24d7108482289c4
| 33.011111 | 118 | 0.655995 | 4.528107 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/extensionFunction2.kt
|
12
|
1365
|
fun KotlinClass.functionFromKotlin(): Int = 42
class KotlinClass {
fun <caret>a() = this.functionFromKotlin()
}
fun a() {
KotlinClass().a()
val d = KotlinClass()
d.a()
d.let {
it.a()
}
d.also {
it.a()
}
with(d) {
a()
}
with(d) out@{
with(4) {
[email protected]()
}
}
}
fun a2() {
val d: KotlinClass? = null
d?.a()
d?.let {
it.a()
}
d?.also {
it.a()
}
with(d) {
this?.a()
}
with(d) out@{
with(4) {
this@out?.a()
}
}
}
fun a3() {
val d: KotlinClass? = null
val a1 = d?.a()
val a2 = d?.let {
it.a()
}
val a3 = d?.also {
it.a()
}
val a4 = with(d) {
this?.a()
}
val a5 = with(d) out@{
with(4) {
this@out?.a()
}
}
}
fun a4() {
val d: KotlinClass? = null
d?.a()?.dec()
val a2 = d?.let {
it.a()
}
a2?.toLong()
d?.also {
it.a()
}?.a()?.and(4)
val a4 = with(d) {
this?.a()
}
val a5 = with(d) out@{
with(4) {
this@out?.a()
}
}
val a6 = a4?.let { out -> a5?.let { out + it } }
}
fun KotlinClass.b(): Int? = a()
fun KotlinClass.c(): Int = this.a()
fun d(d: KotlinClass) = d.a()
|
apache-2.0
|
cf49089dc712bfafaec0eb15bee55164
| 12 | 52 | 0.376557 | 2.929185 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/KotlinScriptDependenciesClassFinder.kt
|
2
|
6293
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.core.script
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.*
import com.intellij.psi.impl.java.stubs.index.JavaFullClassNameIndex
import com.intellij.psi.search.EverythingGlobalScope
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.Processor
import com.intellij.util.containers.ConcurrentFactoryMap
import org.jetbrains.kotlin.idea.core.script.dependencies.KotlinScriptMarkerFileSystem
import org.jetbrains.kotlin.resolve.jvm.KotlinSafeClassFinder
internal class KotlinScriptDependenciesClassFinder(private val project: Project) : NonClasspathClassFinder(project), KotlinSafeClassFinder {
private val useOnlyForScripts = Registry.`is`("kotlin.resolve.scripting.limit.dependency.element.finder", true)
/*
'PsiElementFinder's are global and can be called for any context.
As 'KotlinScriptDependenciesClassFinder' is meant to provide additional dependencies only for scripts,
we need to know if the caller came from a script resolution context.
We are doing so by checking if the given scope contains a synthetic 'KotlinScriptMarkerFileSystem.rootFile'.
Normally, only global scopes and 'KotlinScriptScope' contains such a file.
*/
private fun isApplicable(scope: GlobalSearchScope): Boolean {
return !useOnlyForScripts || scope.contains(KotlinScriptMarkerFileSystem.rootFile)
}
override fun getClassRoots(scope: GlobalSearchScope?): List<VirtualFile> {
var result = super.getClassRoots(scope)
if (scope is EverythingGlobalScope) {
result = result + KotlinScriptMarkerFileSystem.rootFile
}
return result
}
override fun calcClassRoots(): List<VirtualFile> {
return ScriptConfigurationManager.getInstance(project)
.getAllScriptsDependenciesClassFiles()
.filter { it.isValid }
}
private val everywhereCache = CachedValuesManager.getManager(project).createCachedValue {
CachedValueProvider.Result.create(
ConcurrentFactoryMap.createMap { qualifiedName: String ->
findClassNotCached(qualifiedName, GlobalSearchScope.everythingScope(project))
},
ScriptDependenciesModificationTracker.getInstance(project),
PsiModificationTracker.MODIFICATION_COUNT,
ProjectRootModificationTracker.getInstance(project),
VirtualFileManager.getInstance()
)
}
override fun findClass(qualifiedName: String, scope: GlobalSearchScope): PsiClass? {
return if (isApplicable(scope)) everywhereCache.value[qualifiedName]?.takeIf { isInScope(it, scope) } else null
}
private fun findClassNotCached(qualifiedName: String, scope: GlobalSearchScope): PsiClass? {
val topLevelClass = super.findClass(qualifiedName, scope)
if (topLevelClass != null && isInScope(topLevelClass, scope)) {
return topLevelClass
}
// The following code is needed because NonClasspathClassFinder cannot find inner classes
// JavaFullClassNameIndex cannot be used directly, because it filter only classes in source roots
val classes = StubIndex.getElements(
JavaFullClassNameIndex.getInstance().key,
qualifiedName,
project,
scope.takeUnless { it is EverythingGlobalScope },
PsiClass::class.java
).filter {
it.qualifiedName == qualifiedName
}
return when (classes.size) {
0 -> null
1 -> classes.single()
else -> classes.first() // todo: check when this happens
}?.takeIf { isInScope(it, scope) }
}
private fun isInScope(clazz: PsiClass, scope: GlobalSearchScope): Boolean {
if (scope is EverythingGlobalScope) {
return true
}
val file = clazz.containingFile?.virtualFile ?: return false
val index = ProjectFileIndex.getInstance(myProject)
return !index.isInContent(file) && !index.isInLibrary(file) && scope.contains(file)
}
override fun findClasses(qualifiedName: String, scope: GlobalSearchScope): Array<PsiClass> {
return if (isApplicable(scope)) super.findClasses(qualifiedName, scope) else emptyArray()
}
override fun getSubPackages(psiPackage: PsiPackage, scope: GlobalSearchScope): Array<PsiPackage> {
return if (isApplicable(scope)) super.getSubPackages(psiPackage, scope) else emptyArray()
}
override fun getClasses(psiPackage: PsiPackage, scope: GlobalSearchScope): Array<PsiClass> {
return if (isApplicable(scope)) super.getClasses(psiPackage, scope) else emptyArray()
}
override fun getPackageFiles(psiPackage: PsiPackage, scope: GlobalSearchScope): Array<PsiFile> {
return if (isApplicable(scope)) super.getPackageFiles(psiPackage, scope) else emptyArray()
}
override fun getPackageFilesFilter(psiPackage: PsiPackage, scope: GlobalSearchScope): Condition<PsiFile>? {
return if (isApplicable(scope)) super.getPackageFilesFilter(psiPackage, scope) else null
}
override fun getClassNames(psiPackage: PsiPackage, scope: GlobalSearchScope): Set<String> {
return if (isApplicable(scope)) super.getClassNames(psiPackage, scope) else emptySet()
}
override fun processPackageDirectories(
psiPackage: PsiPackage, scope: GlobalSearchScope,
consumer: Processor<in PsiDirectory>, includeLibrarySources: Boolean
): Boolean {
return if (isApplicable(scope)) super.processPackageDirectories(psiPackage, scope, consumer, includeLibrarySources) else true
}
}
|
apache-2.0
|
53d44002cdf51fe212a344cd97785e5b
| 45.279412 | 140 | 0.730494 | 5.166667 | false | false | false | false |
awsdocs/aws-doc-sdk-examples
|
kotlin/services/kms/src/main/kotlin/com/kotlin/kms/DescribeKey.kt
|
1
|
1752
|
// snippet-sourcedescription:[DescribeKey.kt demonstrates how to obtain information about an AWS Key Management Service (AWS KMS) key.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[AWS Key Management Service]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.kms
// snippet-start:[kms.kotlin_describe_key.import]
import aws.sdk.kotlin.services.kms.KmsClient
import aws.sdk.kotlin.services.kms.model.DescribeKeyRequest
import kotlin.system.exitProcess
// snippet-end:[kms.kotlin_describe_key.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<keyId>
Where:
keyId - A key id value to describe (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val keyId = args[0]
describeSpecifcKey(keyId)
}
// snippet-start:[kms.kotlin_describe_key.main]
suspend fun describeSpecifcKey(keyIdVal: String?) {
val request = DescribeKeyRequest {
keyId = keyIdVal
}
KmsClient { region = "us-west-2" }.use { kmsClient ->
val response = kmsClient.describeKey(request)
println("The key description is ${response.keyMetadata?.description}")
println("The key ARN is ${response.keyMetadata?.arn}")
}
}
// snippet-end:[kms.kotlin_describe_key.main]
|
apache-2.0
|
c5c79420a5d7b88d4467c68854dde3df
| 28.736842 | 135 | 0.675799 | 3.759657 | false | false | false | false |
jaredsburrows/android-gif-example
|
app/src/main/java/com/burrowsapps/gif/search/ui/license/LicenseScreen.kt
|
1
|
6665
|
@file:OptIn(
ExperimentalMaterial3Api::class,
ExperimentalMaterial3Api::class,
)
package com.burrowsapps.gif.search.ui.license
import android.annotation.SuppressLint
import android.content.res.Configuration.UI_MODE_NIGHT_MASK
import android.content.res.Configuration.UI_MODE_NIGHT_NO
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults.enterAlwaysScrollBehavior
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import androidx.webkit.WebSettingsCompat.FORCE_DARK_OFF
import androidx.webkit.WebSettingsCompat.FORCE_DARK_ON
import androidx.webkit.WebSettingsCompat.setAlgorithmicDarkeningAllowed
import androidx.webkit.WebSettingsCompat.setForceDark
import androidx.webkit.WebViewAssetLoader
import androidx.webkit.WebViewFeature.ALGORITHMIC_DARKENING
import androidx.webkit.WebViewFeature.FORCE_DARK
import androidx.webkit.WebViewFeature.isFeatureSupported
import com.burrowsapps.gif.search.R
import com.burrowsapps.gif.search.ui.theme.GifTheme
import com.google.accompanist.web.AccompanistWebViewClient
import com.google.accompanist.web.rememberWebViewState
import timber.log.Timber
import com.google.accompanist.web.WebView as AccompanistWebView
/** Shows the license screen of the app. */
@Preview(
name = "dark",
showBackground = true,
device = Devices.PIXEL,
locale = "en",
showSystemUi = true,
uiMode = UI_MODE_NIGHT_YES,
)
@Preview(
name = "light",
showBackground = true,
device = Devices.PIXEL,
locale = "en",
showSystemUi = true,
uiMode = UI_MODE_NIGHT_NO,
)
@Composable
private fun DefaultPreview() {
GifTheme {
LicenseScreen()
}
}
@Composable
internal fun LicenseScreen(navController: NavHostController = rememberNavController()) {
val scrollBehavior = enterAlwaysScrollBehavior(rememberTopAppBarState())
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = { TheToolbar(navController, scrollBehavior) }
) { paddingValues ->
TheContent(paddingValues)
}
}
@Composable
private fun TheToolbar(
navController: NavHostController,
scrollBehavior: TopAppBarScrollBehavior,
) {
TopAppBar(
title = {
Text(
text = stringResource(R.string.license_screen_title),
)
},
navigationIcon = {
if (navController.previousBackStackEntry != null) {
IconButton(
onClick = {
navController.navigateUp()
},
) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = stringResource(R.string.menu_back),
)
}
}
},
scrollBehavior = scrollBehavior
)
}
@Composable
private fun TheContent(innerPadding: PaddingValues) {
Column(
modifier = Modifier
.padding(innerPadding)
.verticalScroll(rememberScrollState()),
) {
// TODO Nested WebView prevent anchor clicks
TheWebView()
}
}
@Composable
private fun TheWebView() {
val context = LocalContext.current
val runningInPreview = LocalInspectionMode.current
// https://developer.android.com/reference/androidx/webkit/WebViewAssetLoader
val state =
rememberWebViewState("https://appassets.androidplatform.net/assets/open_source_licenses.html")
val pathHandler = WebViewAssetLoader.AssetsPathHandler(context)
// Instead of loading files using "files://" directly
val assetLoader = WebViewAssetLoader.Builder().addPathHandler("/assets/", pathHandler).build()
AccompanistWebView(
state = state,
onCreated = { webView ->
if (runningInPreview) {
// webView.settings breaks the preview
return@AccompanistWebView
}
webView.isVerticalScrollBarEnabled = false
webView.settings.apply {
allowFileAccess = false
allowContentAccess = false
setGeolocationEnabled(false)
@Suppress(names = ["DEPRECATION"])
if (VERSION.SDK_INT < VERSION_CODES.R) {
allowFileAccessFromFileURLs = false
allowUniversalAccessFromFileURLs = false
}
// Handle dark mode for WebView
@Suppress(names = ["DEPRECATION"])
@SuppressLint("NewApi")
if (VERSION.SDK_INT < VERSION_CODES.Q && isFeatureSupported(ALGORITHMIC_DARKENING)) {
setAlgorithmicDarkeningAllowed(this, true)
} else if (isFeatureSupported(FORCE_DARK)) {
when (webView.resources.configuration.uiMode and UI_MODE_NIGHT_MASK) {
UI_MODE_NIGHT_YES -> setForceDark(this, FORCE_DARK_ON)
else -> setForceDark(this, FORCE_DARK_OFF)
}
} else {
Timber.w("Dark mode not set")
}
}
},
client = object : AccompanistWebViewClient() {
override fun shouldInterceptRequest(
view: WebView,
request: WebResourceRequest,
): WebResourceResponse? {
// Override URLs for AssetsPathHandler
return assetLoader.shouldInterceptRequest(request.url) ?: super.shouldInterceptRequest(
view, request
)
}
override fun onReceivedHttpError(
view: WebView,
request: WebResourceRequest,
errorResponse: WebResourceResponse,
) {
Timber.e("onReceivedHttpError:\t${errorResponse.statusCode}\t${errorResponse.reasonPhrase}")
}
},
)
}
|
apache-2.0
|
0e77f58f1dee8684226d2375bce20abb
| 32.159204 | 100 | 0.743286 | 4.455214 | false | false | false | false |
RuneSuite/client
|
plugins/src/main/java/org/runestar/client/plugins/emojis/Emojis.kt
|
1
|
4215
|
package org.runestar.client.plugins.emojis
import io.reactivex.rxjava3.core.Observable
import org.runestar.client.api.util.CyclicCache
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.game.Sprite
import org.runestar.client.api.game.appendImageTag
import org.runestar.client.api.game.live.Game
import org.runestar.client.raw.CLIENT
import org.runestar.client.raw.access.XAbstractFont
import org.runestar.client.api.plugins.PluginSettings
import javax.imageio.ImageIO
class Emojis : DisposablePlugin<PluginSettings>() {
private companion object {
const val SPRITE_SHEET_NAME = "emojis.png"
const val NAMES_CSV_NAME = "names.csv"
const val SPRITE_SIZE = 16
}
override val defaultSettings = PluginSettings()
private val shortCodes = HashMap<String, Int>()
private val cache = CyclicCache<String, String>()
private var spritesStartIndex = -1
override fun onStart() {
addNames()
if (spritesStartIndex == -1) expandModIcons()
addSprites()
val drawings = Observable.mergeArray(
XAbstractFont.lineWidth.enter,
XAbstractFont.draw.enter,
XAbstractFont.drawAlpha.enter,
XAbstractFont.drawCentered.enter,
XAbstractFont.drawRightAligned.enter,
XAbstractFont.drawLines.enter,
XAbstractFont.drawCenteredShake.enter,
XAbstractFont.drawCenteredWave.enter,
XAbstractFont.drawCenteredWave2.enter,
XAbstractFont.drawRandomAlphaAndSpacing.enter
)
add(drawings.subscribe { it.arguments[0] = cache.get(it.arguments[0] as String) { replaceEmojis(it) } })
add(Game.ticks.subscribe { cache.cycle() })
}
override fun onStop() {
CLIENT.abstractFont_modIconSprites.fill(
null,
spritesStartIndex,
spritesStartIndex + shortCodes.size
)
shortCodes.clear()
cache.clear()
}
private fun addNames() {
val csv = javaClass.getResource(NAMES_CSV_NAME).openStream().use { it.reader().readText() }
csv.split(',').withIndex().associateTo(shortCodes) { it.value to it.index }
}
private fun addSprites() {
val sheet = ImageIO.read(javaClass.getResource(SPRITE_SHEET_NAME))
val count = sheet.height / SPRITE_SIZE
for (i in 0 until count) {
val subImage = sheet.getSubimage(
0,
i * SPRITE_SIZE,
SPRITE_SIZE, SPRITE_SIZE
)
val sprite = Sprite.Indexed.copy(subImage).accessor
sprite.height -= 4 // tricks the game into drawing the sprite further down
CLIENT.abstractFont_modIconSprites[i + spritesStartIndex] = sprite
}
}
private fun expandModIcons() {
val originalArray = CLIENT.abstractFont_modIconSprites
spritesStartIndex = originalArray.size
CLIENT.abstractFont_modIconSprites = originalArray.copyOf(originalArray.size + shortCodes.size)
}
private fun replaceEmojis(s: String): String {
if (s.length < 3) return s
var colon1 = s.indexOf(':')
if (colon1 == -1) return s
var colon2 = s.indexOf(':', colon1 + 1)
if (colon2 == -1) return s
val sb = StringBuilder(s.length)
var next = 0
do {
sb.append(s.substring(next, colon1))
var code = ""
var id: Int? = null
if (colon1 + 1 != colon2) {
code = s.substring(colon1 + 1, colon2)
id = shortCodes[code]
}
if (id == null) {
sb.append(':').append(code)
colon1 = colon2
next = colon2
} else {
appendImageTag(spritesStartIndex + id, sb)
next = colon2 + 1
colon1 = s.indexOf(':', next)
if (colon1 == -1) break
}
colon2 = s.indexOf(':', colon1 + 1)
} while (colon2 != -1)
if (next < s.length) sb.append(s.substring(next))
return sb.toString()
}
}
|
mit
|
890b16b9699ffe994dff25021017fdf8
| 35.034188 | 112 | 0.595255 | 4.223447 | false | false | false | false |
JetBrains/intellij-community
|
plugins/full-line/local/src/org/jetbrains/completion/full/line/local/suggest/collector/BaseCompletionsGenerator.kt
|
1
|
6166
|
package org.jetbrains.completion.full.line.local.suggest.collector
import io.kinference.model.ExecutionContext
import org.jetbrains.completion.full.line.local.CompletionModel
import org.jetbrains.completion.full.line.local.LongLastLineException
import org.jetbrains.completion.full.line.local.generation.generation.BaseGenerationConfig
import org.jetbrains.completion.full.line.local.generation.model.ModelWrapper
import org.jetbrains.completion.full.line.local.tokenizer.Tokenizer
import kotlin.math.max
import kotlin.math.min
/**
* Base class for all completions generators that trims and cleans up completions
* got from beam-search or other implementation before passing it to the client.
*/
internal abstract class BaseCompletionsGenerator<GenerationConfig : BaseGenerationConfig>(
internal val model: ModelWrapper, internal val tokenizer: Tokenizer
) : CompletionsGenerator<GenerationConfig> {
protected abstract fun generateWithSearch(
context: String, prefix: String, config: GenerationConfig, execContext: ExecutionContext
): List<CompletionModel.CompletionResult>
override fun generate(
context: String, prefix: String, config: GenerationConfig, execContext: ExecutionContext
): List<CompletionModel.CompletionResult> {
if (context.isBlank()) return emptyList()
val seenCompletions = HashSet<String>()
val completions = generateWithSearch(context, prefix, config, execContext)
val result = ArrayList<CompletionModel.CompletionResult>()
for (completion in completions) {
val trimmedCompletion = trimCompletion(completion)
val oneSpecificChar = trimmedCompletion.text.length == 1 && !completion.text[0].isLetterOrDigit()
val containsInvalidSymbols = !tokenizer.isValidString(trimmedCompletion.text)
if (trimmedCompletion.text.isEmpty() || oneSpecificChar || containsInvalidSymbols) continue
val words = trimmedCompletion.text.trim().split(' ')
val targetLen = words.size
if (targetLen < config.minLen || trimmedCompletion.text in seenCompletions) continue
trimmedCompletion.info.wordLen = targetLen
seenCompletions.add(trimmedCompletion.text)
result.add(trimmedCompletion)
}
return result
}
internal fun makeContextIds(context: String, config: GenerationConfig, startIds: List<Int>?): IntArray {
val contextIds = tokenizer.encode(context)
return preprocessContextIds(contextIds, config, startIds)
}
private fun preprocessContextIds(
contextIds: IntArray, config: GenerationConfig, startIds: List<Int>?
): IntArray {
// TODO: explain magic number
val maxPossibleContextLen = model.maxSeqLen - 6 - config.maxLen
val requestedContextLen =
config.maxContextLen?.takeIf { it in 1..maxPossibleContextLen } ?: maxPossibleContextLen
val finalContextLen = min(requestedContextLen, maxPossibleContextLen)
return cropContextIds(contextIds, finalContextLen, config.minContextLen, startIds)
}
protected open fun trimCompletion(completion: CompletionModel.CompletionResult): CompletionModel.CompletionResult {
return completion
}
companion object {
/**
* Crops `contextIds` to fit in model input
* @param contextIds Full tokenized context.
* @param maxContextLen
* Model input capacity.
* The returned array is guaranteed to be shorter or equal to `maxContextLen`.
* @param minContextLen
* If null, the longest possible context will be returned.
* If not null, consequent calls of this function with `contextIds` having a common prefix will return
* cropped context having the same start offset as frequent as possible, considering `minContextLen`.
* This means, if you call this function with a certain context, then add a few tokens to the context
* and call the function again, cropped context returned from the first call will likely begin at the
* same offset in `contextIds` as the context, returned by the second call
* (in other words, the first cropped context will be a prefix of the second one).
* The returned array is guaranteed to be longer or equal to `minContextLen` when it's possible,
* considering `startIds` (if `startIds` is not specified, always except when `contextIds` itself is shorter).
* @param startIds If not null, crop context only on specified token ids.
* @return subsequence of `contextIds` shorter or equal to `maxContextLen`
*/
internal fun cropContextIds(
contextIds: IntArray, maxContextLen: Int, minContextLen: Int?, startIds: List<Int>?
): IntArray {
val caretPosition = contextIds.size
var contextStartIndex = max(0, caretPosition - maxContextLen)
val startIndices = when {
startIds != null -> {
val startIdsSet = startIds.toSet()
var newStartIndices = contextIds.mapIndexed { index, item ->
if (item in startIdsSet) {
index
}
else {
null
}
}.filterNotNull()
if (minContextLen != null) {
val persistentStartIndices = mutableListOf(0)
for (i in newStartIndices.indices) {
val lastPersistentIndex = persistentStartIndices.last()
val maxCropPos = lastPersistentIndex + maxContextLen - minContextLen + 1
val shortNextContext = i < newStartIndices.size - 1 && newStartIndices[i + 1] > maxCropPos
val caretFarAway = i == newStartIndices.size - 1 && maxCropPos < caretPosition
if (shortNextContext || caretFarAway) {
persistentStartIndices.add(newStartIndices[i])
}
}
newStartIndices = persistentStartIndices
}
newStartIndices
}
minContextLen != null -> (0..caretPosition step minContextLen).toList()
else -> null
}
if (startIndices != null && startIndices.isNotEmpty()) {
contextStartIndex =
startIndices.firstOrNull { it >= contextStartIndex } ?: throw LongLastLineException()
}
return contextIds.copyOfRange(contextStartIndex, caretPosition)
}
}
}
|
apache-2.0
|
1f59548c3d94ab5264b3b0791f8f6cb1
| 44.007299 | 117 | 0.712455 | 4.608371 | false | true | false | false |
JetBrains/intellij-community
|
plugins/kotlin/project-configuration/src/org/jetbrains/kotlin/idea/versions/KotlinRuntimeLibraryUtil.kt
|
1
|
5775
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.versions
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderEnumerator
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.ScalarIndexExtension
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.projectConfiguration.KotlinProjectConfigurationBundle
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion
import org.jetbrains.kotlin.platform.isJs
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.utils.JsMetadataVersion
import org.jetbrains.kotlin.utils.PathUtil
fun getLibraryRootsWithIncompatibleAbi(module: Module): Collection<BinaryVersionedFile<BinaryVersion>> {
val platform = module.platform
val badRoots = when {
platform.isJvm() -> getLibraryRootsWithIncompatibleAbiJvm(module)
platform.isJs() -> getLibraryRootsWithIncompatibleAbiJavaScript(module)
// TODO: also check it for Native KT-34525
else -> return emptyList()
}
return if (badRoots.isEmpty()) emptyList() else badRoots.toHashSet()
}
fun getLibraryRootsWithIncompatibleAbiJvm(module: Module): Collection<BinaryVersionedFile<JvmMetadataVersion>> {
return getLibraryRootsWithAbiIncompatibleVersion(module, JvmMetadataVersion.INSTANCE, KotlinJvmMetadataVersionIndex)
}
fun getLibraryRootsWithIncompatibleAbiJavaScript(module: Module): Collection<BinaryVersionedFile<JsMetadataVersion>> {
return getLibraryRootsWithAbiIncompatibleVersion(module, JsMetadataVersion.INSTANCE, KotlinJsMetadataVersionIndex)
}
fun Project.forEachAllUsedLibraries(processor: (Library) -> Boolean) {
OrderEnumerator.orderEntries(this).forEachLibrary(processor)
}
data class BinaryVersionedFile<out T : BinaryVersion>(val file: VirtualFile, val version: T, val supportedVersion: T)
private fun <T : BinaryVersion> getLibraryRootsWithAbiIncompatibleVersion(
module: Module,
supportedVersion: T,
index: ScalarIndexExtension<T>
): Collection<BinaryVersionedFile<T>> {
val id = index.name
val moduleWithAllDependencies = setOf(module) + ModuleUtil.getAllDependentModules(module)
val moduleWithAllDependentLibraries = GlobalSearchScope.union(
moduleWithAllDependencies.map { it.moduleWithLibrariesScope }.toTypedArray()
)
val allVersions = FileBasedIndex.getInstance().getAllKeys(id, module.project)
val badVersions = allVersions.filterNot(BinaryVersion::isCompatible).toHashSet()
val badRoots = hashSetOf<BinaryVersionedFile<T>>()
val fileIndex = ProjectFileIndex.getInstance(module.project)
for (version in badVersions) {
val indexedFiles = FileBasedIndex.getInstance().getContainingFiles(id, version, moduleWithAllDependentLibraries)
for (indexedFile in indexedFiles) {
val libraryRoot = fileIndex.getClassRootForFile(indexedFile) ?: error(
"Only library roots were requested, and only class files should be indexed with the $id key. " +
"File: ${indexedFile.path}"
)
badRoots.add(BinaryVersionedFile(VfsUtil.getLocalFile(libraryRoot), version, supportedVersion))
}
}
return badRoots
}
const val MAVEN_JS_STDLIB_ID = PathUtil.JS_LIB_NAME
const val MAVEN_JS_TEST_ID = PathUtil.KOTLIN_TEST_JS_NAME
val LOG = Logger.getInstance("org.jetbrains.kotlin.idea.versions.KotlinRuntimeLibraryUtilKt")
data class LibInfo(
val groupId: String,
val name: String,
val version: String = "0.0.0"
)
data class DeprecatedLibInfo(
val old: LibInfo,
val new: LibInfo,
val outdatedAfterVersion: String,
@Nls val message: String
)
private fun deprecatedLib(
oldGroupId: String,
oldName: String,
newGroupId: String = oldGroupId,
newName: String = oldName,
outdatedAfterVersion: String,
@Nls message: String
): DeprecatedLibInfo {
return DeprecatedLibInfo(
old = LibInfo(groupId = oldGroupId, name = oldName),
new = LibInfo(groupId = newGroupId, name = newName),
outdatedAfterVersion = outdatedAfterVersion,
message = message
)
}
val DEPRECATED_LIBRARIES_INFORMATION = listOf(
deprecatedLib(
oldGroupId = "org.jetbrains.kotlin",
oldName = PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_NAME, newName = PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_NAME,
outdatedAfterVersion = "1.2.0-rc-39",
message = KotlinProjectConfigurationBundle.message(
"version.message.is.deprecated.since.1.2.0.and.should.be.replaced.with",
PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_NAME,
PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_NAME
)
),
deprecatedLib(
oldGroupId = "org.jetbrains.kotlin",
oldName = PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_NAME, newName = PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME,
outdatedAfterVersion = "1.2.0-rc-39",
message = KotlinProjectConfigurationBundle.message(
"version.message.is.deprecated.since.1.2.0.and.should.be.replaced.with",
PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_NAME,
PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME
)
)
)
|
apache-2.0
|
ea0d6f5e217cbe0320dd4193fc43d351
| 39.964539 | 120 | 0.752381 | 4.501169 | false | false | false | false |
vhromada/Catalog
|
core/src/test/kotlin/com/github/vhromada/catalog/repository/EpisodeRepositorySpringTest.kt
|
1
|
10602
|
package com.github.vhromada.catalog.repository
import com.github.vhromada.catalog.TestConfiguration
import com.github.vhromada.catalog.utils.AccountUtils
import com.github.vhromada.catalog.utils.AuditUtils
import com.github.vhromada.catalog.utils.EpisodeUtils
import com.github.vhromada.catalog.utils.SeasonUtils
import com.github.vhromada.catalog.utils.ShowUtils
import com.github.vhromada.catalog.utils.TestConstants
import com.github.vhromada.catalog.utils.fillAudit
import com.github.vhromada.catalog.utils.updated
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.annotation.Rollback
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.transaction.annotation.Transactional
import javax.persistence.EntityManager
import javax.persistence.PersistenceContext
/**
* A class represents test for class [EpisodeRepository].
*
* @author Vladimir Hromada
*/
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [TestConfiguration::class])
@Transactional
@Rollback
class EpisodeRepositorySpringTest {
/**
* Instance of [EntityManager]
*/
@PersistenceContext
private lateinit var entityManager: EntityManager
/**
* Instance of [EpisodeRepository]
*/
@Autowired
private lateinit var repository: EpisodeRepository
/**
* Test method for get episode.
*/
@Test
fun getEpisode() {
for (i in 1..ShowUtils.SHOWS_COUNT) {
for (j in 1..SeasonUtils.SEASONS_PER_SHOW_COUNT) {
for (k in 1..EpisodeUtils.EPISODES_PER_SEASON_COUNT) {
val id = (i - 1) * EpisodeUtils.EPISODES_PER_SHOW_COUNT + (j - 1) * EpisodeUtils.EPISODES_PER_SEASON_COUNT + k
val episode = repository.findById(id).orElse(null)
EpisodeUtils.assertEpisodeDeepEquals(expected = ShowUtils.getDomainShow(index = i).seasons[j - 1].episodes[k - 1], actual = episode)
}
}
}
assertThat(repository.findById(Int.MAX_VALUE)).isNotPresent
assertSoftly {
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
}
}
/**
* Test method for add episode.
*/
@Test
@DirtiesContext
fun add() {
val episode = EpisodeUtils.newDomainEpisode(id = null)
episode.season = SeasonUtils.getDomainSeason(entityManager = entityManager, id = 1)
val expectedEpisode = EpisodeUtils.newDomainEpisode(id = EpisodeUtils.EPISODES_COUNT + 1)
.fillAudit(audit = AuditUtils.newAudit())
expectedEpisode.season = SeasonUtils.getDomainSeason(entityManager = entityManager, id = 1)
repository.saveAndFlush(episode)
assertSoftly {
it.assertThat(episode.id).isEqualTo(EpisodeUtils.EPISODES_COUNT + 1)
it.assertThat(episode.createdUser).isEqualTo(AccountUtils.getDomainAccount(index = 2).uuid)
it.assertThat(episode.createdTime).isEqualTo(TestConstants.TIME)
it.assertThat(episode.updatedUser).isEqualTo(AccountUtils.getDomainAccount(index = 2).uuid)
it.assertThat(episode.updatedTime).isEqualTo(TestConstants.TIME)
}
EpisodeUtils.assertEpisodeDeepEquals(expected = expectedEpisode, actual = EpisodeUtils.getDomainEpisode(entityManager = entityManager, id = EpisodeUtils.EPISODES_COUNT + 1))
assertSoftly {
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT + 1)
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
}
}
/**
* Test method for update episode.
*/
@Test
fun update() {
val episode = EpisodeUtils.getDomainEpisode(entityManager = entityManager, id = 1)!!
.updated()
val expectedEpisode = ShowUtils.getDomainShow(index = 1).seasons.first().episodes.first()
.updated()
.fillAudit(audit = AuditUtils.updatedAudit())
repository.saveAndFlush(episode)
EpisodeUtils.assertEpisodeDeepEquals(expected = expectedEpisode, actual = EpisodeUtils.getDomainEpisode(entityManager = entityManager, id = 1))
assertSoftly {
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
}
}
/**
* Test method for get episodes by season ID.
*/
@Test
fun findAllBySeasonId() {
for (i in 1..ShowUtils.SHOWS_COUNT) {
val show = ShowUtils.getDomainShow(index = i)
for (season in show.seasons) {
val episodes = repository.findAllBySeasonId(id = season.id!!, pageable = Pageable.ofSize(EpisodeUtils.EPISODES_PER_SEASON_COUNT))
assertSoftly {
it.assertThat(episodes.number).isEqualTo(0)
it.assertThat(episodes.totalPages).isEqualTo(1)
it.assertThat(episodes.totalElements).isEqualTo(EpisodeUtils.EPISODES_PER_SEASON_COUNT.toLong())
}
EpisodeUtils.assertDomainEpisodesDeepEquals(expected = season.episodes, actual = episodes.content)
}
}
assertSoftly {
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
}
}
/**
* Test method for get episodes by season ID with invalid paging.
*/
@Test
fun findAllBySeasonIdInvalidPaging() {
for (i in 1..ShowUtils.SHOWS_COUNT) {
val show = ShowUtils.getDomainShow(index = i)
for (season in show.seasons) {
val episodes = repository.findAllBySeasonId(id = season.id!!, pageable = PageRequest.of(2, EpisodeUtils.EPISODES_PER_SEASON_COUNT))
assertSoftly {
it.assertThat(episodes.content).isEmpty()
it.assertThat(episodes.number).isEqualTo(2)
it.assertThat(episodes.totalPages).isEqualTo(1)
it.assertThat(episodes.totalElements).isEqualTo(EpisodeUtils.EPISODES_PER_SEASON_COUNT.toLong())
}
}
}
assertSoftly {
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
}
}
/**
* Test method for get episodes by season ID with not existing season ID.
*/
@Test
fun findAllBySeasonIdNotExistingSeasonId() {
val episodes = repository.findAllBySeasonId(id = Int.MAX_VALUE, pageable = Pageable.ofSize(EpisodeUtils.EPISODES_PER_SEASON_COUNT))
assertSoftly {
it.assertThat(episodes.content).isEmpty()
it.assertThat(episodes.number).isEqualTo(0)
it.assertThat(episodes.totalPages).isEqualTo(0)
it.assertThat(episodes.totalElements).isEqualTo(0L)
}
assertSoftly {
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
}
}
/**
* Test method for find episode by UUID.
*/
@Test
fun findByUuid() {
for (i in 1..ShowUtils.SHOWS_COUNT) {
val show = ShowUtils.getDomainShow(index = i)
for (season in show.seasons) {
for (episode in season.episodes) {
val result = repository.findByUuid(uuid = episode.uuid).orElse(null)
EpisodeUtils.assertEpisodeDeepEquals(expected = episode, actual = result)
}
}
}
assertThat(repository.findByUuid(uuid = TestConstants.UUID)).isNotPresent
assertSoftly {
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
}
}
/**
* Test method for get statistics.
*/
@Test
fun getStatistics() {
val result = repository.getStatistics()
EpisodeUtils.assertStatisticsDeepEquals(expected = EpisodeUtils.getStatistics(), actual = result)
assertSoftly {
it.assertThat(EpisodeUtils.getEpisodesCount(entityManager = entityManager)).isEqualTo(EpisodeUtils.EPISODES_COUNT)
it.assertThat(SeasonUtils.getSeasonsCount(entityManager = entityManager)).isEqualTo(SeasonUtils.SEASONS_COUNT)
it.assertThat(ShowUtils.getShowsCount(entityManager = entityManager)).isEqualTo(ShowUtils.SHOWS_COUNT)
}
}
}
|
mit
|
bcf0fa5dff6051bf669a951d285847eb
| 42.809917 | 181 | 0.691002 | 4.656126 | false | true | false | false |
apollographql/apollo-android
|
apollo-normalized-cache-api/src/commonMain/kotlin/com/apollographql/apollo3/cache/normalized/api/NormalizedCacheFactory.kt
|
1
|
997
|
package com.apollographql.apollo3.cache.normalized.api
/**
* A Factory used to construct an instance of a [NormalizedCache] configured with the custom scalar adapters set in
* ApolloClient.Builder#addCustomScalarAdapter(ScalarType, CustomScalarAdapter).
*/
abstract class NormalizedCacheFactory {
private var nextFactory: NormalizedCacheFactory? = null
/**
* ApolloClient.Builder#addCustomScalarAdapter(ScalarType, CustomScalarAdapter).
* @return An implementation of [NormalizedCache].
*/
abstract fun create(): NormalizedCache
fun createChain(): NormalizedCache {
val nextFactory = nextFactory
return if (nextFactory != null) {
create().chain(nextFactory.createChain())
} else {
create()
}
}
fun chain(factory: NormalizedCacheFactory) = apply {
var leafFactory: NormalizedCacheFactory = this
while (leafFactory.nextFactory != null) {
leafFactory = leafFactory.nextFactory!!
}
leafFactory.nextFactory = factory
}
}
|
mit
|
7819bd88b097dd392a44c3818b1a0227
| 29.212121 | 115 | 0.731194 | 4.552511 | false | false | false | false |
StepicOrg/stepik-android
|
app/src/main/java/org/stepik/android/domain/mobile_tiers/interactor/MobileTiersInteractor.kt
|
1
|
1705
|
package org.stepik.android.domain.mobile_tiers.interactor
import com.android.billingclient.api.BillingClient
import io.reactivex.Single
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.mobile_tiers.model.LightSku
import org.stepik.android.domain.mobile_tiers.model.MobileTier
import org.stepik.android.domain.mobile_tiers.repository.LightSkuRepository
import org.stepik.android.domain.mobile_tiers.repository.MobileTiersRepository
import org.stepik.android.model.Course
import org.stepik.android.remote.mobile_tiers.model.MobileTierCalculation
import javax.inject.Inject
class MobileTiersInteractor
@Inject
constructor(
private val mobileTiersRepository: MobileTiersRepository,
private val lightSkuRepository: LightSkuRepository
) {
fun fetchTiersAndSkus(courses: List<Course>, sourceType: DataSourceType): Single<Pair<List<MobileTier>, List<LightSku>>> {
val mobileTierCalculations = courses
.filter(Course::isPaid)
.map { MobileTierCalculation(course = it.id) }
return mobileTiersRepository
.calculateMobileTiers(mobileTierCalculations)
.flatMap { mobileTiers ->
val priceTiers = mobileTiers.mapNotNull(MobileTier::priceTier)
val promoTiers = mobileTiers.mapNotNull(MobileTier::promoTier)
val skuIds = priceTiers.union(promoTiers).toList()
lightSkuRepository
.getLightInventory(BillingClient.SkuType.INAPP, skuIds, sourceType)
.map { lightSkus -> mobileTiers to lightSkus }
}
.onErrorReturnItem(emptyList<MobileTier>() to emptyList<LightSku>())
}
}
|
apache-2.0
|
2697b68a4c4628dd9a630eae8d1ebdf1
| 46.388889 | 126 | 0.731965 | 4.645777 | false | false | false | false |
evant/binding-collection-adapter
|
app/src/main/java/me/tatarka/bindingcollectionadapter/sample/FragmentViewPager2View.kt
|
1
|
1584
|
package me.tatarka.bindingcollectionadapter.sample
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.viewModels
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.tabs.TabLayoutMediator
import me.tatarka.bindingcollectionadapter.sample.databinding.Viewpager2ViewBinding
class FragmentViewPager2View : Fragment() {
private val viewModel: MutableViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.setCheckable(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return Viewpager2ViewBinding.inflate(inflater, container, false).also {
it.lifecycleOwner = this
it.viewModel = viewModel
it.listeners = PagerListeners(viewModel)
it.executePendingBindings()
TabLayoutMediator(it.tabs, it.pager) { tab, position ->
val item = viewModel.items[position]
tab.text = viewModel.pageTitles.getPageTitle(position, item)
}.attach()
}.root
}
private class PagerListeners(
private val delegate: Listeners
) : Listeners {
override fun onAddItem() {
delegate.onAddItem()
}
override fun onRemoveItem() {
delegate.onRemoveItem()
}
}
}
|
apache-2.0
|
b1b622e34c927a889cd9a8cde7e74294
| 30.058824 | 83 | 0.683712 | 5.044586 | false | false | false | false |
aporter/coursera-android
|
ExamplesKotlin/NotificationStatusBarWithCustomView/app/src/main/java/course/examples/notification/statusbarwithcustomview/NotificationStatusBarWithCustomViewActivity.kt
|
1
|
4468
|
package course.examples.notification.statusbarwithcustomview
import android.app.Activity
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.media.AudioAttributes
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.RemoteViews
class NotificationStatusBarWithCustomViewActivity : Activity() {
companion object {
// Notification ID to allow for future updates
private val MY_NOTIFICATION_ID = 1
private const val KEY_COUNT = "key_count"
// Notification Text Elements
private val mTickerText = "This is a Really, Really, Super Long Notification Message!"
private val mContentText = "You've Been Notified!"
// Notification Sound and Vibration on Arrival
private val soundURI = Uri
.parse("android.resource://course.examples.notification.statusbarwithcustomview/" + R.raw.alarm_rooster)
private val mVibratePattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
// Notification Channel ID
private lateinit var mChannelID: String
private lateinit var mNotificationManager: NotificationManager
// private lateinit var soundURI: Uri
}
// Notification Count
private var mNotificationCount: Int = 0
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
savedInstanceState?.run {
mNotificationCount = savedInstanceState.getInt(KEY_COUNT)
}
createNotificationChannel()
}
private fun createNotificationChannel() {
mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mChannelID = "$packageName.channel_01"
// The user-visible name of the channel.
val name = getString(R.string.channel_name)
// The user-visible description of the channel.
val description = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_HIGH
val mChannel = NotificationChannel(mChannelID, name, importance)
// Configure the notification channel.
mChannel.description = description
mChannel.enableLights(true)
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.lightColor = Color.RED
mChannel.enableVibration(true)
mChannel.vibrationPattern = mVibratePattern
// Uri soundURI = Uri.parse("android.resource://" + packageName + "/" + R.raw.alarm_rooster);
mChannel.setSound(
soundURI,
AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build()
)
mNotificationManager.createNotificationChannel(mChannel)
}
fun onClick(v: View) {
// Define action Intent
val notificationIntent = Intent(
applicationContext,
NotificationSubActivity::class.java
).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val contentIntent = PendingIntent.getActivity(
applicationContext, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT
)
val contentView = RemoteViews(
packageName,
R.layout.custom_notification
)
contentView.setTextViewText(
R.id.notification_text,
"$mContentText ( ${++mNotificationCount} )"
)
// Define the Notification's expanded message and Intent:
val notificationBuilder = Notification.Builder(
applicationContext, mChannelID
)
.setTicker(mTickerText)
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setCustomContentView(contentView)
// Pass the Notification to the NotificationManager:
mNotificationManager.notify(
MY_NOTIFICATION_ID,
notificationBuilder.build()
)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(KEY_COUNT, mNotificationCount)
}
}
|
mit
|
8baea598c74aaa0ddbbb3bd5249be2b8
| 32.103704 | 116 | 0.681065 | 5.262662 | false | false | false | false |
Kotlin/kotlinx.coroutines
|
kotlinx-coroutines-core/common/src/Await.kt
|
1
|
6485
|
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlinx.atomicfu.*
import kotlin.coroutines.*
/**
* Awaits for completion of given deferred values without blocking a thread and resumes normally with the list of values
* when all deferred computations are complete or resumes with the first thrown exception if any of computations
* complete exceptionally including cancellation.
*
* This function is **not** equivalent to `deferreds.map { it.await() }` which fails only when it sequentially
* gets to wait for the failing deferred, while this `awaitAll` fails immediately as soon as any of the deferreds fail.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting,
* this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**. If the job was cancelled while this function was
* suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details.
*/
public suspend fun <T> awaitAll(vararg deferreds: Deferred<T>): List<T> =
if (deferreds.isEmpty()) emptyList() else AwaitAll(deferreds).await()
/**
* Awaits for completion of given deferred values without blocking a thread and resumes normally with the list of values
* when all deferred computations are complete or resumes with the first thrown exception if any of computations
* complete exceptionally including cancellation.
*
* This function is **not** equivalent to `this.map { it.await() }` which fails only when it sequentially
* gets to wait for the failing deferred, while this `awaitAll` fails immediately as soon as any of the deferreds fail.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting,
* this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**. If the job was cancelled while this function was
* suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details.
*/
public suspend fun <T> Collection<Deferred<T>>.awaitAll(): List<T> =
if (isEmpty()) emptyList() else AwaitAll(toTypedArray()).await()
/**
* Suspends current coroutine until all given jobs are complete.
* This method is semantically equivalent to joining all given jobs one by one with `jobs.forEach { it.join() }`.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting,
* this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**. If the job was cancelled while this function was
* suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details.
*/
public suspend fun joinAll(vararg jobs: Job): Unit = jobs.forEach { it.join() }
/**
* Suspends current coroutine until all given jobs are complete.
* This method is semantically equivalent to joining all given jobs one by one with `forEach { it.join() }`.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting,
* this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**. If the job was cancelled while this function was
* suspended, it will not resume successfully. See [suspendCancellableCoroutine] documentation for low-level details.
*/
public suspend fun Collection<Job>.joinAll(): Unit = forEach { it.join() }
private class AwaitAll<T>(private val deferreds: Array<out Deferred<T>>) {
private val notCompletedCount = atomic(deferreds.size)
suspend fun await(): List<T> = suspendCancellableCoroutine { cont ->
// Intricate dance here
// Step 1: Create nodes and install them as completion handlers, they may fire!
val nodes = Array(deferreds.size) { i ->
val deferred = deferreds[i]
deferred.start() // To properly await lazily started deferreds
AwaitAllNode(cont).apply {
handle = deferred.invokeOnCompletion(asHandler)
}
}
val disposer = DisposeHandlersOnCancel(nodes)
// Step 2: Set disposer to each node
nodes.forEach { it.disposer = disposer }
// Here we know that if any code the nodes complete, it will dispose the rest
// Step 3: Now we can check if continuation is complete
if (cont.isCompleted) {
// it is already complete while handlers were being installed -- dispose them all
disposer.disposeAll()
} else {
cont.invokeOnCancellation(handler = disposer.asHandler)
}
}
private inner class DisposeHandlersOnCancel(private val nodes: Array<AwaitAllNode>) : CancelHandler() {
fun disposeAll() {
nodes.forEach { it.handle.dispose() }
}
override fun invoke(cause: Throwable?) { disposeAll() }
override fun toString(): String = "DisposeHandlersOnCancel[$nodes]"
}
private inner class AwaitAllNode(private val continuation: CancellableContinuation<List<T>>) : JobNode() {
lateinit var handle: DisposableHandle
private val _disposer = atomic<DisposeHandlersOnCancel?>(null)
var disposer: DisposeHandlersOnCancel?
get() = _disposer.value
set(value) { _disposer.value = value }
override fun invoke(cause: Throwable?) {
if (cause != null) {
val token = continuation.tryResumeWithException(cause)
if (token != null) {
continuation.completeResume(token)
// volatile read of disposer AFTER continuation is complete
// and if disposer was already set (all handlers where already installed, then dispose them all)
disposer?.disposeAll()
}
} else if (notCompletedCount.decrementAndGet() == 0) {
continuation.resume(deferreds.map { it.getCompleted() })
// Note that all deferreds are complete here, so we don't need to dispose their nodes
}
}
}
}
|
apache-2.0
|
4feb35ba39c8a4392b1c8872877ae227
| 50.468254 | 120 | 0.703007 | 4.879609 | false | false | false | false |
JetBrains/teamcity-dnx-plugin
|
plugin-dotnet-server/src/main/kotlin/jetbrains/buildServer/dotnet/DotnetToolProviderAdapter.kt
|
1
|
3153
|
package jetbrains.buildServer.dotnet
import com.intellij.openapi.diagnostic.Logger
import jetbrains.buildServer.FileSystemService
import jetbrains.buildServer.ToolService
import jetbrains.buildServer.tools.*
import jetbrains.buildServer.web.openapi.PluginDescriptor
import java.io.File
import java.io.FileFilter
class DotnetToolProviderAdapter(
private val _toolService: ToolService,
private val _pluginDescriptor: PluginDescriptor,
private val _packageVersionParser: SemanticVersionParser,
private val _fileSystemService: FileSystemService) : ServerToolProviderAdapter() {
override fun getType(): jetbrains.buildServer.tools.ToolType = DotnetToolTypeAdapter.Shared
override fun getAvailableToolVersions(): MutableCollection<out ToolVersion> =
_toolService.getTools(DotnetToolTypeAdapter.Shared, DotnetToolTypeAdapter.Shared.type).toMutableList()
override fun tryGetPackageVersion(toolPackage: File) =
_toolService.tryGetPackageVersion(DotnetToolTypeAdapter.Shared, toolPackage) ?: super.tryGetPackageVersion(toolPackage)
override fun fetchToolPackage(toolVersion: ToolVersion, targetDirectory: File) =
_toolService.fetchToolPackage(DotnetToolTypeAdapter.Shared, toolVersion, targetDirectory)
override fun unpackToolPackage(toolPackage: File, targetDirectory: File) =
_toolService.unpackToolPackage(DotnetToolTypeAdapter.Shared, toolPackage, "build/_common/", targetDirectory)
override fun getDefaultBundledVersionId(): String? = null
override fun getBundledToolVersions(): MutableCollection<InstalledToolVersion> {
val pluginPath = File(_pluginDescriptor.pluginRoot, "server")
val toolPackage = _fileSystemService
.list(pluginPath)
.filter { NUGET_BUNDLED_FILTER.accept(it) }
.firstOrNull()
if (toolPackage == null) {
LOG.warn("Failed to find package spec on path $pluginPath")
return super.getBundledToolVersions()
}
val toolVersion = _packageVersionParser.tryParse(toolPackage.nameWithoutExtension)
?.let { GetPackageVersionResult.version(DotnetToolVersion(it.toString())).toolVersion }
if (toolVersion == null) {
LOG.warn("Failed to parse version from \"${toolPackage.nameWithoutExtension}\"")
return super.getBundledToolVersions()
}
return mutableListOf(SimpleInstalledToolVersion.newBundledToAgentTool(DotnetToolVersion(toolVersion.version), toolPackage))
}
private inner class DotnetToolVersion internal constructor(version: String)
: SimpleToolVersion(type, version, ToolVersionIdHelper.getToolId(DotnetConstants.INTEGRATION_PACKAGE_TYPE, version))
companion object {
private val LOG: Logger = Logger.getInstance(DotnetToolProviderAdapter::class.java.name)
private val NUGET_BUNDLED_FILTER = FileFilter { packageFile ->
packageFile.isFile && packageFile.nameWithoutExtension.startsWith(DotnetConstants.INTEGRATION_PACKAGE_TYPE, true) && "jar".equals(packageFile.extension, true)
}
}
}
|
apache-2.0
|
25e2f1e9671e9a55bffb39dea62d58a6
| 46.074627 | 170 | 0.741833 | 4.981043 | false | false | false | false |
leafclick/intellij-community
|
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/Variables.kt
|
1
|
10727
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.SmartList
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.settings.XDebuggerSettingsManager
import org.jetbrains.concurrency.Obsolescent
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.then
import org.jetbrains.concurrency.thenAsync
import org.jetbrains.debugger.values.ValueType
import java.util.*
import java.util.regex.Pattern
private val UNNAMED_FUNCTION_PATTERN = Pattern.compile("^function[\\t ]*\\(")
private val NATURAL_NAME_COMPARATOR = Comparator<Variable> { o1, o2 -> naturalCompare(o1.name, o2.name) }
// start properties loading to achieve, possibly, parallel execution (properties loading & member filter computation)
fun processVariables(context: VariableContext,
variables: Promise<List<Variable>>,
obsolescent: Obsolescent,
consumer: (memberFilter: MemberFilter, variables: List<Variable>) -> Unit): Promise<Unit> {
return context.memberFilter
.thenAsync(obsolescent) { memberFilter ->
variables
.then(obsolescent) {
consumer(memberFilter, it)
}
}
}
fun processScopeVariables(scope: Scope,
node: XCompositeNode,
context: VariableContext,
isLast: Boolean): Promise<Unit> {
return processVariables(context, scope.variablesHost.get(), node) { memberFilter, variables ->
val additionalVariables = memberFilter.additionalVariables
val exceptionValue = context.vm?.suspendContextManager?.context?.exceptionData?.exceptionValue
val properties = ArrayList<Variable>(variables.size + additionalVariables.size + (if (exceptionValue == null) 0 else 1))
exceptionValue?.let {
properties.add(VariableImpl("Exception", it))
}
val functions = SmartList<Variable>()
for (variable in variables) {
if (memberFilter.isMemberVisible(variable) && variable.name != RECEIVER_NAME && variable.name != memberFilter.sourceNameToRaw(RECEIVER_NAME)) {
val value = variable.value
if (value != null && value.type == ValueType.FUNCTION && value.valueString != null && !UNNAMED_FUNCTION_PATTERN.matcher(
value.valueString).lookingAt()) {
functions.add(variable)
}
else {
properties.add(variable)
}
}
}
addAditionalVariables(additionalVariables, properties, memberFilter)
if (XDebuggerSettingsManager.getInstance().dataViewSettings.isSortValues) {
val comparator = if (memberFilter.hasNameMappings()) Comparator { o1, o2 ->
naturalCompare(memberFilter.rawNameToSource(o1), memberFilter.rawNameToSource(o2))
}
else NATURAL_NAME_COMPARATOR
properties.sortWith(comparator)
functions.sortWith(comparator)
}
if (!properties.isEmpty()) {
node.addChildren(createVariablesList(properties, context, memberFilter), functions.isEmpty() && isLast)
}
if (!functions.isEmpty()) {
node.addChildren(XValueChildrenList.bottomGroup(VariablesGroup("Functions", functions, context)), isLast)
}
else if (isLast && properties.isEmpty()) {
node.addChildren(XValueChildrenList.EMPTY, true)
}
}
}
fun processNamedObjectProperties(variables: List<Variable>,
node: XCompositeNode,
context: VariableContext,
memberFilter: MemberFilter,
maxChildrenToAdd: Int,
defaultIsLast: Boolean): List<Variable>? {
val list = filterAndSort(variables, memberFilter)
if (list.isEmpty()) {
if (defaultIsLast) {
node.addChildren(XValueChildrenList.EMPTY, true)
}
return null
}
val to = Math.min(maxChildrenToAdd, list.size)
val isLast = to == list.size
node.addChildren(createVariablesList(list, 0, to, context, memberFilter), defaultIsLast && isLast)
if (isLast) {
return null
}
else {
node.tooManyChildren(list.size - to)
return list
}
}
fun filterAndSort(variables: List<Variable>, memberFilter: MemberFilter): List<Variable> {
if (variables.isEmpty()) {
return emptyList()
}
val additionalVariables = memberFilter.additionalVariables
val result = ArrayList<Variable>(variables.size + additionalVariables.size)
for (variable in variables) {
if (memberFilter.isMemberVisible(variable)) {
result.add(variable)
}
}
if (XDebuggerSettingsManager.getInstance().dataViewSettings.isSortValues) {
result.sortWith(NATURAL_NAME_COMPARATOR)
}
addAditionalVariables(additionalVariables, result, memberFilter)
return result
}
private fun addAditionalVariables(additionalVariables: Collection<Variable>,
result: MutableList<Variable>,
memberFilter: MemberFilter,
functions: MutableList<Variable>? = null) {
val oldSize = result.size
ol@ for (variable in additionalVariables) {
if (!memberFilter.isMemberVisible(variable)) continue
for (i in 0..(oldSize - 1)) {
val vmVariable = result[i]
if (memberFilter.rawNameToSource(vmVariable) == memberFilter.rawNameToSource(variable)) {
// we prefer additionalVariable here because it is more smart variable (e.g. NavigatableVariable)
val vmValue = vmVariable.value
// to avoid evaluation, use vm value directly
if (vmValue != null) {
variable.value = vmValue
}
result.set(i, variable)
continue@ol
}
}
if (functions != null) {
for (function in functions) {
if (memberFilter.rawNameToSource(function) == memberFilter.rawNameToSource(variable)) {
continue@ol
}
}
}
result.add(variable)
}
}
// prefixed '_' must be last, uppercase after lowercase, fixed case sensitive natural compare
private fun naturalCompare(string1: String?, string2: String?): Int {
//noinspection StringEquality
if (string1 === string2) {
return 0
}
if (string1 == null) {
return -1
}
if (string2 == null) {
return 1
}
val string1Length = string1.length
val string2Length = string2.length
var i = 0
var j = 0
while (i < string1Length && j < string2Length) {
var ch1 = string1[i]
var ch2 = string2[j]
if ((StringUtil.isDecimalDigit(ch1) || ch1 == ' ') && (StringUtil.isDecimalDigit(ch2) || ch2 == ' ')) {
var startNum1 = i
while (ch1 == ' ' || ch1 == '0') {
// skip leading spaces and zeros
startNum1++
if (startNum1 >= string1Length) {
break
}
ch1 = string1[startNum1]
}
var startNum2 = j
while (ch2 == ' ' || ch2 == '0') {
// skip leading spaces and zeros
startNum2++
if (startNum2 >= string2Length) {
break
}
ch2 = string2[startNum2]
}
i = startNum1
j = startNum2
// find end index of number
while (i < string1Length && StringUtil.isDecimalDigit(string1[i])) {
i++
}
while (j < string2Length && StringUtil.isDecimalDigit(string2[j])) {
j++
}
val lengthDiff = (i - startNum1) - (j - startNum2)
if (lengthDiff != 0) {
// numbers with more digits are always greater than shorter numbers
return lengthDiff
}
while (startNum1 < i) {
// compare numbers with equal digit count
val diff = string1[startNum1] - string2[startNum2]
if (diff != 0) {
return diff
}
startNum1++
startNum2++
}
i--
j--
}
else if (ch1 != ch2) {
fun reverseCase(ch: Char) = when {
ch.isUpperCase() -> ch.toLowerCase()
ch.isLowerCase() -> ch.toUpperCase()
else -> ch
}
when {
ch1 == '_' -> return 1
ch2 == '_' -> return -1
else -> return reverseCase(ch1) - reverseCase(ch2)
}
}
i++
j++
}
// After the loop the end of one of the strings might not have been reached, if the other
// string ends with a number and the strings are equal until the end of that number. When
// there are more characters in the string, then it is greater.
if (i < string1Length) {
return 1
}
else if (j < string2Length) {
return -1
}
return string1Length - string2Length
}
@JvmOverloads fun createVariablesList(variables: List<Variable>, variableContext: VariableContext, memberFilter: MemberFilter? = null): XValueChildrenList {
return createVariablesList(variables, 0, variables.size, variableContext, memberFilter)
}
fun createVariablesList(variables: List<Variable>, from: Int, to: Int, variableContext: VariableContext, memberFilter: MemberFilter?): XValueChildrenList {
val list = XValueChildrenList(to - from)
var getterOrSetterContext: VariableContext? = null
for (i in from until to) {
val variable = variables[i]
val normalizedName = memberFilter?.rawNameToSource(variable) ?: variable.name
list.add(VariableView(normalizedName, variable, variableContext))
if (variable is ObjectProperty) {
if (variable.getter != null) {
if (getterOrSetterContext == null) {
getterOrSetterContext = NonWatchableVariableContext(variableContext)
}
list.add(VariableView(VariableImpl("get $normalizedName", variable.getter!!), getterOrSetterContext))
}
if (variable.setter != null) {
if (getterOrSetterContext == null) {
getterOrSetterContext = NonWatchableVariableContext(variableContext)
}
list.add(VariableView(VariableImpl("set $normalizedName", variable.setter!!), getterOrSetterContext))
}
}
}
return list
}
private class NonWatchableVariableContext(variableContext: VariableContext) : VariableContextWrapper(variableContext, null) {
override fun watchableAsEvaluationExpression() = false
}
|
apache-2.0
|
e11a75b2075b6237fd81e786ff15b487
| 34.058824 | 156 | 0.656474 | 4.531897 | false | false | false | false |
bitsydarel/DBWeather
|
dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/implementations/datasources/local/lives/RoomLivesDataSource.kt
|
1
|
5926
|
/*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweatherdata.implementations.datasources.local.lives
import android.content.Context
import android.support.annotation.RestrictTo
import android.support.annotation.VisibleForTesting
import com.dbeginc.dbweatherdata.implementations.datasources.local.LocalLivesDataSource
import com.dbeginc.dbweatherdata.proxies.local.lives.LocalFavoriteLive
import com.dbeginc.dbweatherdata.proxies.local.lives.LocalIpTvPlaylist
import com.dbeginc.dbweatherdata.proxies.mappers.toDomain
import com.dbeginc.dbweatherdata.proxies.mappers.toProxy
import com.dbeginc.dbweatherdomain.entities.lives.IpTvLive
import com.dbeginc.dbweatherdomain.entities.lives.IpTvPlaylist
import com.dbeginc.dbweatherdomain.entities.lives.YoutubeLive
import com.dbeginc.dbweatherdomain.entities.requests.lives.IpTvLiveRequest
import com.dbeginc.dbweatherdomain.entities.requests.lives.YoutubeLiveRequest
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Maybe
class RoomLivesDataSource private constructor(private val db: RoomLivesDatabase) : LocalLivesDataSource {
companion object {
@JvmStatic
fun create(context: Context): RoomLivesDataSource {
return RoomLivesDataSource(RoomLivesDatabase.createDb(context))
}
@RestrictTo(RestrictTo.Scope.TESTS)
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
@JvmStatic
fun createForTest(testDatabase: RoomLivesDatabase): RoomLivesDataSource {
return RoomLivesDataSource(db = testDatabase)
}
}
override fun getAllYoutubeLives(): Flowable<List<YoutubeLive>> = db.livesDao()
.getAllYoutubeLives()
.map { lives -> lives.map { live -> live.toDomain() } }
override fun findYoutubeLive(name: String): Maybe<List<YoutubeLive>> {
return db.livesDao().findYoutubeLiveByName(name)
.map { lives -> lives.map { live -> live.toDomain() } }
}
override fun getYoutubeLives(names: List<String>): Flowable<List<YoutubeLive>> = db.livesDao().getYoutubeLives(names).map { lives -> lives.map { live -> live.toDomain() } }
override fun getYoutubeLive(name: String): Flowable<YoutubeLive> = db.livesDao().getYoutubeLive(name).map { live -> live.toDomain() }
override fun getFavoriteYoutubeLives(): Flowable<List<String>> = db.livesDao().getFavoriteYoutubeLives().map { lives -> lives.map { live -> live.live_id } }
override fun addYoutubeLiveToFavorite(request: YoutubeLiveRequest<Unit>): Completable =
Completable.fromAction {
db.livesDao().addYoutubeLiveToFavorites(
LocalFavoriteLive(request.channelName, request.channelName)
)
}
override fun removeYoutubeLiveFromFavorite(request: YoutubeLiveRequest<Unit>): Completable =
Completable.fromAction {
db.livesDao().removeYoutubeLiveFromFavorites(
LocalFavoriteLive(request.channelName, request.channelName)
)
}
override fun putYoutubeLives(lives: List<YoutubeLive>): Completable =
Completable.fromAction {
db.livesDao()
.putYoutubeLives(lives.map { live -> live.toProxy() })
}
override fun getAllIpTvPlaylist(): Flowable<List<IpTvPlaylist>> {
return db.livesDao().getAllIpTvPlaylist()
.map { ipTvs -> ipTvs.map { it.toDomain() } }
}
override fun getIpTvLives(request: IpTvLiveRequest<Unit>): Flowable<List<IpTvLive>> {
return db.livesDao()
.getIpTvLives(playlistId = request.playlist)
.map { ipTvs -> ipTvs.map { it.toDomain() } }
}
override fun getIpTvLive(request: IpTvLiveRequest<String>): Flowable<IpTvLive> {
return db.livesDao()
.getIpTvLive(playlistId = request.playlist, ipTvLiveId = request.arg)
.map { it.toDomain() }
}
override fun addIpTvLiveToFavorite(request: IpTvLiveRequest<IpTvLive>): Completable {
return Completable.fromAction {
db.livesDao()
.addIpTvLiveToFavorite(ipTvLive = request.arg.toProxy())
}
}
override fun removeTvLiveFromFavorite(request: IpTvLiveRequest<IpTvLive>): Completable {
return Completable.fromAction {
db.livesDao()
.removeTvLiveFromFavorite(ipTvLive = request.arg.toProxy())
}
}
override fun putAllIpTvPlaylist(playlists: List<IpTvPlaylist>): Completable {
return Completable.fromAction {
playlists.map { (name, channels) -> LocalIpTvPlaylist(name) to channels.map { it.toProxy() } }
.forEach {
db.livesDao().putIpTvPlaylist(playlist = it.first)
db.livesDao().putAllIpTvLives(channels = it.second)
}
}
}
override fun findPlaylist(name: String): Maybe<List<IpTvPlaylist>> {
return db.livesDao().findIpPlayLists(name)
.map { it.map { it.toDomain() } }
}
override fun findIpTvLive(playlistId: String, name: String): Maybe<List<IpTvLive>> {
return db.livesDao().findIpTvLiveWithChannelName(playlistId, name)
.map { it.map { it.toDomain() } }
}
}
|
gpl-3.0
|
f6bcb26719d214dd7f0dfe2877c93fb3
| 42.580882 | 176 | 0.678367 | 4.33504 | false | true | false | false |
leafclick/intellij-community
|
plugins/filePrediction/src/com/intellij/filePrediction/FileUsagePredictor.kt
|
1
|
3914
|
// 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.filePrediction
import com.intellij.filePrediction.ExternalReferencesResult.Companion.FAILED_COMPUTATION
import com.intellij.filePrediction.history.FilePredictionHistory
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.FileIndexFacade
import com.intellij.openapi.util.Computable
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.util.concurrency.NonUrgentExecutor
internal object FileUsagePredictor {
private const val CALCULATE_OPEN_FILE_PROBABILITY: Double = 0.5
private const val CALCULATE_CANDIDATE_PROBABILITY: Double = 0.1
private const val MAX_CANDIDATE: Int = 10
fun onFileOpened(project: Project, newFile: VirtualFile, prevFile: VirtualFile?) {
NonUrgentExecutor.getInstance().execute {
if (Math.random() < CALCULATE_OPEN_FILE_PROBABILITY) {
logFileFeatures(project, newFile, prevFile)
}
FilePredictionHistory.getInstance(project).onFileOpened(newFile.url)
}
}
private fun logFileFeatures(project: Project, newFile: VirtualFile, prevFile: VirtualFile?) {
val start = System.currentTimeMillis()
val result = calculateExternalReferences(project, prevFile)
val refsComputation = System.currentTimeMillis() - start
FileNavigationLogger.logEvent(project, newFile, prevFile, "file.opened", refsComputation, result.contains(newFile))
if (Math.random() < CALCULATE_CANDIDATE_PROBABILITY) {
prevFile?.let {
calculateCandidates(project, it, newFile, refsComputation, result)
}
}
}
private fun calculateExternalReferences(project: Project, prevFile: VirtualFile?): ExternalReferencesResult {
return ApplicationManager.getApplication().runReadAction(Computable<ExternalReferencesResult> {
if (prevFile?.isValid == false) {
return@Computable FAILED_COMPUTATION
}
val prevPsiFile = prevFile?.let { PsiManager.getInstance(project).findFile(it) }
if (DumbService.isDumb(project)) {
return@Computable FAILED_COMPUTATION
}
FilePredictionFeaturesHelper.calculateExternalReferences(prevPsiFile)
})
}
private fun calculateCandidates(project: Project,
prevFile: VirtualFile,
openedFile: VirtualFile,
refsComputation: Long,
referencesResult: ExternalReferencesResult) {
val candidates = selectFileCandidates(project, prevFile, referencesResult.references)
for (candidate in candidates) {
if (candidate != openedFile) {
FileNavigationLogger.logEvent(project, candidate, prevFile, "candidate.calculated", refsComputation, referencesResult.contains(candidate))
}
}
}
private fun selectFileCandidates(project: Project, currentFile: VirtualFile, refs: Set<VirtualFile>): List<VirtualFile> {
val result = ArrayList<VirtualFile>()
addWithLimit(refs.iterator(), result, currentFile, MAX_CANDIDATE / 2)
val fileIndex = FileIndexFacade.getInstance(project)
var parent = currentFile.parent
while (parent != null && parent.isDirectory && result.size < MAX_CANDIDATE && fileIndex.isInProjectScope(parent)) {
addWithLimit(parent.children.iterator(), result, currentFile, MAX_CANDIDATE)
parent = parent.parent
}
return result
}
private fun addWithLimit(from: Iterator<VirtualFile>, to: MutableList<VirtualFile>, skip: VirtualFile, limit: Int) {
while (to.size < limit && from.hasNext()) {
val next = from.next()
if (!next.isDirectory && skip != next) {
to.add(next)
}
}
}
}
|
apache-2.0
|
351ff6b48fa6d9dc2e18d976572818cc
| 41.543478 | 146 | 0.722279 | 4.626478 | false | false | false | false |
leafclick/intellij-community
|
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/mappings/generateMappings.kt
|
1
|
6918
|
// 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.intellij.build.images.mappings
import org.jetbrains.intellij.build.images.IconsClassGenerator
import org.jetbrains.intellij.build.images.isImage
import org.jetbrains.intellij.build.images.sync.*
import java.io.File
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.*
import kotlin.streams.toList
fun main() = generateMappings()
/**
* Generate icon mappings for https://github.com/JetBrains/IntelliJIcons-web-site
*/
private fun generateMappings() {
val exclusions = System.getProperty("mappings.json.exclude.paths")
?.split(",")
?.map(String::trim)
?: emptyList()
val context = Context()
val mappings = (loadIdeaGeneratedIcons(context) + loadNonGeneratedIcons(context, "idea")).groupBy {
"${it.product}#${it.set}"
}.toSortedMap().values.flatMap {
if (it.size > 1) {
System.err.println("Duplicates were generated $it\nRenaming")
it.subList(1, it.size).sorted().mapIndexed { i, duplicate ->
Mapping(duplicate.product, "${duplicate.set}${i + 1}", duplicate.path)
} + it.first()
}
else it
}.filter { mapping ->
exclusions.none { excluded ->
mapping.path.startsWith(excluded)
}
}
val mappingsJson = mappings.joinToString(separator = ",\n") {
it.toString().prependIndent(" ")
}
val json = """
|{
| "mappings": [
|$mappingsJson
| ]
|}
""".trimMargin()
val path = File(System.getProperty("mappings.json.path") ?: error("Specify mappings.json.path"))
val repo = findGitRepoRoot(path)
fun String.normalize() = replace(Regex("\\s+"), " ").trim()
if (json.normalize() == path.readText().normalize()) {
println("Update is not required")
}
else {
val branch = System.getProperty("branch") ?: "icons-mappings-update"
execute(repo, GIT, "checkout", "-B", branch, "origin/master")
path.writeText(json)
val jsonFile = path.toRelativeString(repo)
stageFiles(listOf(jsonFile), repo)
commitAndPush(repo, "refs/heads/$branch", "$jsonFile automatic update",
"MappingsUpdater", "[email protected]",
force = true)
}
}
private class Mapping(val product: String, val set: String, val path: String): Comparable<Mapping> {
override fun toString(): String {
val productName = when (product) {
"kotlin", "mps" -> product
else -> "intellij-$product"
}
return """
|{
| "product": "$productName",
| "set": "$set",
| "src": "../IntelliJIcons/$path",
| "category": "icons"
|}
""".trimMargin()
}
override fun compareTo(other: Mapping): Int = path.compareTo(other.path)
}
private fun loadIdeaGeneratedIcons(context: Context): Collection<Mapping> {
val home = context.devRepoDir
val homePath = home.absolutePath
val project = jpsProject(homePath)
val generator = IconsClassGenerator(home, project.modules)
return protectStdErr {
project.modules.parallelStream()
.flatMap { generator.getIconsClassInfo(it).stream() }
.filter { it.images.isNotEmpty() }
.map { info ->
val icons = info.images.asSequence()
.filter { it.file != null && Icon(it.file!!.toFile()).isValid }
.map { it.sourceRoot.file }.toSet()
when {
icons.isEmpty() -> null
icons.size > 1 -> error("${info.className}: ${icons.joinToString()}")
else -> Mapping("idea", info.className, "idea/${icons.first().toRelativeString(home)}")
}
}.filter(Objects::nonNull).map { it!! }.toList()
}
}
private fun loadNonGeneratedIcons(context: Context, vararg skip: String): Collection<Mapping> {
val iconsRepo = context.iconsRepoDir
val toSkip = sequenceOf(*skip)
.map(iconsRepo::resolve)
.map(File::toString)
.toList()
val iconsRoots = mutableSetOf<File>()
Files.walkFileTree(iconsRepo.toPath(), object : SimpleFileVisitor<Path>() {
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes) =
if (toSkip.contains(dir.toString()) || dir.fileName.toString() == ".git") {
FileVisitResult.SKIP_SUBTREE
}
else super.preVisitDirectory(dir, attrs)
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (isImage(file)) iconsRoots.add(file.parent.toFile())
return FileVisitResult.CONTINUE
}
})
return iconsRoots.groupBy { product(iconsRepo, it) }.flatMap { entry ->
val (product, roots) = entry
val rootSet = "${product.capitalize()}Icons"
if (roots.size == 1) {
val path = roots.single().toRelativeString(iconsRepo)
return@flatMap listOf(Mapping(product, rootSet, path))
}
roots.map { root ->
val path = root.toRelativeString(iconsRepo)
val set = set(root, roots, iconsRepo, product)
.takeIf(String::isNotBlank)
?.let { "$rootSet.$it" }
Mapping(product, set ?: rootSet, path)
}.distinct()
}
}
private fun product(iconsRepo: File, iconsDir: File): String = when {
iconsRepo == iconsDir.parentFile -> iconsDir.name
iconsDir.parentFile != null -> product(iconsRepo, iconsDir.parentFile)
else -> error("Unable to determine product name for $iconsDir")
}
private val delimiters = arrayOf("/", ".", "-", "_")
private val exclusions = setOf("icons", "images",
"source", "src", "main", "resources",
"org", "jetbrains", "plugins")
private fun set(root: File, roots: Collection<File>, iconsRepo: File, product: String): String {
val ancestors = roots.filter { it.isAncestorOf(root) }
val parts = root.toRelativeString(iconsRepo)
.splitToSequence(*delimiters)
.filter(String::isNotBlank)
.filter { it.toLowerCase() != product }
.filter { !exclusions.contains(it.toLowerCase()) }
.toMutableList()
ancestors.forEach { parts -= it.toRelativeString(iconsRepo).split(*delimiters) }
val parentPrefix = parent(root, roots, iconsRepo)
?.let { set(it, roots, iconsRepo, product) }
?.takeIf(String::isNotBlank)
?.let { "$it." } ?: ""
return parentPrefix + parts.asSequence()
.distinct().filter(String::isNotBlank)
.joinToString(separator = ".", transform = String::capitalize)
}
private fun parent(root: File?, roots: Collection<File>, iconsRepo: File): File? =
if (root != null && root != iconsRepo) roots.firstOrNull {
it == root.parentFile
} ?: parent(root.parentFile, roots, iconsRepo)
else null
|
apache-2.0
|
dfd496c00f8861573e83f8a39e3acbaf
| 37.438889 | 140 | 0.638913 | 4.086237 | false | false | false | false |
bitsydarel/DBWeather
|
dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/ConstantHolder.kt
|
1
|
1371
|
/*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweatherdata
/**
* Created by darel on 15.09.17.
*
* Constant Holder class
*/
internal const val TAG = "dbweather"
internal const val WEATHER_TABLE = "weather"
internal const val ARTICLES_TABLE = "articles"
internal const val NEWSPAPERS_TABLE = "newspapers"
internal const val YOUTUBE_LIVE_TABLE = "youtube_live"
internal const val IPTV_LIVE_TABLE = "iptv_live"
internal const val IPTV_PLAYLIST_TABLE = "iptv_playlist"
internal const val FAVORITE_LIVE_TABLE = "favorite_live"
internal const val YOUTUBE_LIVES_FIREBASE_REFERENCE = "live_source"
internal const val IPTV_LIVES_FIREBASE_REFERENCE = "iptv_files"
internal const val NETWORK_CACHE_NAME = "network_network_cache"
internal const val DEFAULT_NETWORK_CACHE_SIZE: Long = 100 * 1024 * 1024
|
gpl-3.0
|
f40eb3d1212e5cea1afee312414003b8
| 39.352941 | 76 | 0.753465 | 3.685484 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/classes/kt343.kt
|
2
|
380
|
fun launch(f : () -> Unit) {
f()
}
fun box(): String {
val list = ArrayList<Int>()
val foo : () -> Unit = {
list.add(2) //first exception
}
foo()
launch({
list.add(3)
})
val bar = {
val x = 1 //second exception
}
bar()
return if (list.size == 2 && list.get(0) == 2 && list.get(1) == 3) "OK" else "fail"
}
|
apache-2.0
|
a26c002d424bac227e76284f9a3737a7
| 16.272727 | 87 | 0.444737 | 3.064516 | false | false | false | false |
Nunnery/MythicDrops
|
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/spawning/ItemSpawningListener.kt
|
1
|
8190
|
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2020 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.spawning
import com.tealcube.minecraft.bukkit.mythicdrops.api.MythicDrops
import com.tealcube.minecraft.bukkit.mythicdrops.api.names.NameType
import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.Tier
import com.tealcube.minecraft.bukkit.mythicdrops.events.EntityNameEvent
import com.tealcube.minecraft.bukkit.mythicdrops.events.EntitySpawningEvent
import com.tealcube.minecraft.bukkit.mythicdrops.items.MythicDropTracker
import com.tealcube.minecraft.bukkit.mythicdrops.names.NameMap
import com.tealcube.minecraft.bukkit.mythicdrops.utils.CreatureSpawnEventUtil
import com.tealcube.minecraft.bukkit.mythicdrops.utils.EquipmentUtils
import com.tealcube.minecraft.bukkit.mythicdrops.worldguard.WorldGuardFlags
import com.tealcube.minecraft.spigot.worldguard.adapters.lib.WorldGuardAdapters
import io.pixeloutlaw.minecraft.spigot.mythicdrops.getTier
import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.entity.EntityType
import org.bukkit.entity.LivingEntity
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.entity.CreatureSpawnEvent
import org.bukkit.inventory.ItemStack
class ItemSpawningListener(private val mythicDrops: MythicDrops) : Listener {
companion object {
private const val WORLD_MAX_HEIGHT = 255
}
@EventHandler(priority = EventPriority.LOWEST)
fun onCreatureSpawnEventLowest(creatureSpawnEvent: CreatureSpawnEvent) {
if (shouldNotHandleSpawnEvent(creatureSpawnEvent)) return
if (mythicDrops.settingsManager.configSettings.options.isGiveAllMobsNames) {
giveLivingEntityName(creatureSpawnEvent.entity)
}
// handle blank mob spawn
if (mythicDrops.settingsManager.configSettings.options.blankMobSpawn.isEnabled) {
creatureSpawnEvent.entity.equipment?.let {
it.clear()
if (
creatureSpawnEvent.entityType == EntityType.SKELETON &&
!mythicDrops.settingsManager.configSettings.options.blankMobSpawn.isSkeletonsSpawnWithoutBow
) {
it.setItemInMainHand(ItemStack(Material.BOW))
}
}
}
// turn on or off can pick up items per mob
creatureSpawnEvent.entity.canPickupItems =
mythicDrops.settingsManager.configSettings.options.isCanMobsPickUpEquipment
}
@EventHandler(priority = EventPriority.LOW)
fun onCreatureSpawnEventLow(creatureSpawnEvent: CreatureSpawnEvent) {
if (shouldNotHandleSpawnEvent(creatureSpawnEvent)) return
val disableLegacyItemCheck = mythicDrops.settingsManager.configSettings.options.isDisableLegacyItemChecks
val dropStrategy =
mythicDrops.dropStrategyManager.getById(mythicDrops.settingsManager.configSettings.drops.strategy)
?: return
MythicDropTracker.spawn()
val drops = dropStrategy.getDropsForCreatureSpawnEvent(creatureSpawnEvent)
val tiers = drops.mapNotNull { it.first.getTier(mythicDrops.tierManager, disableLegacyItemCheck) }
val ese = EntitySpawningEvent(creatureSpawnEvent.entity)
Bukkit.getPluginManager().callEvent(ese)
drops.forEach {
val itemStack = it.first
val dropChance = it.second
EquipmentUtils.equipEntity(creatureSpawnEvent.entity, itemStack, dropChance)
}
val rarestTier = tiers.minByOrNull { it.weight }
if (drops.isNotEmpty()) {
giveLivingEntityName(creatureSpawnEvent.entity, rarestTier)
}
}
private fun giveLivingEntityName(livingEntity: LivingEntity, tier: Tier? = null) {
// due to the order of checks, we may end up in here without checking if mobs can be given names,
// so check if they even can be given names.
if (!mythicDrops.settingsManager.configSettings.options.isGiveMobsNames) return
val generalName = NameMap
.getRandom(NameType.GENERAL_MOB_NAME, "")
val specificName = NameMap
.getRandom(
NameType.SPECIFIC_MOB_NAME,
"." + livingEntity.type.name.toLowerCase()
)
val name = if (!specificName.isNullOrBlank()) {
specificName
} else {
generalName
}
val displayColor =
if (tier != null &&
mythicDrops
.settingsManager
.configSettings
.options
.isGiveMobsColoredNames
) {
tier.displayColor
} else {
ChatColor.WHITE
}
val event = EntityNameEvent(livingEntity, displayColor.toString() + name)
Bukkit.getPluginManager().callEvent(event)
if (event.isCancelled) {
return
}
livingEntity.customName = event.name
livingEntity.isCustomNameVisible = true
}
// returns true if we should NOT spawn based on event spawn reason criteria
private fun isShouldNotSpawnBasedOnSpawnReason(event: CreatureSpawnEvent): Boolean {
val spawnPrevention = mythicDrops.settingsManager.creatureSpawningSettings.spawnPrevention
return when {
event.spawnReason == CreatureSpawnEvent.SpawnReason.DROWNED && spawnPrevention.isDrowned -> true
event.spawnReason == CreatureSpawnEvent.SpawnReason.REINFORCEMENTS &&
spawnPrevention.isReinforcements -> true
event.spawnReason == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && spawnPrevention.isSpawnEgg -> true
event.spawnReason == CreatureSpawnEvent.SpawnReason.SPAWNER && spawnPrevention.isSpawner -> true
mythicDrops
.settingsManager
.creatureSpawningSettings
.spawnPrevention
.aboveY[event.entity.world.name] ?: WORLD_MAX_HEIGHT
<= event.entity.location.y -> true
else -> false
}
}
// returns true if we should NOT spawn based on event criteria
private fun shouldNotHandleSpawnEvent(event: CreatureSpawnEvent): Boolean {
return when {
CreatureSpawnEventUtil.shouldCancelDropsBasedOnCreatureSpawnEvent(event) -> true
!mythicDrops
.settingsManager
.configSettings
.multiworld
.enabledWorlds
.contains(event.entity.world.name) -> {
true
}
isShouldNotSpawnBasedOnSpawnReason(event) -> true
!mythicDrops
.settingsManager
.configSettings
.options
.isDisplayMobEquipment -> true
WorldGuardAdapters.isFlagDenyAtLocation(event.location, WorldGuardFlags.mythicDrops) -> true
else -> false
}
}
}
|
mit
|
e0ef001f2982ebe92784eddbc0cb0749
| 42.333333 | 113 | 0.686203 | 4.883721 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.