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
Shashi-Bhushan/General
cp-trials/src/main/kotlin/in/shabhushan/cp_trials/ProdSum.kt
1
1074
package `in`.shabhushan.cp_trials import kotlin.math.abs object ProdSum { fun prod2Sum(a:Long, b:Long, c:Long, d:Long):List<LongArray> = mutableListOf<LongArray>().apply { val ad = a * d val bc = b * c val ac = a * c val bd = b * d val firstArray = longArrayOf(ac + bd, abs(bc - ad)).sortedArray() val secondArray = longArrayOf(ad + bc, abs(bd - ac)).sortedArray() this.add(firstArray) if(firstArray[0] != secondArray[0] && firstArray[1] != secondArray[1]) { this.add(secondArray) } }.sortedBy { it.first() }.apply { println("Arrya is ${this[0]}") } fun prod2Sum2(a:Long, b:Long, c:Long, d:Long):List<LongArray> = mutableListOf<LongArray>().apply { val ad = a * d val bc = b * c val ac = a * c val bd = b * d add(longArrayOf(ac + bd, abs(bc - ad)).sortedArray()) add(longArrayOf(ad + bc, abs(bd - ac)).sortedArray()) }.sortedBy { it.first() }.distinctBy { it.first() } }
gpl-2.0
6dca9576ce5e905eebe4bdae2728de23
26.538462
102
0.537244
3.43131
false
false
false
false
Kotlin/dokka
plugins/base/base-test-utils/src/main/kotlin/renderers/JsoupUtils.kt
1
3166
package utils import org.jsoup.nodes.Element import org.jsoup.nodes.Node import org.jsoup.nodes.TextNode fun Element.match(vararg matchers: Any, ignoreSpanWithTokenStyle:Boolean = false): Unit = childNodes() .let { list -> if(ignoreSpanWithTokenStyle) { list .filterNot { it is Element && it.tagName() == "span" && it.attr("class").startsWith("token ") && it.childNodeSize() == 0} .map { if(it is Element && it.tagName() == "span" && it.attr("class").startsWith("token ") && it.childNodeSize() == 1) it.childNode(0) else it } .uniteConsecutiveTextNodes() } else list } .filter { (it !is TextNode || it.text().isNotBlank())} .let { it.drop(it.size - matchers.size) } .zip(matchers) .forEach { (n, m) -> m.accepts(n, ignoreSpan = ignoreSpanWithTokenStyle) } open class Tag(val name: String, vararg val matchers: Any, val expectedClasses: List<String> = emptyList()) class Div(vararg matchers: Any) : Tag("div", *matchers) class P(vararg matchers: Any) : Tag("p", *matchers) class Span(vararg matchers: Any) : Tag("span", *matchers) class A(vararg matchers: Any) : Tag("a", *matchers) class B(vararg matchers: Any) : Tag("b", *matchers) class I(vararg matchers: Any) : Tag("i", *matchers) class STRIKE(vararg matchers: Any) : Tag("strike", *matchers) class BlockQuote(vararg matchers: Any) : Tag("blockquote", *matchers) class Dl(vararg matchers: Any) : Tag("dl", *matchers) class Dt(vararg matchers: Any) : Tag("dt", *matchers) class Dd(vararg matchers: Any) : Tag("dd", *matchers) class Var(vararg matchers: Any) : Tag("var", *matchers) class U(vararg matchers: Any) : Tag("u", *matchers) object Wbr : Tag("wbr") object Br : Tag("br") fun Tag.withClasses(vararg classes: String) = Tag(name, *matchers, expectedClasses = classes.toList()) private fun Any.accepts(n: Node, ignoreSpan:Boolean = true) { when (this) { is String -> assert(n is TextNode && n.text().trim() == this.trim()) { "\"$this\" expected but found: $n" } is Tag -> { check(n is Element) { "Expected node to be Element: $n" } assert(n.tagName() == name) { "Tag \"$name\" expected but found: \"$n\"" } expectedClasses.forEach { assert(n.hasClass(it)) { "Expected to find class \"$it\" for tag \"$name\", found: ${n.classNames()}" } } if (matchers.isNotEmpty()) n.match(*matchers, ignoreSpanWithTokenStyle = ignoreSpan) } else -> throw IllegalArgumentException("$this is not proper matcher") } } private fun List<Node>.uniteConsecutiveTextNodes(): MutableList<Node> { val resList = mutableListOf<Node>() var acc = StringBuilder() forEachIndexed { index, item -> if (item is TextNode) { acc.append(item.text()) if (!(index + 1 < size && this[index + 1] is TextNode)) { resList.add(TextNode(acc.toString())) acc = StringBuilder() } } else resList.add(item) } return resList }
apache-2.0
8238e7ded0aac332e17b66609f16982a
42.972222
142
0.600126
3.787081
false
false
false
false
lgou2w/MoonLakeLauncher
src/main/kotlin/com/minecraft/moonlake/launcher/util/MuiDepthUtils.kt
1
2927
/* * Copyright (C) 2017 The MoonLake Authors * * 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.minecraft.moonlake.launcher.util import com.minecraft.moonlake.launcher.layout.MuiPane import javafx.scene.Node import javafx.scene.effect.BlurType import javafx.scene.effect.DropShadow import javafx.scene.paint.Color object MuiDepthUtils { /************************************************************************** * * Private Implements * **************************************************************************/ private val depth: Array<DropShadow> = arrayOf( DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, .0), .0, .0, .0, .0), DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, .26), 10.0, .12, -1.0, 2.0), DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, .26), 12.5, .16, .0, 3.0), DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, .26), 15.0, .16, .0, 4.0), DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, .26), 17.5, .16, .0, 5.0), DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, .26), 20.0, .19, .0, 6.0), DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, .26), 22.5, .19, .0, 7.0), DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, .26), 25.0, .25, .0, 8.0), DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, .26), 27.5, .25, .0, 9.0), DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, .26), 30.0, .30, .0, 10.0)) private fun safeLevel(level: Int): Int = if(level < 0) 0 else if(level >= depth.size) depth.size - 1 else level /************************************************************************** * * Public API * **************************************************************************/ @JvmStatic fun getShadowAt(level: Int): DropShadow = depth[safeLevel(level)] @JvmStatic fun setNodeDepth(node: Node, level: Int) { val depth = depth[safeLevel(level)] node.effect = DropShadow(BlurType.GAUSSIAN, depth.color, depth.radius, depth.spread, depth.offsetX, depth.offsetY) } @JvmStatic fun createNodeDepth(node: Node, level: Int): Node { val container = MuiPane(node) setNodeDepth(container, level) return container } }
gpl-3.0
1402206c072afa62341bd23129857a01
40.225352
122
0.571575
3.654182
false
false
false
false
SimpleTimeTracking/StandaloneClient
src/main/kotlin/org/stt/persistence/stt/STTItemConverter.kt
1
4799
package org.stt.persistence.stt import org.stt.model.TimeTrackingItem import java.time.LocalDateTime internal class STTItemConverter { fun lineToTimeTrackingItem(line: String): TimeTrackingItem { val start = parseDate(line.substring(0, 19))!! val end = if (line.length >= 39) parseDate(line.substring(20, 39)) else null val activityStart = if (end == null) 20 else 40 val activity = if (line.length > activityStart) unescape(line.substring(activityStart)) else "" return TimeTrackingItem(activity, start, end) } private fun unescape(activity: String): String { val chars = activity.toCharArray() val n = chars.size val b = StringBuilder() var i = 0 while (i < n) { val next = chars[i] if (next == '\\' && i + 1 < n) { i++ if (chars[i] == 'n') { b.append('\n') } else { b.append(chars[i]) } } else { b.append(next) } i++ } return b.toString() } private fun parseDate(from: String): LocalDateTime? { val chars = from.toCharArray() if (chars[0] < '0' || chars[0] > '9' || chars[1] < '0' || chars[1] > '9' || chars[2] < '0' || chars[2] > '9' || chars[3] < '0' || chars[3] > '9' || chars[4] != '-' || chars[5] < '0' || chars[5] > '9' || chars[6] < '0' || chars[6] > '9' || chars[7] != '-' || chars[8] < '0' || chars[8] > '9' || chars[9] < '0' || chars[9] > '9' || chars[10] != '_' || chars[11] < '0' || chars[11] > '9' || chars[12] < '0' || chars[12] > '9' || chars[13] != ':' || chars[14] < '0' || chars[14] > '9' || chars[15] < '0' || chars[15] > '9' || chars[16] != ':' || chars[17] < '0' || chars[17] > '9' || chars[18] < '0' || chars[18] > '9') { return null } val y = (chars[0] - '0') * 1000 + (chars[1] - '0') * 100 + (chars[2] - '0') * 10 + (chars[3] - '0') val mo = (chars[5] - '0') * 10 + (chars[6] - '0') val d = (chars[8] - '0') * 10 + (chars[9] - '0') val h = (chars[11] - '0') * 10 + (chars[12] - '0') val mi = (chars[14] - '0') * 10 + (chars[15] - '0') val s = (chars[17] - '0') * 10 + (chars[18] - '0') return LocalDateTime.of(y, mo, d, h, mi, s) } fun timeTrackingItemToLine(item: TimeTrackingItem): String { val builder = StringBuilder(80) val start = item.start appendDateTime(builder, start) builder.append(' ') item.end?.let { endDateTime -> appendDateTime(builder, endDateTime) builder.append(' ') } escape(builder, item.activity) return builder.toString() } private fun escape(b: StringBuilder, activity: String) { val chars = activity.toCharArray() val n = chars.size var i = 0 while (i < n) { val next = chars[i] if (next == '\r') { b.append("\\n") if (i + 1 < n && chars[i + 1] == '\n') { i++ } } else if (next == '\n') { b.append("\\n") } else if (next == '\\') { b.append("\\\\") } else { b.append(next) } i++ } } private fun appendDateTime(b: StringBuilder, dt: LocalDateTime) { val y = dt.year val mo = dt.monthValue val d = dt.dayOfMonth val h = dt.hour val mi = dt.minute val s = dt.second b.append((y / 1000 % 10 + '0'.toInt()).toChar()) b.append((y / 100 % 10 + '0'.toInt()).toChar()) b.append((y / 10 % 10 + '0'.toInt()).toChar()) b.append((y % 10 + '0'.toInt()).toChar()) b.append('-') b.append((mo / 10 % 10 + '0'.toInt()).toChar()) b.append((mo % 10 + '0'.toInt()).toChar()) b.append('-') b.append((d / 10 % 10 + '0'.toInt()).toChar()) b.append((d % 10 + '0'.toInt()).toChar()) b.append('_') b.append((h / 10 % 10 + '0'.toInt()).toChar()) b.append((h % 10 + '0'.toInt()).toChar()) b.append(':') b.append((mi / 10 % 10 + '0'.toInt()).toChar()) b.append((mi % 10 + '0'.toInt()).toChar()) b.append(':') b.append((s / 10 % 10 + '0'.toInt()).toChar()) b.append((s % 10 + '0'.toInt()).toChar()) } }
gpl-3.0
83f06992d109af823ab9a7b60bef0db6
34.286765
107
0.421129
3.55745
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/common/views/TintedTextView.kt
1
1814
package com.garpr.android.features.common.views import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.appcompat.widget.AppCompatTextView import androidx.core.content.ContextCompat import androidx.palette.graphics.Palette import com.garpr.android.R import com.garpr.android.extensions.compoundDrawablesRelativeCompat import com.garpr.android.extensions.getAttrColor import com.garpr.android.extensions.setTintedDrawableColor import com.garpr.android.misc.ColorListener import com.garpr.android.misc.Refreshable class TintedTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : AppCompatTextView(context, attrs), ColorListener, Refreshable { @ColorInt private val drawableTintColor: Int init { @SuppressLint("CustomViewStyleable") val ta = context.obtainStyledAttributes(attrs, R.styleable.View) drawableTintColor = ta.getColor(R.styleable.View_drawableTintColor, context.getAttrColor(android.R.attr.textColorSecondary)) ta.recycle() } override fun onFinishInflate() { super.onFinishInflate() refresh() } override fun onPaletteBuilt(palette: Palette?) { setTintedDrawableColor(palette?.mutedSwatch?.rgb ?: drawableTintColor) } override fun refresh() { setTintedDrawableColor(drawableTintColor) } fun setStartCompoundDrawableRelativeWithIntrinsicBounds(@DrawableRes drawableResId: Int) { val drawables = compoundDrawablesRelativeCompat drawables[0] = ContextCompat.getDrawable(context, drawableResId) compoundDrawablesRelativeCompat = drawables refresh() } }
unlicense
dec0937bb98a974107f0ac113cd06931
31.981818
94
0.760198
5.024931
false
false
false
false
italoag/qksms
presentation/src/main/java/com/moez/QKSMS/feature/conversations/ConversationItemTouchCallback.kt
3
6627
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS 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. * * QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.feature.conversations import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import androidx.core.graphics.drawable.toBitmap import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.moez.QKSMS.R import com.moez.QKSMS.common.util.Colors import com.moez.QKSMS.common.util.extensions.dpToPx import com.moez.QKSMS.util.Preferences import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.Observables import io.reactivex.rxkotlin.plusAssign import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import javax.inject.Inject import kotlin.math.max import kotlin.math.min class ConversationItemTouchCallback @Inject constructor( colors: Colors, disposables: CompositeDisposable, prefs: Preferences, private val context: Context ) : ItemTouchHelper.SimpleCallback(0, 0) { val swipes: Subject<Pair<Long, Int>> = PublishSubject.create() /** * Setting the adapter allows us to animate back to the original position */ var adapter: RecyclerView.Adapter<*>? = null private val backgroundPaint = Paint() private var rightAction = 0 private var swipeRightIcon: Bitmap? = null private var leftAction = 0 private var swipeLeftIcon: Bitmap? = null private val iconLength = 24.dpToPx(context) init { disposables += colors.themeObservable() .doOnNext { theme -> backgroundPaint.color = theme.theme } .subscribeOn(Schedulers.io()) .subscribe() disposables += Observables .combineLatest(prefs.swipeRight.asObservable(), prefs.swipeLeft.asObservable(), colors.themeObservable() ) { right, left, theme -> rightAction = right swipeRightIcon = iconForAction(right, theme.textPrimary) leftAction = left swipeLeftIcon = iconForAction(left, theme.textPrimary) setDefaultSwipeDirs((if (right == Preferences.SWIPE_ACTION_NONE) 0 else ItemTouchHelper.RIGHT) or (if (left == Preferences.SWIPE_ACTION_NONE) 0 else ItemTouchHelper.LEFT)) } .subscribeOn(Schedulers.io()) .subscribe() } override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onChildDraw( c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { val itemView = viewHolder.itemView if (dX > 0) { c.drawRect(itemView.left.toFloat(), itemView.top.toFloat(), dX, itemView.bottom.toFloat(), backgroundPaint) swipeRightIcon?.let { icon -> val availablePx = dX.toInt() - iconLength if (availablePx > 0) { val src = Rect(0, 0, min(availablePx, icon.width), icon.height) val dstTop = itemView.top + (itemView.bottom - itemView.top - icon.height) / 2 val dst = Rect(iconLength, dstTop, iconLength + src.width(), dstTop + src.height()) c.drawBitmap(icon, src, dst, null) } } } else if (dX < 0) { c.drawRect(itemView.right.toFloat() + dX, itemView.top.toFloat(), itemView.right.toFloat(), itemView.bottom.toFloat(), backgroundPaint) swipeLeftIcon?.let { icon -> val availablePx = -dX.toInt() - iconLength if (availablePx > 0) { val src = Rect(max(0, icon.width - availablePx), 0, icon.width, icon.height) val dstTop = itemView.top + (itemView.bottom - itemView.top - icon.height) / 2 val dst = Rect(itemView.right - iconLength - src.width(), dstTop, itemView.right - iconLength, dstTop + src.height()) c.drawBitmap(icon, src, dst, null) } } } super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) } } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { swipes.onNext(Pair(viewHolder.itemId, direction)) // This will trigger the animation back to neutral state val action = if (direction == ItemTouchHelper.RIGHT) rightAction else leftAction if (action != Preferences.SWIPE_ACTION_ARCHIVE) { adapter?.notifyItemChanged(viewHolder.adapterPosition) } } private fun iconForAction(action: Int, tint: Int): Bitmap? { val res = when (action) { Preferences.SWIPE_ACTION_ARCHIVE -> R.drawable.ic_archive_white_24dp Preferences.SWIPE_ACTION_DELETE -> R.drawable.ic_delete_white_24dp Preferences.SWIPE_ACTION_BLOCK -> R.drawable.ic_block_white_24dp Preferences.SWIPE_ACTION_CALL -> R.drawable.ic_call_white_24dp Preferences.SWIPE_ACTION_READ -> R.drawable.ic_check_white_24dp Preferences.SWIPE_ACTION_UNREAD -> R.drawable.ic_markunread_black_24dp else -> null } return res?.let(context.resources::getDrawable) ?.apply { setTint(tint) } ?.toBitmap(iconLength, iconLength) } }
gpl-3.0
0fd24f041c8e80bb651b148bd6dd91b3
39.414634
120
0.628791
4.644008
false
false
false
false
backpaper0/syobotsum
core/src/syobotsum/actor/ReadyImage.kt
1
770
package syobotsum.actor import com.badlogic.gdx.scenes.scene2d.Action import com.badlogic.gdx.scenes.scene2d.actions.Actions import com.badlogic.gdx.scenes.scene2d.ui.Image import com.badlogic.gdx.scenes.scene2d.ui.Skin class ReadyImage(skin: Skin, styleName: String) : Image(skin, styleName) { var callback: Runnable? = null fun start() { val scale = 0.8f val duration = 1f val scaleTo = Actions.scaleTo(scale, scale, duration) val moveBy = Actions.moveBy((width - (width * scale)) / 2f, (height - (height * scale)) / 2f, duration) val invisible = Actions.visible(false) val run = callback.let { Actions.run(it) } addAction(Actions.sequence(Actions.parallel(scaleTo, moveBy), invisible, run)) } }
apache-2.0
9923e292c9f5cf9aad4aa9f2bec5f363
35.666667
111
0.687013
3.53211
false
false
false
false
infinum/android_dbinspector
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/shared/listeners/FabExtendingOnScrollListener.kt
1
959
package com.infinum.dbinspector.ui.shared.listeners import androidx.recyclerview.widget.RecyclerView import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton internal class FabExtendingOnScrollListener( private val floatingActionButton: ExtendedFloatingActionButton ) : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { if (newState == RecyclerView.SCROLL_STATE_IDLE && !floatingActionButton.isExtended && recyclerView.computeVerticalScrollOffset() == 0 ) { floatingActionButton.extend() } super.onScrollStateChanged(recyclerView, newState) } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dy != 0 && floatingActionButton.isExtended) { floatingActionButton.shrink() } super.onScrolled(recyclerView, dx, dy) } }
apache-2.0
2bfcd82f7639e7cbdff221b8315dd3b7
35.884615
84
0.714286
5.448864
false
false
false
false
prfarlow1/nytc-meet
app/src/main/kotlin/org/needhamtrack/nytc/Constants.kt
1
1000
package org.needhamtrack.nytc object Constants { const val SPREADSHEET_ID = "1Kod_mU3V22LXtwvjBSY8mcU1vMZDdMh9b3tCj6exKzY" const val TIMESTAMP_COLUMN = "C" const val RUNNER_NUMBER_COLUMN = "D" const val COMPETITOR_NAME_COLUMN = "E" const val CLUB_COLUMN = "F" const val MARK1_COLUMN = "I" const val MARK3_COLUMN = "K" const val ROW_OFFSET = 2 const val EVENT_DATA_START_CELL = "D2" const val EVENT_DATA_END_CELL = "K100" const val FOUL = "FOUL" const val NO_MARK = "NO MARK" const val ERROR = "error" const val UNATTACHED = "unattached" const val CM_PER_INCH = 2.54 val MARK_MAP = mapOf(1 to "I", 2 to "J", 3 to "K", 4 to "L", 5 to "M", 6 to "N", 7 to "O", 8 to "P", 9 to "Q", 10 to "R", 11 to "S", 12 to "T", 13 to "U", 14 to "V", 15 to "W", 16 to "X") }
mit
1cb7d305d18714c921711626ea93a864
27.6
77
0.506
3.125
false
false
false
false
infinum/android_dbinspector
dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/pragma/usecases/GetTableInfoUseCaseTest.kt
1
1676
package com.infinum.dbinspector.domain.pragma.usecases import com.infinum.dbinspector.domain.Repositories import com.infinum.dbinspector.domain.shared.models.parameters.PragmaParameters import com.infinum.dbinspector.shared.BaseTest import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.koin.core.module.Module import org.koin.dsl.module import org.koin.test.get @DisplayName("GetTableInfoUseCase tests") internal class GetTableInfoUseCaseTest : BaseTest() { override fun modules(): List<Module> = listOf( module { factory { mockk<Repositories.Connection>() } factory { mockk<Repositories.Pragma>() } } ) @Test fun `Invoking use case invokes connection open and pragma table info`() { val given = PragmaParameters.Pragma( databasePath = "test.db", statement = "my_statement" ) val connectionRepository: Repositories.Connection = get() val pragmaRepository: Repositories.Pragma = get() val useCase = GetTableInfoUseCase(connectionRepository, pragmaRepository) coEvery { connectionRepository.open(any()) } returns mockk() coEvery { pragmaRepository.getTableInfo(any()) } returns mockk { every { cells } returns listOf() every { copy(null, 0, 0, listOf()) } returns this } test { useCase.invoke(given) } coVerify(exactly = 1) { connectionRepository.open(any()) } coVerify(exactly = 1) { pragmaRepository.getTableInfo(any()) } } }
apache-2.0
49fc1d6600c81307363bb7fba577672c
32.52
81
0.682578
4.422164
false
true
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/libanki/sync/BackendSync.kt
1
2198
/*************************************************************************************** * Copyright (c) 2022 Ankitects Pty Ltd <http://apps.ankiweb.net> * * * * 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.sync import anki.sync.SyncAuth import anki.sync.SyncCollectionResponse import anki.sync.SyncStatusResponse import com.ichi2.libanki.CollectionV16 fun CollectionV16.syncLogin(username: String, password: String): SyncAuth { return backend.syncLogin(username = username, password = password) } fun CollectionV16.syncCollection(auth: SyncAuth): SyncCollectionResponse { return backend.syncCollection(input = auth) } fun CollectionV16.fullUpload(auth: SyncAuth) { return backend.fullUpload(input = auth) } fun CollectionV16.fullDownload(auth: SyncAuth) { return backend.fullDownload(input = auth) } fun CollectionV16.syncMedia(auth: SyncAuth) { return backend.syncMedia(input = auth) } fun CollectionV16.syncStatus(auth: SyncAuth): SyncStatusResponse { return backend.syncStatus(input = auth) }
gpl-3.0
9da3a5a29fb6fd90a39276213a0a5958
46.782609
90
0.545041
5.111628
false
false
false
false
tschuchortdev/kotlin-compile-testing
core/src/test/kotlin/com/tschuchort/compiletesting/TestUtils.kt
1
1393
package com.tschuchort.compiletesting import io.github.classgraph.ClassGraph import org.assertj.core.api.Assertions import java.io.File fun defaultCompilerConfig(): KotlinCompilation { return KotlinCompilation( ).apply { inheritClassPath = false correctErrorTypes = true verbose = true reportOutputFiles = false messageOutputStream = System.out } } fun defaultJsCompilerConfig(): KotlinJsCompilation { return KotlinJsCompilation( ).apply { inheritClassPath = false verbose = true reportOutputFiles = false messageOutputStream = System.out } } fun assertClassLoadable(compileResult: KotlinCompilation.Result, className: String): Class<*> { try { val clazz = compileResult.classLoader.loadClass(className) Assertions.assertThat(clazz).isNotNull return clazz } catch(e: ClassNotFoundException) { return Assertions.fail<Nothing>("Class $className could not be loaded") } } /** * Returns the classpath for a dependency (format $name-$version). * This is necessary to know the actual location of a dependency * which has been included in test runtime (build.gradle). */ fun classpathOf(dependency: String): File { val regex = Regex(".*$dependency\\.jar") return ClassGraph().classpathFiles.first { classpath -> classpath.name.matches(regex) } }
mpl-2.0
ef924299ac960531ab0ef531eedf2ae0
29.282609
95
0.704235
4.770548
false
false
false
false
wcaokaze/cac2er
src/main/kotlin/com/wcaokaze/cac2er/CacheImpl.kt
1
2303
package com.wcaokaze.cac2er import com.wcaokaze.io.CacheInputStream import com.wcaokaze.io.CacheOutputStream import java.io.* internal val Cache<*>.uniformizer: CacheUniformizer get() = (this as CacheImpl<*>).uniformizer internal class CacheImpl<T> (@Transient var uniformizer: CacheUniformizer) : WritableCache<T>, Serializable { override val file get() = uniformizer.file override val circulationRecord get() = uniformizer.circulationRecord override var content: T get() { @Suppress("UNCHECKED_CAST") return uniformizer.content as T } set(value) { uniformizer.content = value } override fun addObserver(observer: (T) -> Unit) { @Suppress("UNCHECKED_CAST") uniformizer.observers += observer as (Any?) -> Unit } override fun removeObserver(observer: (T) -> Unit) { @Suppress("UNCHECKED_CAST") uniformizer.observers -= observer as (Any?) -> Unit } override fun equals(other: Any?): Boolean { if (other !is CacheImpl<*>) return false return this.file == other.file } override fun hashCode() = file.hashCode() private fun writeObject(stream: ObjectOutputStream) { stream.defaultWriteObject() if (stream !is CacheOutputStream) { // Caches only can saved by Cac2er throw NotSerializableException("com.wcaokaze.cac2er.CacheImpl") } /* * NOTE: `writeObject` runs while the content of another Cache is serialized, * so this function writes into the file of a "parent" cache. All this * function have to do is to write the file path so that the "parent" * cache can find the file of "this" cache. */ val relativePath = file.relativeSibling(stream.uniformizer.file) stream.writeUTF(relativePath.path) stream.dependence += relativePath } private fun readObject(stream: ObjectInputStream) { stream.defaultReadObject() if (stream !is CacheInputStream) { // Caches only can loaded by Cac2er throw NotActiveException() } val relativePath = stream.readUTF() val file = stream.parentFile.resolve(relativePath) val (content, circulationRecord) = Cacher.load(file) uniformizer = CacheUniformizer.Pool.setContent(file, content) uniformizer.circulationRecord += circulationRecord } }
mit
1c777bfada89d64db4f8a28ca2e575ca
28.525641
81
0.693443
4.217949
false
false
false
false
dafi/commonutils
app/src/main/java/com/ternaryop/utils/io/IOUtils.kt
1
1813
package com.ternaryop.utils.io import java.io.File import java.io.FileNotFoundException import java.io.IOException import java.util.regex.Pattern private const val BUFFER_SIZE = 100 * 1024 @Throws(IOException::class) fun File.moveTo(targetFile: File) { if (!exists()) { throw FileNotFoundException("Source '$this' does not exist") } if (isDirectory) { throw IOException("Source '$this' is a directory") } if (targetFile.exists()) { throw IOException("Destination '$targetFile' already exists") } if (targetFile.isDirectory) { throw IOException("Destination '$targetFile' is a directory") } if (!renameTo(targetFile)) { copyTo(targetFile, true, BUFFER_SIZE) if (!delete()) { targetFile.delete() throw IOException("Failed to delete original file '$this' after copy to '$targetFile'") } } } fun File.generateUniqueFileName(): File { var file = this val parentFile = file.parentFile var nameWithExt = file.name val patternCount = Pattern.compile("""(.*) \((\d+)\)""") while (file.exists()) { var name: String val ext: String val extPos = nameWithExt.lastIndexOf('.') if (extPos < 0) { name = nameWithExt ext = "" } else { name = nameWithExt.substring(0, extPos) // contains dot ext = nameWithExt.substring(extPos) } val matcherCount = patternCount.matcher(name) var count = 1 if (matcherCount.matches()) { name = matcherCount.group(1)!! count = Integer.parseInt(matcherCount.group(2)!!) + 1 } nameWithExt = "$name ($count)$ext" file = File(parentFile, nameWithExt) } return file }
mit
75facde8a25dccc75d3ba7f4c54a4e36
27.328125
99
0.595698
4.337321
false
false
false
false
andersonlucasg3/SpriteKit-Android
SpriteKitLib/src/main/java/br/com/insanitech/spritekit/actions/SKActionFadeOut.kt
1
1215
package br.com.insanitech.spritekit.actions import br.com.insanitech.spritekit.SKEaseCalculations import br.com.insanitech.spritekit.SKNode /** * Created by anderson on 06/01/17. */ internal class SKActionFadeOut : SKAction() { private var startAlpha: Float = 0.toFloat() override fun computeStart(node: SKNode) { this.startAlpha = node.alpha } override fun computeAction(node: SKNode, elapsed: Long) { when (this.timingMode) { SKActionTimingMode.Linear -> node.alpha = SKEaseCalculations.linear(elapsed.toFloat(), this.startAlpha, -this.startAlpha, this.duration.toFloat()) SKActionTimingMode.EaseIn -> node.alpha = SKEaseCalculations.easeIn(elapsed.toFloat(), this.startAlpha, -this.startAlpha, this.duration.toFloat()) SKActionTimingMode.EaseOut -> node.alpha = SKEaseCalculations.easeOut(elapsed.toFloat(), this.startAlpha, -this.startAlpha, this.duration.toFloat()) SKActionTimingMode.EaseInEaseOut -> node.alpha = SKEaseCalculations.easeInOut(elapsed.toFloat(), this.startAlpha, -this.startAlpha, this.duration.toFloat()) } } override fun computeFinish(node: SKNode) { node.alpha = 0.0f } }
bsd-3-clause
2bff2f181d3851402554f8fc22c9fa2e
38.193548
168
0.711934
4.090909
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/CreateCertificate.kt
1
7198
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers import com.google.cloud.spanner.ErrorCode as SpannerErrorCode import com.google.cloud.spanner.Mutation import com.google.cloud.spanner.SpannerException import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.common.identity.InternalId import org.wfanet.measurement.gcloud.common.toGcloudByteArray import org.wfanet.measurement.gcloud.common.toGcloudTimestamp import org.wfanet.measurement.gcloud.spanner.AsyncDatabaseClient import org.wfanet.measurement.gcloud.spanner.bufferTo import org.wfanet.measurement.gcloud.spanner.insertMutation import org.wfanet.measurement.gcloud.spanner.set import org.wfanet.measurement.gcloud.spanner.setJson import org.wfanet.measurement.internal.kingdom.Certificate import org.wfanet.measurement.kingdom.deploy.common.DuchyIds import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.CertSubjectKeyIdAlreadyExistsException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DataProviderNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.KingdomInternalException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.MeasurementConsumerNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.ModelProviderNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.DataProviderReader import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.MeasurementConsumerReader import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.ModelProviderReader /** * Creates a certificate in the database. * * Throws a subclass of [KingdomInternalException] on [execute]. * @throws [CertSubjectKeyIdAlreadyExistsException] subjectKeyIdentifier of [Certificate] collides * with a certificate already in the database * @throws [DataProviderNotFoundException] DataProvider not found * @throws [MeasurementConsumerNotFoundException] MeasurementConsumer not found * @throws [DuchyNotFoundException] Duchy not found */ class CreateCertificate(private val certificate: Certificate) : SpannerWriter<Certificate, Certificate>() { @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null. private val ownerTableName: String = when (certificate.parentCase) { Certificate.ParentCase.EXTERNAL_DATA_PROVIDER_ID -> "DataProvider" Certificate.ParentCase.EXTERNAL_MEASUREMENT_CONSUMER_ID -> "MeasurementConsumer" Certificate.ParentCase.EXTERNAL_DUCHY_ID -> "Duchy" Certificate.ParentCase.EXTERNAL_MODEL_PROVIDER_ID -> "ModelProvider" Certificate.ParentCase.PARENT_NOT_SET -> throw IllegalArgumentException("Parent field of Certificate is not set") } override suspend fun TransactionScope.runTransaction(): Certificate { val certificateId = idGenerator.generateInternalId() val externalMapId = idGenerator.generateExternalId() certificate.toInsertMutation(certificateId).bufferTo(transactionContext) createCertificateMapTableMutation( getOwnerInternalId(transactionContext), certificateId.value, externalMapId.value ) .bufferTo(transactionContext) return certificate.toBuilder().setExternalCertificateId(externalMapId.value).build() } override fun ResultScope<Certificate>.buildResult(): Certificate { return checkNotNull(transactionResult) } private suspend fun getOwnerInternalId( transactionContext: AsyncDatabaseClient.TransactionContext ): Long { // TODO: change all of the reads below to use index lookups or simple queries. @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null. return when (certificate.parentCase) { Certificate.ParentCase.EXTERNAL_DATA_PROVIDER_ID -> { val externalDataProviderId = ExternalId(certificate.externalDataProviderId) DataProviderReader() .readByExternalDataProviderId(transactionContext, externalDataProviderId) ?.dataProviderId ?: throw DataProviderNotFoundException(externalDataProviderId) } Certificate.ParentCase.EXTERNAL_MEASUREMENT_CONSUMER_ID -> { val externalMeasurementConsumerId = ExternalId(certificate.externalMeasurementConsumerId) MeasurementConsumerReader() .readByExternalMeasurementConsumerId(transactionContext, externalMeasurementConsumerId) ?.measurementConsumerId ?: throw MeasurementConsumerNotFoundException(externalMeasurementConsumerId) } Certificate.ParentCase.EXTERNAL_DUCHY_ID -> DuchyIds.getInternalId(certificate.externalDuchyId) ?: throw DuchyNotFoundException(certificate.externalDuchyId) Certificate.ParentCase.EXTERNAL_MODEL_PROVIDER_ID -> { val externalModelProviderId = ExternalId(certificate.externalModelProviderId) ModelProviderReader() .readByExternalModelProviderId(transactionContext, externalModelProviderId) ?.modelProviderId ?: throw ModelProviderNotFoundException(externalModelProviderId) } Certificate.ParentCase.PARENT_NOT_SET -> throw IllegalArgumentException("Parent field of Certificate is not set") } } private fun createCertificateMapTableMutation( internalOwnerId: Long, internalCertificateId: Long, externalMapId: Long ): Mutation { val tableName = "${ownerTableName}Certificates" val internalIdField = "${ownerTableName}Id" val externalIdField = "External${ownerTableName}CertificateId" return insertMutation(tableName) { set(internalIdField to internalOwnerId) set("CertificateId" to internalCertificateId) set(externalIdField to externalMapId) } } override suspend fun handleSpannerException(e: SpannerException): Certificate? { when (e.errorCode) { SpannerErrorCode.ALREADY_EXISTS -> throw CertSubjectKeyIdAlreadyExistsException() else -> throw e } } } fun Certificate.toInsertMutation(internalId: InternalId): Mutation { return insertMutation("Certificates") { set("CertificateId" to internalId) set("SubjectKeyIdentifier" to subjectKeyIdentifier.toGcloudByteArray()) set("NotValidBefore" to notValidBefore.toGcloudTimestamp()) set("NotValidAfter" to notValidAfter.toGcloudTimestamp()) set("RevocationState" to revocationState) set("CertificateDetails" to details) setJson("CertificateDetailsJson" to details) } }
apache-2.0
a6f1e54c5218e6acf7ca1e2853a4b1a6
46.986667
105
0.783273
4.873392
false
false
false
false
acidbluebriggs/graphql-java-tools
src/main/kotlin/com/coxautodev/graphql/tools/DictionaryTypeResolver.kt
1
1651
package com.coxautodev.graphql.tools import com.google.common.collect.BiMap import graphql.schema.GraphQLInterfaceType import graphql.schema.GraphQLObjectType import graphql.schema.GraphQLUnionType import graphql.schema.TypeResolver /** * @author Andrew Potter */ abstract class DictionaryTypeResolver(private val dictionary: BiMap<Class<*>, String>, private val types: Map<String, GraphQLObjectType>) : TypeResolver { override fun getType(`object`: Any): GraphQLObjectType { val clazz = `object`.javaClass val name = dictionary[clazz] ?: clazz.simpleName return types[name] ?: throw TypeResolverError(getError(name)) } abstract fun getError(name: String): String } class InterfaceTypeResolver(dictionary: BiMap<Class<*>, String>, private val thisInterface: GraphQLInterfaceType, types: List<GraphQLObjectType>) : DictionaryTypeResolver(dictionary, types.filter { it.interfaces.any { it.name == thisInterface.name } }.associateBy { it.name }) { override fun getError(name: String) = "Expected object type with name '$name' to implement interface '${thisInterface.name}', but it doesn't!" } class UnionTypeResolver(dictionary: BiMap<Class<*>, String>, private val thisUnion: GraphQLUnionType, types: List<GraphQLObjectType>) : DictionaryTypeResolver(dictionary, types.filter { type -> thisUnion.types.any { it.name == type.name } }.associateBy { it.name }) { override fun getError(name: String) = "Expected object type with name '$name' to exist for union '${thisUnion.name}', but it doesn't!" } class TypeResolverError(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
mit
ee0610746be9ff922fb4a166a34011f7
50.59375
278
0.754088
4.462162
false
false
false
false
SimonVT/cathode
trakt-api/src/main/java/net/simonvt/cathode/api/body/CheckinItem.kt
1
1982
/* * Copyright (C) 2014 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.api.body import net.simonvt.cathode.api.entity.Sharing class CheckinItem private constructor( val movie: TraktIdItem?, val episode: TraktIdItem?, val sharing: Sharing?, val message: String?, val venue_id: String?, val venue_name: String?, val app_version: String?, val app_date: String? ) { data class Builder( var movie: TraktIdItem? = null, var episode: TraktIdItem? = null, var sharing: Sharing? = null, var message: String? = null, var venue_id: String? = null, var venue_name: String? = null, var app_version: String? = null, var app_date: String? = null ) { fun movie(traktId: Long) = apply { this.movie = TraktIdItem.withId(traktId) } fun episode(traktId: Long) = apply { this.episode = TraktIdItem.withId(traktId) } fun sharing(sharing: Sharing) = apply { this.sharing = sharing } fun message(message: String?) = apply { this.message = message } fun venueId(venueId: String?) = apply { this.venue_id = venueId } fun venueName(venueName: String?) = apply { this.venue_name = venueName } fun appVersion(appVersion: String) = apply { this.app_version = appVersion } fun appDate(appDate: String) = apply { this.app_date = appDate } fun build() = CheckinItem(movie, episode, sharing, message, venue_id, venue_name, app_version, app_date) } }
apache-2.0
a4199e9b7dfc1baab6d2f5f9d9426dc7
35.703704
96
0.695257
3.73258
false
false
false
false
noseblowhorn/krog
src/test/kotlin/eu/fizzystuff/krog/scenes/mainscreen/PlayerCharacterMovementTests.kt
1
4797
package eu.fizzystuff.krog.scenes.mainscreen import com.googlecode.lanterna.input.KeyStroke import com.googlecode.lanterna.input.KeyType import eu.fizzystuff.krog.scenes.mainscreen.input.PlayerCharacterMovement import eu.fizzystuff.krog.model.DungeonLevel import eu.fizzystuff.krog.model.PlayerCharacter import eu.fizzystuff.krog.model.Tile import eu.fizzystuff.krog.model.WorldState import eu.fizzystuff.krog.ui.MessageBuffer import org.junit.Assert import org.junit.Before import org.junit.Test class PlayerCharacterMovementTests { val messageBuffer: MessageBuffer = MessageBuffer() @Before fun setUp() { WorldState.instance.currentDungeonLevel = DungeonLevel(3, 3) PlayerCharacter.instance = PlayerCharacter() PlayerCharacter.instance.x = 1 PlayerCharacter.instance.y = 1 } @Test fun testMoveNorth() { PlayerCharacterMovement(messageBuffer).process(KeyStroke(KeyType.ArrowUp)) Assert.assertEquals(0, PlayerCharacter.instance.y) Assert.assertEquals(1, PlayerCharacter.instance.x) PlayerCharacterMovement(messageBuffer).process(KeyStroke(KeyType.ArrowUp)) Assert.assertEquals(0, PlayerCharacter.instance.y) Assert.assertEquals(1, PlayerCharacter.instance.x) } @Test fun testMoveSouth() { PlayerCharacterMovement(messageBuffer).process(KeyStroke(KeyType.ArrowDown)) Assert.assertEquals(2, PlayerCharacter.instance.y) Assert.assertEquals(1, PlayerCharacter.instance.x) PlayerCharacterMovement(messageBuffer).process(KeyStroke(KeyType.ArrowDown)) Assert.assertEquals(2, PlayerCharacter.instance.y) Assert.assertEquals(1, PlayerCharacter.instance.x) } @Test fun testMoveWest() { PlayerCharacterMovement(messageBuffer).process(KeyStroke(KeyType.ArrowLeft)) Assert.assertEquals(1, PlayerCharacter.instance.y) Assert.assertEquals(0, PlayerCharacter.instance.x) PlayerCharacterMovement(messageBuffer).process(KeyStroke(KeyType.ArrowLeft)) Assert.assertEquals(1, PlayerCharacter.instance.y) Assert.assertEquals(0, PlayerCharacter.instance.x) } @Test fun testMoveEast() { PlayerCharacterMovement(messageBuffer).process(KeyStroke(KeyType.ArrowRight)) Assert.assertEquals(1, PlayerCharacter.instance.y) Assert.assertEquals(2, PlayerCharacter.instance.x) PlayerCharacterMovement(messageBuffer).process(KeyStroke(KeyType.ArrowRight)) Assert.assertEquals(1, PlayerCharacter.instance.y) Assert.assertEquals(2, PlayerCharacter.instance.x) } @Test fun testMoveNorthwest() { PlayerCharacterMovement(messageBuffer).process(KeyStroke('7', false, false)) Assert.assertEquals(0, PlayerCharacter.instance.y) Assert.assertEquals(0, PlayerCharacter.instance.x) PlayerCharacterMovement(messageBuffer).process(KeyStroke('7', false, false)) Assert.assertEquals(0, PlayerCharacter.instance.y) Assert.assertEquals(0, PlayerCharacter.instance.x) } @Test fun testMoveNortheast() { PlayerCharacterMovement(messageBuffer).process(KeyStroke('9', false, false)) Assert.assertEquals(0, PlayerCharacter.instance.y) Assert.assertEquals(2, PlayerCharacter.instance.x) PlayerCharacterMovement(messageBuffer).process(KeyStroke('9', false, false)) Assert.assertEquals(0, PlayerCharacter.instance.y) Assert.assertEquals(2, PlayerCharacter.instance.x) } @Test fun testMoveSouthwest() { PlayerCharacterMovement(messageBuffer).process(KeyStroke('1', false, false)) Assert.assertEquals(2, PlayerCharacter.instance.y) Assert.assertEquals(0, PlayerCharacter.instance.x) PlayerCharacterMovement(messageBuffer).process(KeyStroke('1', false, false)) Assert.assertEquals(2, PlayerCharacter.instance.y) Assert.assertEquals(0, PlayerCharacter.instance.x) } @Test fun testMoveSoutheast() { PlayerCharacterMovement(messageBuffer).process(KeyStroke('3', false, false)) Assert.assertEquals(2, PlayerCharacter.instance.y) Assert.assertEquals(2, PlayerCharacter.instance.x) PlayerCharacterMovement(messageBuffer).process(KeyStroke('3', false, false)) Assert.assertEquals(2, PlayerCharacter.instance.y) Assert.assertEquals(2, PlayerCharacter.instance.x) } @Test fun testMoveThroughObstruction() { WorldState.instance.currentDungeonLevel.setTileAt(1, 0, Tile.wallTile) PlayerCharacterMovement(messageBuffer).process(KeyStroke(KeyType.ArrowUp)) Assert.assertEquals(1, PlayerCharacter.instance.y) Assert.assertEquals(1, PlayerCharacter.instance.x) } }
apache-2.0
5a18496d05f267a92b6e998b3cd4a92f
33.028369
85
0.729206
4.360909
false
true
false
false
Geobert/radis
app/src/main/kotlin/fr/geobert/radis/ui/adapter/AccountAdapter.kt
1
2990
package fr.geobert.radis.ui.adapter import android.database.Cursor import android.support.v4.app.FragmentActivity import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import fr.geobert.radis.R import fr.geobert.radis.data.Account import fr.geobert.radis.tools.formatDate import fr.geobert.radis.tools.formatSum import fr.geobert.radis.tools.map import java.util.* class AccountAdapter(val activity: FragmentActivity) : BaseAdapter(), Iterable<Account> { private var accountsList: MutableList<Account> = LinkedList() private val redColor: Int by lazy(LazyThreadSafetyMode.NONE) { activity.resources.getColor(R.color.op_alert) } private val greenColor: Int by lazy(LazyThreadSafetyMode.NONE) { activity.resources.getColor(R.color.positiveSum) } override fun getView(p0: Int, p1: View?, p2: ViewGroup): View? { val h: AccountRowHolder = if (p1 == null) { val v = activity.layoutInflater.inflate(R.layout.account_row, p2, false) val t = AccountRowHolder(v) v.tag = t t } else { p1.tag as AccountRowHolder } if (accountsList.isEmpty()) { return null } val account = accountsList[p0] val currencySymbol = account.getCurrencySymbol(activity) h.accountName.text = account.name val stringBuilder = StringBuilder() val sum = account.curSum if (sum < 0) { h.accountSum.setTextColor(redColor) } else { h.accountSum.setTextColor(greenColor) } stringBuilder.append((sum.toDouble() / 100.0).formatSum()) stringBuilder.append(' ').append(currencySymbol) h.accountSum.text = stringBuilder val dateLong = account.curSumDate?.time ?: 0 stringBuilder.setLength(0) if (dateLong > 0) { stringBuilder.append(activity.getString(R.string.balance_at).format(Date(dateLong).formatDate())) } else { stringBuilder.append(activity.getString(R.string.current_sum)) } h.balanceDate.text = stringBuilder return h.view } fun getAccount(p: Int): Account { return accountsList.get(p) } override fun getItem(p0: Int): Any? { return accountsList.get(p0) } override fun getItemId(p0: Int): Long { return if (p0 < count) accountsList.get(p0).id else 0 } override fun getCount(): Int { return accountsList.count() } fun swapCursor(c: Cursor) { accountsList = c.map { Account(c) } notifyDataSetChanged() } override fun iterator(): Iterator<Account> { return accountsList.iterator() } override fun isEmpty(): Boolean { return count == 0 } fun getAccountById(id: Long): Account? { accountsList.forEach { if (it.id == id) return it } return null } companion object { val TAG = "AccountAdapter" } }
gpl-2.0
dfb796455c680a0afb3877a3d27fd6ac
29.510204
119
0.639799
4.09589
false
false
false
false
rusinikita/movies-shmoovies
app/src/main/kotlin/com/nikita/movies_shmoovies/common/utils/ContextExtentions.kt
1
1379
package com.nikita.movies_shmoovies.common.utils import android.content.Context import android.content.res.Resources import android.content.res.TypedArray import android.graphics.drawable.Drawable import android.support.annotation.AttrRes import android.support.annotation.ColorInt import android.support.annotation.ColorRes import android.support.annotation.DrawableRes import android.support.v4.content.ContextCompat import android.support.v4.content.res.ResourcesCompat import android.view.LayoutInflater fun Context.dpToPx(dp: Float): Int = (resources.displayMetrics.density * dp + 0.5).toInt() fun Context.dpToPxF(dp: Float): Float = dpToPx(dp).toFloat() @ColorInt fun Context.getColorCompat(@ColorRes colorRes: Int): Int = ContextCompat.getColor(this, colorRes) fun Context.getDrawableCompat(@DrawableRes drawableRes: Int, theme: Resources.Theme? = null): Drawable? = ResourcesCompat.getDrawable(this.resources, drawableRes, theme) val Context.layoutInflater: LayoutInflater get() = LayoutInflater.from(this) fun Context.getThemeColor(@AttrRes attr: Int): Int = getThemeAttr(attr, { it.getColor(0, 0) }) private inline fun <T> Context.getThemeAttr(@AttrRes attr: Int, extractor: (TypedArray) -> T): T { val attrs = intArrayOf(attr) val typedArray = this.obtainStyledAttributes(attrs) val value: T = extractor(typedArray) typedArray.recycle() return value }
apache-2.0
183b5461bb192e9c5831550ad70b21f1
40.818182
169
0.799855
4.104167
false
false
false
false
tasks/tasks
app/src/main/java/com/todoroo/astrid/service/TaskDeleter.kt
1
3378
package com.todoroo.astrid.service import com.todoroo.astrid.api.Filter import com.todoroo.astrid.data.Task import kotlinx.coroutines.runBlocking import org.tasks.LocalBroadcastManager import org.tasks.caldav.VtodoCache import org.tasks.data.CaldavAccount import org.tasks.data.CaldavCalendar import org.tasks.data.DeletionDao import org.tasks.data.GoogleTaskAccount import org.tasks.data.GoogleTaskDao import org.tasks.data.GoogleTaskList import org.tasks.data.TaskContainer import org.tasks.data.TaskDao import org.tasks.db.QueryUtils import org.tasks.db.SuspendDbUtils.chunkedMap import org.tasks.jobs.WorkManager import org.tasks.preferences.Preferences import org.tasks.sync.SyncAdapters import javax.inject.Inject class TaskDeleter @Inject constructor( private val deletionDao: DeletionDao, private val workManager: WorkManager, private val taskDao: TaskDao, private val localBroadcastManager: LocalBroadcastManager, private val googleTaskDao: GoogleTaskDao, private val preferences: Preferences, private val syncAdapters: SyncAdapters, private val vtodoCache: VtodoCache, ) { suspend fun markDeleted(item: Task) = markDeleted(listOf(item.id)) suspend fun markDeleted(taskIds: List<Long>): List<Task> { val ids: MutableSet<Long> = HashSet(taskIds) ids.addAll(taskIds.chunkedMap(googleTaskDao::getChildren)) ids.addAll(taskIds.chunkedMap(taskDao::getChildren)) deletionDao.markDeleted(ids) workManager.cleanup(ids) syncAdapters.sync() localBroadcastManager.broadcastRefresh() return ids.chunkedMap(taskDao::fetch) } suspend fun clearCompleted(filter: Filter): Int { val deleteFilter = Filter(null, null) deleteFilter.setFilterQueryOverride( QueryUtils.removeOrder(QueryUtils.showHiddenAndCompleted(filter.originalSqlQuery))) val completed = taskDao.fetchTasks(preferences, deleteFilter) .filter(TaskContainer::isCompleted) .map(TaskContainer::getId) .toMutableList() completed.removeAll(deletionDao.hasRecurringAncestors(completed)) completed.removeAll(googleTaskDao.hasRecurringParent(completed)) markDeleted(completed) return completed.size } suspend fun delete(task: Task) = delete(task.id) suspend fun delete(task: Long) = delete(listOf(task)) suspend fun delete(tasks: List<Long>) { deletionDao.delete(tasks) workManager.cleanup(tasks) localBroadcastManager.broadcastRefresh() } fun delete(list: GoogleTaskList) = runBlocking { val tasks = deletionDao.delete(list) delete(tasks) localBroadcastManager.broadcastRefreshList() } suspend fun delete(list: GoogleTaskAccount) { val tasks = deletionDao.delete(list) delete(tasks) localBroadcastManager.broadcastRefreshList() } suspend fun delete(list: CaldavCalendar) { vtodoCache.delete(list) val tasks = deletionDao.delete(list) delete(tasks) localBroadcastManager.broadcastRefreshList() } suspend fun delete(list: CaldavAccount) { vtodoCache.delete(list) val tasks = deletionDao.delete(list) delete(tasks) localBroadcastManager.broadcastRefreshList() } }
gpl-3.0
fa6fbd3a24dd880746f53f74c77a3aa3
34.197917
99
0.716696
4.540323
false
false
false
false
apollo-rsps/apollo
game/plugin/skills/herblore/src/Ingredient.kt
1
1972
import CrushableIngredient.Companion.isCrushable import NormalIngredient.Companion.isNormalIngredient import org.apollo.game.plugin.api.Definitions /** * A secondary ingredient in a potion. */ interface Ingredient { val id: Int companion object { internal fun Int.isIngredient(): Boolean = isNormalIngredient() || isCrushable() } } enum class CrushableIngredient(val uncrushed: Int, override val id: Int) : Ingredient { UNICORN_HORN(uncrushed = 237, id = 235), DRAGON_SCALE(uncrushed = 243, id = 241), CHOCOLATE_BAR(uncrushed = 1973, id = 1975), BIRDS_NEST(uncrushed = 5075, id = 6693); val uncrushedName by lazy { Definitions.item(uncrushed)!!.name } companion object { private const val PESTLE_AND_MORTAR = 233 private const val KNIFE = 5605 private val ingredients = CrushableIngredient.values().associateBy(CrushableIngredient::uncrushed) operator fun get(id: Int): CrushableIngredient? = ingredients[id] internal fun Int.isCrushable(): Boolean = this in ingredients internal fun Int.isGrindingTool(): Boolean = this == KNIFE || this == PESTLE_AND_MORTAR } } enum class NormalIngredient(override val id: Int) : Ingredient { EYE_NEWT(id = 221), RED_SPIDERS_EGGS(id = 223), LIMPWURT_ROOT(id = 225), SNAPE_GRASS(id = 231), WHITE_BERRIES(id = 239), WINE_ZAMORAK(id = 245), JANGERBERRIES(id = 247), TOADS_LEGS(id = 2152), MORT_MYRE_FUNGI(id = 2970), POTATO_CACTUS(id = 3138), PHOENIX_FEATHER(id = 4621), FROG_SPAWN(id = 5004), PAPAYA_FRUIT(id = 5972), POISON_IVY_BERRIES(id = 6018), YEW_ROOTS(id = 6049), MAGIC_ROOTS(id = 6051); companion object { private val ingredients = NormalIngredient.values().associateBy(NormalIngredient::id) operator fun get(id: Int): NormalIngredient? = ingredients[id] internal fun Int.isNormalIngredient(): Boolean = this in ingredients } }
isc
9eeb397810bdb5a19bcba2bfd19cfe76
31.883333
106
0.675456
3.222222
false
false
false
false
soniccat/android-taskmanager
modelcore_ui/src/main/java/com/aglushkov/modelcore_ui/view/LoadingStatusView.kt
1
3569
package com.aglushkov.modelcore_ui.view import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import androidx.core.content.withStyledAttributes import androidx.core.view.isVisible import com.aglushkov.modelcore.extensions.getLayoutInflater import com.aglushkov.modelcore.resource.Resource import com.aglushkov.modelcore.resource.isLoadedAndEmpty import com.aglushkov.modelcore.resource.isLoading import com.aglushkov.modelcore_ui.R import com.aglushkov.modelcore_ui.databinding.LoadingStatusViewBinding class LoadingStatusView: FrameLayout { private var binding: LoadingStatusViewBinding var needChangeVisibility = false constructor(context: Context) : super(context, null) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs, 0) { applyAttributeSet(attrs) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { applyAttributeSet(attrs) } init { binding = LoadingStatusViewBinding.inflate(context.getLayoutInflater(), this, true) } private fun applyAttributeSet(attrs: AttributeSet?) { if (attrs != null) { context.withStyledAttributes(attrs, R.styleable.LoadingStatusView) { binding.text.text = getString(R.styleable.LoadingStatusView_text) needChangeVisibility = getBoolean(R.styleable.LoadingStatusView_need_change_visibility, false) } } } fun showProgress(aText: String? = null) { if (needChangeVisibility) isVisible = true binding.progress.visibility = View.VISIBLE binding.text.visibility = if (aText != null) View.VISIBLE else View.GONE binding.text.text = aText binding.tryAgainButton.isVisible = false } fun showText(aText: String?, showTryAgainButton: Boolean = false) { if (needChangeVisibility) isVisible = true binding.progress.visibility = View.INVISIBLE binding.text.visibility = if (aText != null) View.VISIBLE else View.GONE binding.text.text = aText binding.tryAgainButton.isVisible = showTryAgainButton } fun hideElements() { if (needChangeVisibility) isVisible = false binding.progress.visibility = View.INVISIBLE binding.text.visibility = View.GONE binding.text.text = null binding.tryAgainButton.isVisible = false } fun setOnTryAgainListener(callback: (View) -> Unit) { binding.tryAgainButton.setOnClickListener(callback) } } fun <T> Resource<T>.bind(view: LoadingStatusView?, errorText: String? = null, loadingText: String? = null, emptyText: String?) where T : Collection<*> { if (view == null) return if (isLoadedAndEmpty() && emptyText != null) { view.showText(emptyText, false) } else { bind(view, errorText, loadingText) } } fun <T> Resource<T>.bind(view: LoadingStatusView?, errorText: String? = null, loadingText: String? = null) { if (view == null) return val data = data() if (data != null) { view.hideElements() } else { if (isLoading()) { view.showProgress(loadingText) } else { if (this is Resource.Error) { view.showText(errorText, canTryAgain) } else { view.hideElements() } } } }
mit
0cadf862b071f17db3992a70e78f8dfa
34
114
0.656486
4.489308
false
false
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/search/RadioSearchEngineListPreference.kt
1
2157
/* 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.search import android.content.Context import androidx.preference.PreferenceViewHolder import android.util.AttributeSet import android.widget.CompoundButton import android.widget.RadioGroup import org.mozilla.focus.R import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.Settings class RadioSearchEngineListPreference : SearchEngineListPreference, RadioGroup.OnCheckedChangeListener { override val itemResId: Int get() = R.layout.search_engine_radio_button @Suppress("unused") constructor(context: Context, attrs: AttributeSet) : super(context, attrs) @Suppress("unused") constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun onBindViewHolder(holder: PreferenceViewHolder?) { super.onBindViewHolder(holder) searchEngineGroup!!.setOnCheckedChangeListener(this) } override fun updateDefaultItem(defaultButton: CompoundButton) { defaultButton.isChecked = true } override fun onCheckedChanged(group: RadioGroup, checkedId: Int) { /* onCheckedChanged is called intermittently before the search engine table is full, so we must check these conditions to prevent crashes and inconsistent states. */ if (group.childCount != searchEngines.count() || group.getChildAt(checkedId) == null || !group.getChildAt(checkedId).isPressed) { return } val newDefaultEngine = searchEngines[checkedId] Settings.getInstance(group.context).setDefaultSearchEngineByName(newDefaultEngine.name) val source = if (CustomSearchEngineStore.isCustomSearchEngine(newDefaultEngine.identifier, context)) CustomSearchEngineStore.ENGINE_TYPE_CUSTOM else CustomSearchEngineStore.ENGINE_TYPE_BUNDLED TelemetryWrapper.setDefaultSearchEngineEvent(source) } }
mpl-2.0
d6c680ef164cb8be4b77f05ade5f53ba
39.698113
111
0.741307
4.970046
false
false
false
false
juxeii/dztools
java/dzjforex/src/main/kotlin/com/jforex/dzjforex/sell/BrokerSell.kt
1
3253
package com.jforex.dzjforex.sell import arrow.Kind import arrow.core.Option import com.dukascopy.api.IOrder import com.dukascopy.api.Instrument import com.jforex.dzjforex.misc.* import com.jforex.dzjforex.order.OrderLookupApi.getTradeableOrderForId import com.jforex.dzjforex.zorro.BROKER_SELL_FAIL import com.jforex.kforexutils.misc.asPrice import com.jforex.kforexutils.order.event.OrderEvent import com.jforex.kforexutils.order.event.OrderEventType import com.jforex.kforexutils.order.extension.close import com.jforex.kforexutils.order.extension.isClosed import com.jforex.kforexutils.settings.TradingSettings object BrokerSellApi { data class CloseParams(val order: IOrder, val amount: Double, val price: Double, val slippage: Double) fun <F> ContextDependencies<F>.brokerSell( orderId: Int, contracts: Int, maybeLimitPrice: Option<Double>, slippage: Double ) = getTradeableOrderForId(orderId) .flatMap { order -> if (order.isClosed) { logger.warn("BrokerSell: trying to close already closed order $order!") just(order.zorroId()) } else { val closeParams = CloseParams( order = order, amount = contracts.toAmount(), price = getLimitPrice(maybeLimitPrice, order.instrument), slippage = slippage ) logger.debug("BrokerSell: $closeParams") closeOrder(closeParams).flatMap { orderEvent -> processOrderEventAndGetResult(orderEvent) } } }.handleErrorWith { error -> processError(error) } fun <F> ContextDependencies<F>.closeOrder(closeParams: CloseParams): Kind<F, OrderEvent> = delay { closeParams .order .close( amount = closeParams.amount, price = closeParams.price, slippage = closeParams.slippage ) {} .blockingLast() } fun <F> ContextDependencies<F>.processOrderEventAndGetResult(orderEvent: OrderEvent) = delay { if (orderEvent.type == OrderEventType.CLOSE_OK || orderEvent.type == OrderEventType.PARTIAL_CLOSE_OK) orderEvent.order.zorroId() else BROKER_SELL_FAIL } fun <F> ContextDependencies<F>.processError(error: Throwable) = delay { when (error) { is OrderIdNotFoundException -> natives.logAndPrintErrorOnZorro("BrokerSell: orderId ${error.orderId} not found!") is AssetNotTradeableException -> natives.logAndPrintErrorOnZorro("BrokerSell: asset ${error.instrument} currently not tradeable!") else -> logger.error("BrokerSell failed! Error: ${error.message} Stack trace: ${getStackTrace(error)}") } BROKER_SELL_FAIL } fun getLimitPrice(maybeLimitPrice: Option<Double>, instrument: Instrument) = maybeLimitPrice .fold({ TradingSettings.noPreferredClosePrice }) { limitPrice -> limitPrice.asPrice(instrument) } }
mit
0f092f5ee254275cc3ca0673788ab786
38.682927
113
0.619121
4.43188
false
false
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/model/IndicatorReportingServiceImpl.kt
1
3233
package net.nemerosa.ontrack.extension.indicators.model import net.nemerosa.ontrack.common.getOrNull import net.nemerosa.ontrack.extension.indicators.portfolio.IndicatorPortfolioService import net.nemerosa.ontrack.model.labels.LabelManagementService import net.nemerosa.ontrack.model.labels.ProjectLabelManagementService import net.nemerosa.ontrack.model.labels.findLabelByDisplay import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.structure.StructureService import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional class IndicatorReportingServiceImpl( private val structureService: StructureService, private val labelManagementService: LabelManagementService, private val projectLabelManagementService: ProjectLabelManagementService, private val portfolioService: IndicatorPortfolioService, private val indicatorService: IndicatorService, ) : IndicatorReportingService { override fun report(filter: IndicatorReportingFilter, types: List<IndicatorType<*, *>>): IndicatorProjectReport { // Gets the list of projects val projects = findProjects(filter, types) // Creates the report return IndicatorProjectReport( items = projects.map { project -> IndicatorProjectReportItem( project = project, indicators = types.map { type -> indicatorService.getProjectIndicator(project, type) } ) } ) } override fun findProjects(filter: IndicatorReportingFilter, types: List<IndicatorType<*, *>>): List<Project> { val list = when { filter.projectId != null -> listOf( structureService.getProject(ID.of(filter.projectId)) ) filter.projectName != null -> listOfNotNull( structureService.findProjectByName(filter.projectName).getOrNull() ) filter.label != null -> { val actualLabel = labelManagementService.findLabelByDisplay(filter.label) if (actualLabel != null) { projectLabelManagementService.getProjectsForLabel(actualLabel).map { id -> structureService.getProject(id) } } else { emptyList() } } filter.portfolio != null -> { val actualPortfolio = portfolioService.findPortfolioById(filter.portfolio) if (actualPortfolio != null) { portfolioService.getPortfolioProjects(actualPortfolio) } else { emptyList() } } else -> structureService.projectList } return if (filter.filledOnly != null && filter.filledOnly) { list.filter { project -> types.any { type -> indicatorService.getProjectIndicator(project, type).value != null } } } else { list } } }
mit
df4ff9831b11e2a67465890a585cf22f
39.425
117
0.628828
5.622609
false
false
false
false
nemerosa/ontrack
ontrack-extension-ldap/src/test/java/net/nemerosa/ontrack/extension/ldap/support/LDAPServer.kt
1
658
package net.nemerosa.ontrack.extension.ldap.support import org.slf4j.Logger import org.slf4j.LoggerFactory class LDAPServer( private val ldifPath: String = "/users.ldif", private val partitionSuffix: String = "dc=nemerosa,dc=net" ) { private val logger: Logger = LoggerFactory.getLogger(LDAPServer::class.java) fun start() { val ldif = LDAPServer::class.java.getResourceAsStream(ldifPath).reader().readText() val ldapContainer = UnboundIdContainer(partitionSuffix, ldif) logger.info("Starting on port ${ldapContainer.port}...") ldapContainer.start() } } fun main() { LDAPServer().start() }
mit
8b831531d0d7e3b5a4154547cf30eaff
27.652174
91
0.696049
3.781609
false
false
false
false
vjames19/kotlin-microservice-example
jooby-api/src/main/kotlin/io/github/vjames19/kotlinmicroserviceexample/blog/api/jooby/endpoint/PostEndpoint.kt
1
2600
package io.github.vjames19.kotlinmicroserviceexample.blog.api.jooby.endpoint import io.github.vjames19.kotlinmicroserviceexample.blog.domain.Comment import io.github.vjames19.kotlinmicroserviceexample.blog.domain.Post import io.github.vjames19.kotlinmicroserviceexample.blog.service.CommentService import io.github.vjames19.kotlinmicroserviceexample.blog.service.PostService import org.jooby.mvc.* import java.util.* import java.util.concurrent.CompletableFuture import javax.inject.Inject /** * Created by victor.reventos on 6/12/17. */ @Path("/posts") class PostEndpoint @Inject constructor(val postService: PostService, val commentService: CommentService) { @GET @Path("/:id") fun get(id: Long): CompletableFuture<Optional<Post>> { return postService.get(id) } @POST fun create(@Body createPostRequest: CreatePostRequest): CompletableFuture<Post> { return postService.create(createPostRequest.toDomain()) } @PUT @Path("/:id") fun update(id: Long, @Body updatePostRequest: UpdatePostRequest): CompletableFuture<Optional<Post>> { return postService.update(Post(id = id, userId = updatePostRequest.userId, content = updatePostRequest.content)) } @DELETE @Path("/:id") fun delete(id: Long): CompletableFuture<Optional<*>> { return postService.delete(id) } @GET @Path("/:id/comments") fun getComments(id: Long): CompletableFuture<List<Comment>> { return commentService.getCommentsForPost(id) } @POST @Path("/:id/comments") fun addComment(id: Long, @Body commentRequest: CommentRequest): CompletableFuture<Comment> { return commentService.create(Comment(id = 0, userId = commentRequest.userId, postId = id, text = commentRequest.text)) } @PUT @Path("/:id/comments/:commentId") fun updateComment(id: Long, commentId: Long, @Body commentRequest: CommentRequest): CompletableFuture<Optional<Comment>> { return commentService.update(Comment(id = commentId, userId = commentRequest.userId, postId = id, text = commentRequest.text)) } @DELETE @Path("/:id/comments/:commentId") fun deleteComment(commentId: Long): CompletableFuture<Optional<*>> { return commentService.delete(commentId) } } data class CreatePostRequest(val userId: Long, val content: String) { fun toDomain(): Post = Post(id = 0, userId = userId, content = content) } data class UpdatePostRequest(val userId: Long, val content: String) data class CommentRequest(val userId: Long, val text: String)
mit
c0db1d908327e3550c06e62cd9a859f4
34.630137
134
0.711154
4.14673
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/bukkit/util/BukkitConstants.kt
1
683
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bukkit.util object BukkitConstants { const val HANDLER_ANNOTATION = "org.bukkit.event.EventHandler" const val EVENT_PRIORITY_CLASS = "org.bukkit.event.EventPriority" const val LISTENER_CLASS = "org.bukkit.event.Listener" const val CHAT_COLOR_CLASS = "org.bukkit.ChatColor" const val EVENT_CLASS = "org.bukkit.event.Event" const val PLUGIN = "org.bukkit.plugin.Plugin" const val EVENT_ISCANCELLED_METHOD_NAME = "isCancelled" const val CANCELLABLE_CLASS = "org.bukkit.event.Cancellable" }
mit
0a73a560239463f7fcdffe45d3006661
28.695652
69
0.72328
3.632979
false
false
false
false
langara/MyIntent
mydrawables/src/main/java/pl/mareklangiewicz/mydrawables/MyArrowDrawable.kt
1
1113
package pl.mareklangiewicz.mydrawables import android.graphics.Path import android.graphics.Rect import androidx.annotation.IntRange /** * Created by Marek Langiewicz on 16.09.15. * An arrow/menu animation */ class MyArrowDrawable : MyLivingDrawable() { override fun drawLivingPath(path: Path, @IntRange(from = 0, to = 10000) level: Int, bounds: Rect, cx: Int, cy: Int) { val w4 = bounds.width() / 4 val h4 = bounds.height() / 4 val h8 = bounds.height() / 8 val topBarY = cy - h8 val bottomBarY = cy + h8 val topArrY = cy - h4 val bottomArrY = cy + h4 val leftX = bounds.left + w4 val rightX = bounds.right - w4 // middle bar ln(leftX, cy, rightX, cy) // top bar ln(lvl(leftX, cx), lvl(topBarY, topArrY), rightX, lvl(topBarY, cy)) // bottom bar val y = lvl(bottomBarY, cy).toFloat() if (y - cy < 2) path.lineTo(rightX.toFloat(), y) else path.moveTo(rightX.toFloat(), y) path.lineTo(lvl(leftX, cx).toFloat(), lvl(bottomBarY, bottomArrY).toFloat()) } }
apache-2.0
6249cfe4bfb783af71b89ae0855424c8
29.081081
121
0.603774
3.424615
false
false
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/ui/widget/DecorationOne.kt
1
1013
package com.engineer.imitate.ui.widget import android.content.Context import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView import com.engineer.imitate.util.dp2px /** * @author rookie * @since 12-10-2019 */ class DecorationOne(val context: Context) : RecyclerView.ItemDecoration() { val TAG = "DecorationOne" private val dp8 = context.dp2px(8f).toInt() private val dp14 = context.dp2px(14f).toInt() override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { super.getItemOffsets(outRect, view, parent, state) val pos = parent.getChildAdapterPosition(view) when (pos) { 0 -> { outRect.left = dp14 } 5 -> { outRect.left = dp8 outRect.right = dp14 } else -> { outRect.left = dp8 } } } }
apache-2.0
8b0f64e2960ddce3eef56deda7c22a86
24.325
75
0.582428
4.18595
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/ext/web/config/WebServerConfig.kt
1
2132
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.ext.web.config import com.google.common.base.Strings import org.apache.commons.codec.binary.Hex import org.eclipse.jetty.server.Server import svnserver.config.SharedConfig import svnserver.context.SharedContext import svnserver.ext.web.server.WebServer import svnserver.ext.web.token.EncryptionFactoryAes import java.net.URL import java.security.SecureRandom /** * Web server configuration. * * @author Artem V. Navrotskiy <[email protected]> */ class WebServerConfig : SharedConfig { private var listen: Array<ListenConfig> private var secret = defaultSecret private var baseUrl: String? = null constructor() { listen = arrayOf(ListenHttpConfig()) } constructor(port: Int) { listen = arrayOf(ListenHttpConfig(port)) } @Throws(Exception::class) override fun create(context: SharedContext) { val url: URL? = if (Strings.isNullOrEmpty(baseUrl)) { null } else { URL(if (baseUrl!!.endsWith("/")) baseUrl else "$baseUrl/") } context.add(WebServer::class.java, WebServer(context, createJettyServer(), if (baseUrl == null) null else url, EncryptionFactoryAes(secret))) } private fun createJettyServer(): Server { val server = Server() for (listenConfig in listen) server.addConnector(listenConfig.createConnector(server)) return server } companion object { private val defaultSecret = generateDefaultSecret() private fun generateDefaultSecret(): String { val random = SecureRandom() val bytes = ByteArray(EncryptionFactoryAes.KEY_SIZE) random.nextBytes(bytes) return String(Hex.encodeHex(bytes)) } } }
gpl-2.0
ba709bd2a0b622bf0e783318a7174aef
32.84127
149
0.692777
4.255489
false
true
false
false
Le-Chiffre/Yttrium
Server/src/com/rimmer/yttrium/server/http/PooledClient.kt
2
7434
package com.rimmer.yttrium.server.http import com.rimmer.yttrium.Context import com.rimmer.yttrium.Task import com.rimmer.yttrium.getOrAdd import com.rimmer.yttrium.parseInt import com.rimmer.yttrium.server.ServerContext import io.netty.buffer.ByteBuf import io.netty.channel.EventLoop import io.netty.handler.codec.http.* import io.netty.util.AsciiString import java.io.IOException import java.util.* class HttpPooledClient( context: ServerContext, val maxIdle: Long = 60L * 1000L * 1000000L, val maxBusy: Long = 60L * 1000L * 1000000L, val maxRetries: Int = 1, val debug: Boolean = false, val useNative: Boolean = false ) { private val pools: Map<EventLoop, HashMap<String, SingleThreadPool>> init { // We initialize the pool at creation to avoid synchronization when lazily creating pools. val map = HashMap<EventLoop, HashMap<String, SingleThreadPool>>() context.handlerGroup.forEach { loop -> if(loop is EventLoop) { map[loop] = HashMap() } } pools = map } fun get(context: Context, url: String, headers: HttpHeaders? = null, listener: HttpListener? = null) = request(context, url, HttpMethod.GET, headers, listener = listener) fun post( context: Context, url: String, headers: HttpHeaders? = null, body: Any? = null, contentType: AsciiString? = HttpHeaderValues.APPLICATION_JSON, listener: HttpListener? = null ) = request(context, url, HttpMethod.POST, headers, body, contentType, listener) fun put( context: Context, url: String, headers: HttpHeaders? = null, body: Any? = null, contentType: AsciiString? = HttpHeaderValues.APPLICATION_JSON, listener: HttpListener? = null ) = request(context, url, HttpMethod.PUT, headers, body, contentType, listener) fun delete( context: Context, url: String, headers: HttpHeaders? = null, body: Any? = null, contentType: AsciiString? = HttpHeaderValues.APPLICATION_JSON, listener: HttpListener? = null ) = request(context, url, HttpMethod.DELETE, headers, body, contentType, listener) fun request( context: Context, url: String, method: HttpMethod, headers: HttpHeaders? = null, body: Any? = null, contentType: AsciiString? = HttpHeaderValues.APPLICATION_JSON, listener: HttpListener? = null ): Task<HttpResult> { val loop = context.eventLoop val pool = pools[loop] ?: throw IllegalArgumentException("Invalid context event loop - the event loop must be in the server's handlerGroup.") val split = url.split("://") val isSsl: Boolean val index = if(split.size > 1) { isSsl = split[0] == "https" 1 } else { isSsl = false 0 } val domain = split[index].substringBefore('/') val path = split[index].substring(domain.length) val portString = domain.substringAfter(':', "") val host = if(portString.isEmpty()) domain else domain.substringBefore(':') val port = if(portString.isNotEmpty()) parseInt(portString) else if(isSsl) 443 else 80 val selector = "$domain $isSsl" val request = genRequest(path, host, method, headers, body, contentType) val client = pool.getOrAdd(selector) { SingleThreadPool(PoolConfiguration(4, maxIdle, maxBusy, debug = debug)) { connectHttp(loop, host, port, isSsl, 30000, useNative, it) } } val task = Task<HttpResult>() client.get { c, e -> if(e == null) { val wrappedListener = object : HttpListener { var connection = c!! var hasResult = false var retries = 0 override fun onResult(result: HttpResult): Boolean { hasResult = true return listener?.onResult(result) ?: true } override fun onContent(result: HttpResult, content: ByteBuf, finished: Boolean): Boolean { hasResult = true val ret = listener?.onContent(result, content, finished) ?: true if(finished || !ret) { if(body is ByteBuf) body.release() connection.close() task.finish(result) } return ret } override fun onError(error: Throwable) { connection.close() if(hasResult) { if(body is ByteBuf) body.release() listener?.onError(error) task.fail(error) } else if(error is IOException && retries < maxRetries) { if(debug) println("Retrying $method $path") retries++ if(body is ByteBuf) body.retain() client.get { c, e -> if(e == null) { connection = c!! val req = genRequest(path, host, method, headers, body, contentType) connection.request(req, body, this) } else { if(body is ByteBuf) body.release(body.refCnt()) task.fail(e) } } } else { if(body is ByteBuf) body.release() task.fail(error) } } } c!!.request(request, body, wrappedListener) } else { if(body is ByteBuf) body.release(body.refCnt()) task.fail(e) } } return task } fun genRequest( path: String, domain: String, method: HttpMethod, headers: HttpHeaders? = null, body: Any? = null, contentType: AsciiString? = HttpHeaderValues.APPLICATION_JSON ): HttpRequest { val request = if(body === null) { DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, path) } else { DefaultHttpRequest(HttpVersion.HTTP_1_1, method, path) } val httpHeaders = request.headers() if(headers !== null) { httpHeaders.add(headers) } if(!httpHeaders.contains(HttpHeaderNames.HOST)) { httpHeaders[HttpHeaderNames.HOST] = domain } if(body !== null) { if(!httpHeaders.contains(HttpHeaderNames.CONTENT_TYPE) && contentType != null) { httpHeaders[HttpHeaderNames.CONTENT_TYPE] = contentType } if(!httpHeaders.contains(HttpHeaderNames.CONTENT_LENGTH) && body is ByteBuf) { httpHeaders[HttpHeaderNames.CONTENT_LENGTH] = body.writerIndex() } } // Retain body in case we need to retry. if(body is ByteBuf) body.retain() return request } }
mit
f131c4cfdee034e46e521e64c0ac4125
35.263415
127
0.531746
4.919921
false
false
false
false
android/security-samples
FileLocker/app/src/main/java/com/android/example/filelocker/BindingAdapter.kt
1
6931
/* * Copyright (c) 2019 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.android.example.filelocker import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.view.View import android.view.ViewGroup import android.view.WindowInsets import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.core.graphics.ColorUtils import androidx.core.view.updateLayoutParams import androidx.databinding.BindingAdapter import com.google.android.material.color.MaterialColors import com.google.android.material.shape.MaterialShapeDrawable @BindingAdapter("statusBarAdaptive") fun View.bindStatusBarAdaptive(statusBarAdaptive: Boolean) { val bgColor = backgroundColor val luminance = ColorUtils.calculateLuminance(bgColor) if (luminance < 0.5) { clearStatusBarLight() } else { setStatusBarLight() } } private val View.backgroundColor: Int @ColorInt get() { return when (val bg = background) { is ColorDrawable -> bg.color is MaterialShapeDrawable -> bg.fillColor?.defaultColor ?: Color.TRANSPARENT else -> Color.TRANSPARENT } } private fun View.setStatusBarLight() { systemUiVisibility = systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } private fun View.clearStatusBarLight() { systemUiVisibility = systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() } @BindingAdapter("layoutFullscreen") fun View.bindLayoutFullscreen(previousFullscreen: Boolean, fullscreen: Boolean) { if (previousFullscreen != fullscreen && fullscreen) { systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION } } @BindingAdapter( "paddingLeftSystemWindowInsets", "paddingTopSystemWindowInsets", "paddingRightSystemWindowInsets", "paddingBottomSystemWindowInsets", requireAll = false ) fun View.applySystemWindowInsetsPadding( previousApplyLeft: Boolean, previousApplyTop: Boolean, previousApplyRight: Boolean, previousApplyBottom: Boolean, applyLeft: Boolean, applyTop: Boolean, applyRight: Boolean, applyBottom: Boolean ) { if (previousApplyLeft == applyLeft && previousApplyTop == applyTop && previousApplyRight == applyRight && previousApplyBottom == applyBottom ) { return } doOnApplyWindowInsets { view, insets, padding, _, _ -> val left = if (applyLeft) insets.systemWindowInsetLeft else 0 val top = if (applyTop) insets.systemWindowInsetTop else 0 val right = if (applyRight) insets.systemWindowInsetRight else 0 val bottom = if (applyBottom) insets.systemWindowInsetBottom else 0 view.setPadding( padding.left + left, padding.top + top, padding.right + right, padding.bottom + bottom ) } } @BindingAdapter( "marginLeftSystemWindowInsets", "marginTopSystemWindowInsets", "marginRightSystemWindowInsets", "marginBottomSystemWindowInsets", requireAll = false ) fun View.applySystemWindowInsetsMargin( previousApplyLeft: Boolean, previousApplyTop: Boolean, previousApplyRight: Boolean, previousApplyBottom: Boolean, applyLeft: Boolean, applyTop: Boolean, applyRight: Boolean, applyBottom: Boolean ) { if (previousApplyLeft == applyLeft && previousApplyTop == applyTop && previousApplyRight == applyRight && previousApplyBottom == applyBottom ) { return } doOnApplyWindowInsets { view, insets, _, margin, _ -> val left = if (applyLeft) insets.systemWindowInsetLeft else 0 val top = if (applyTop) insets.systemWindowInsetTop else 0 val right = if (applyRight) insets.systemWindowInsetRight else 0 val bottom = if (applyBottom) insets.systemWindowInsetBottom else 0 view.updateLayoutParams<ViewGroup.MarginLayoutParams> { leftMargin = margin.left + left topMargin = margin.top + top rightMargin = margin.right + right bottomMargin = margin.bottom + bottom } } } fun View.doOnApplyWindowInsets( block: (View, WindowInsets, InitialPadding, InitialMargin, Int) -> Unit ) { // Create a snapshot of the view's padding & margin states val initialPadding = recordInitialPaddingForView(this) val initialMargin = recordInitialMarginForView(this) val initialHeight = recordInitialHeightForView(this) // Set an actual OnApplyWindowInsetsListener which proxies to the given // lambda, also passing in the original padding & margin states setOnApplyWindowInsetsListener { v, insets -> block(v, insets, initialPadding, initialMargin, initialHeight) // Always return the insets, so that children can also use them insets } // request some insets requestApplyInsetsWhenAttached() } class InitialPadding(val left: Int, val top: Int, val right: Int, val bottom: Int) class InitialMargin(val left: Int, val top: Int, val right: Int, val bottom: Int) private fun recordInitialPaddingForView(view: View) = InitialPadding( view.paddingLeft, view.paddingTop, view.paddingRight, view.paddingBottom ) private fun recordInitialMarginForView(view: View): InitialMargin { val lp = view.layoutParams as? ViewGroup.MarginLayoutParams ?: throw IllegalArgumentException("Invalid view layout params") return InitialMargin(lp.leftMargin, lp.topMargin, lp.rightMargin, lp.bottomMargin) } private fun recordInitialHeightForView(view: View): Int { return view.layoutParams.height } fun View.requestApplyInsetsWhenAttached() { if (isAttachedToWindow) { // We're already attached, just request as normal requestApplyInsets() } else { // We're not attached to the hierarchy, add a listener to // request when we are addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) { v.removeOnAttachStateChangeListener(this) v.requestApplyInsets() } override fun onViewDetachedFromWindow(v: View) = Unit }) } }
apache-2.0
c9e9bf140c98125fe6c903a92d8d1a23
33.487562
94
0.7087
4.686275
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/DiningSettingsAdapter.kt
1
1811
package com.pennapps.labs.pennmobile.adapters import android.content.Context import android.content.SharedPreferences import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.preference.PreferenceManager import androidx.recyclerview.widget.RecyclerView import com.pennapps.labs.pennmobile.R import com.pennapps.labs.pennmobile.classes.DiningHall import kotlinx.android.synthetic.main.laundry_settings_child_item.view.* class DiningSettingsAdapter(private var diningHalls: List<DiningHall>) : RecyclerView.Adapter<DiningSettingsAdapter.DiningSettingsViewHolder>() { private lateinit var mContext: Context private lateinit var sp: SharedPreferences override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DiningSettingsViewHolder { mContext = parent.context val view = LayoutInflater.from(mContext).inflate(R.layout.laundry_settings_child_item, parent, false) sp = PreferenceManager.getDefaultSharedPreferences(mContext) return DiningSettingsViewHolder(view) } override fun getItemCount(): Int { return diningHalls.count() } override fun onBindViewHolder(holder: DiningSettingsViewHolder, position: Int) { val hall = diningHalls[position] holder.view.laundry_room_name?.text = hall.name val switch = holder.view.laundry_favorite_switch // set the switch to the correct on or off switch.isChecked = sp.getBoolean(hall.name, false) switch.setOnClickListener { val editor = sp.edit() editor.putBoolean(hall.name, switch.isChecked) editor.apply() } } inner class DiningSettingsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val view = itemView } }
mit
f49b67f0f4c852b103069dd69a939647
36.75
109
0.741579
4.667526
false
false
false
false
xbh0902/cryptlib
CryptLibrary/src/main/kotlin/me/xbh/lib/core/cxx/CryptServiceImpl.kt
1
1680
package me.xbh.lib.core.cxx import android.content.Context import me.xbh.lib.core.ICrypt import me.xbh.lib.core.CryptService import java.util.* /** * <p> * 描述:使用`CryptServiceImpl`可以对数据加密,提供安全保障。其中包含MD5、AES、和RSA公钥加密解密 * </p> * 创建日期:2017年11月02日. * @author [email protected] * @version 1.0 */ internal class CryptServiceImpl : CryptService { private val objs = HashMap<String, ICrypt>() init { objs.put(CryptService.AES, AesImpl()) objs.put(CryptService.RSA, RsaImpl()) } /** * 获取RSA公钥 * @param buildType 构建环境 * dev:1、qa:2、pro:3 */ override fun getRsaPubKey(buildType: Int): String = getElement(CryptService.RSA).getKey(buildType) /** * 获取一个16位的随机密钥 */ override fun getAesKey(): String = getElement(CryptService.AES).getKey(null) /** * md5加密 */ override fun md5(plain: String): String = Md5().digest(plain) /** * 获取本地密钥 */ override fun getAesLocalKey(context: Context) = getElement(CryptService.AES).getKey(context) /** * 加密 */ override fun encrypt(plain: String, key: String, type: String): String { val crypt = getElement(type) return crypt.encrypt(plain, key) } /** * 解密 */ override fun decrypt(cipher: String, key: String,type: String): String { val crypt = getElement(type) return crypt.decrypt(cipher, key) } private fun getElement(type: String): ICrypt { return objs[type] as ICrypt } }
mit
840fa7fd95dcfb7e3d842283433fcff3
21.573529
102
0.617992
3.284797
false
false
false
false
mihmuh/IntelliJConsole
Konsole/src/com/intellij/idekonsole/KActions.kt
1
2941
package com.intellij.idekonsole import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.editor.actions.ContentChooser import com.intellij.openapi.project.DumbAwareAction import java.util.* class ClearOutputAction : DumbAwareAction("Clear Output", null, AllIcons.Actions.Clean) { override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.getData(KDataKeys.K_EDITOR) != null } override fun actionPerformed(e: AnActionEvent) { val editor = e.getRequiredData(KDataKeys.K_EDITOR) editor.clearAll() } } class ExecuteAction : DumbAwareAction("Run", null, AllIcons.General.Run) { override fun update(e: AnActionEvent) { val editor = e.getData(KDataKeys.K_EDITOR) e.presentation.isEnabled = e.place == ActionPlaces.MAIN_MENU || editor != null && editor.canExecute() } override fun actionPerformed(e: AnActionEvent) { val editor = e.getRequiredData(KDataKeys.K_EDITOR) editor.handleCommand() } } class ConsoleHistoryAction : DumbAwareAction("Show History", null, AllIcons.General.MessageHistory) { override fun update(e: AnActionEvent) { val editor = e.getData(KDataKeys.K_EDITOR) e.presentation.isEnabled = editor != null && e.project != null } override fun actionPerformed(e: AnActionEvent) { val editor = e.getRequiredData(KDataKeys.K_EDITOR) val project = e.project!! val contentChooser = object : ContentChooser<String>(project, "Console History", false) { init { isOKActionEnabled = false } override fun removeContentAt(content: String) { KSettings.instance.getConsoleHistory().remove(content) } override fun getStringRepresentationFor(content: String): String = trimCommand(content) override fun getContents(): List<String> { val recentMessages = KSettings.instance.getConsoleHistory() Collections.reverse(recentMessages) return recentMessages } } if (contentChooser.showAndGet()) { val selectedIndex = contentChooser.selectedIndex if (selectedIndex >= 0) { val selectedText = contentChooser.allContents[selectedIndex] editor.setText(selectedText) } } } } class PreviousCommandAction : DumbAwareAction("Previous command", null, AllIcons.Actions.PreviousOccurence){ override fun actionPerformed(e: AnActionEvent?) { e?.getData(KDataKeys.K_EDITOR)?.prevCmd() } } class NextCommandAction : DumbAwareAction("Next command", null, AllIcons.Actions.NextOccurence){ override fun actionPerformed(e: AnActionEvent?) { e?.getData(KDataKeys.K_EDITOR)?.nextCmd() } }
gpl-3.0
4891d31444243b087f44411f29b9e1a9
34.02381
108
0.66916
4.698083
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/ConnectedAppInteraction.kt
1
745
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.common.Interaction /** * All of the interactions for a connected app. * * @param allScopes Provides the lists of scopes that are required for third-party connected app features. * @param isConnected Whether an app is connected or not. */ @JsonClass(generateAdapter = true) data class ConnectedAppInteraction( @Json(name = "all_scopes") val allScopes: ConnectedScopes? = null, @Json(name = "is_connected") val isConnected: Boolean? = null, @Json(name = "options") override val options: List<String>? = null, @Json(name = "uri") override val uri: String? = null ) : Interaction
mit
010f3520efb5f1f1c8068d1859eaad14
26.592593
106
0.719463
3.921053
false
false
false
false
AndroidX/androidx
room/room-compiler-processing-testing/src/main/java/androidx/room/compiler/processing/util/Source.kt
3
4643
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.util import com.google.testing.compile.JavaFileObjects import org.intellij.lang.annotations.Language import java.io.File import javax.tools.JavaFileObject /** * Common abstraction for test sources in kotlin and java */ sealed class Source { abstract val relativePath: String abstract val contents: String abstract fun toJFO(): JavaFileObject override fun toString(): String { return "SourceFile[$relativePath]" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Source) return false if (relativePath != other.relativePath) return false if (contents != other.contents) return false return true } override fun hashCode(): Int { var result = relativePath.hashCode() result = 31 * result + contents.hashCode() return result } class JavaSource( val qName: String, override val contents: String ) : Source() { override fun toJFO(): JavaFileObject { return JavaFileObjects.forSourceString( qName, contents ) } override val relativePath get() = qName.replace(".", File.separator) + ".java" } class KotlinSource( override val relativePath: String, override val contents: String ) : Source() { override fun toJFO(): JavaFileObject { throw IllegalStateException("cannot include kotlin code in javac compilation") } } companion object { fun java( qName: String, @Language("java") code: String ): Source { return JavaSource( qName, code ) } fun kotlin( filePath: String, @Language("kotlin") code: String ): Source { return KotlinSource( filePath, code ) } /** * Convenience method to convert JFO's to the Source objects in XProcessing so that we can * convert room tests to the common API w/o major code refactor */ fun fromJavaFileObject(javaFileObject: JavaFileObject): Source { val uri = javaFileObject.toUri() // parse name from uri val contents = javaFileObject.openReader(true).use { it.readText() } val qName = if (uri.scheme == "mem") { // in java compile testing, path includes SOURCE_OUTPUT, drop it uri.path.substringAfter("SOURCE_OUTPUT/").replace('/', '.') } else { uri.path.replace('/', '.') } val javaExt = ".java" check(qName.endsWith(javaExt)) { "expected a java source file, $qName does not seem like one" } return java(qName.dropLast(javaExt.length), contents) } fun loadKotlinSource( file: File, relativePath: String ): Source { check(file.exists() && file.name.endsWith(".kt")) return kotlin(relativePath, file.readText()) } fun loadJavaSource( file: File, qName: String ): Source { check(file.exists() && file.name.endsWith(".java")) return java(qName, file.readText()) } fun load( file: File, qName: String, relativePath: String ): Source { check(file.exists()) { "file does not exist: ${file.canonicalPath}" } return when { file.name.endsWith(".kt") -> loadKotlinSource(file, relativePath) file.name.endsWith(".java") -> loadJavaSource(file, qName) else -> error("invalid file extension ${file.name}") } } } }
apache-2.0
b286fbd59302ec63aaf57a76fedf2378
29.149351
98
0.562567
4.98176
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/reactnativestripesdk/StripeSdkCardViewManager.kt
2
2655
package abi44_0_0.host.exp.exponent.modules.api.components.reactnativestripesdk import abi44_0_0.com.facebook.react.bridge.ReadableArray import abi44_0_0.com.facebook.react.bridge.ReadableMap import abi44_0_0.com.facebook.react.common.MapBuilder import abi44_0_0.com.facebook.react.uimanager.SimpleViewManager import abi44_0_0.com.facebook.react.uimanager.ThemedReactContext import abi44_0_0.com.facebook.react.uimanager.annotations.ReactProp class StripeSdkCardViewManager : SimpleViewManager<StripeSdkCardView>() { override fun getName() = "CardField" private var reactContextRef: ThemedReactContext? = null override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> { return MapBuilder.of( CardFocusEvent.EVENT_NAME, MapBuilder.of("registrationName", "onFocusChange"), CardChangedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onCardChange") ) } override fun receiveCommand(root: StripeSdkCardView, commandId: String?, args: ReadableArray?) { when (commandId) { "focus" -> root.requestFocusFromJS() "blur" -> root.requestBlurFromJS() "clear" -> root.requestClearFromJS() } } @ReactProp(name = "dangerouslyGetFullCardDetails") fun setDangerouslyGetFullCardDetails(view: StripeSdkCardView, dangerouslyGetFullCardDetails: Boolean = false) { view.setDangerouslyGetFullCardDetails(dangerouslyGetFullCardDetails) } @ReactProp(name = "postalCodeEnabled") fun setPostalCodeEnabled(view: StripeSdkCardView, postalCodeEnabled: Boolean = true) { view.setPostalCodeEnabled(postalCodeEnabled) } @ReactProp(name = "autofocus") fun setAutofocus(view: StripeSdkCardView, autofocus: Boolean = false) { view.setAutofocus(autofocus) } @ReactProp(name = "cardStyle") fun setCardStyle(view: StripeSdkCardView, cardStyle: ReadableMap) { view.setCardStyle(cardStyle) } @ReactProp(name = "placeholder") fun setPlaceHolders(view: StripeSdkCardView, placeholder: ReadableMap) { view.setPlaceHolders(placeholder) } override fun createViewInstance(reactContext: ThemedReactContext): StripeSdkCardView { val stripeSdkModule: StripeSdkModule? = reactContext.getNativeModule(StripeSdkModule::class.java) val view = StripeSdkCardView(reactContext) reactContextRef = reactContext stripeSdkModule?.cardFieldView = view return view } override fun onDropViewInstance(view: StripeSdkCardView) { super.onDropViewInstance(view) val stripeSdkModule: StripeSdkModule? = reactContextRef?.getNativeModule(StripeSdkModule::class.java) stripeSdkModule?.cardFieldView = null reactContextRef = null } }
bsd-3-clause
6786f104813552178cd30ed65d71f9dc
35.875
113
0.772505
4.053435
false
false
false
false
ftomassetti/LangSandbox
src/main/kotlin/me/tomassetti/sandy/ast/Mapping.kt
1
3230
package me.tomassetti.sandy.ast import me.tomassetti.langsandbox.SandyParser.* import org.antlr.v4.runtime.ParserRuleContext import org.antlr.v4.runtime.Token interface ParseTreeToAstMapper<in PTN : ParserRuleContext, out ASTN : Node> { fun map(parseTreeNode: PTN) : ASTN } fun SandyFileContext.toAst(considerPosition: Boolean = false) : SandyFile = SandyFile(this.line().map { it.statement().toAst(considerPosition) }, toPosition(considerPosition)) fun Token.startPoint() = Point(line, charPositionInLine) fun Token.endPoint() = Point(line, charPositionInLine + (if (type == EOF) 0 else text.length)) fun ParserRuleContext.toPosition(considerPosition: Boolean) : Position? { return if (considerPosition) Position(start.startPoint(), stop.endPoint()) else null } fun StatementContext.toAst(considerPosition: Boolean = false) : Statement = when (this) { is VarDeclarationStatementContext -> VarDeclaration(varDeclaration().assignment().ID().text, varDeclaration().assignment().expression().toAst(considerPosition), toPosition(considerPosition)) is AssignmentStatementContext -> Assignment(assignment().ID().text, assignment().expression().toAst(considerPosition), toPosition(considerPosition)) is PrintStatementContext -> Print(print().expression().toAst(considerPosition), toPosition(considerPosition)) else -> throw UnsupportedOperationException(this.javaClass.canonicalName) } fun ExpressionContext.toAst(considerPosition: Boolean = false) : Expression = when (this) { is BinaryOperationContext -> toAst(considerPosition) is IntLiteralContext -> IntLit(text, toPosition(considerPosition)) is DecimalLiteralContext -> DecLit(text, toPosition(considerPosition)) is ParenExpressionContext -> expression().toAst(considerPosition) is VarReferenceContext -> VarReference(text, toPosition(considerPosition)) is TypeConversionContext -> TypeConversion(expression().toAst(considerPosition), targetType.toAst(considerPosition), toPosition(considerPosition)) else -> throw UnsupportedOperationException(this.javaClass.canonicalName) } fun TypeContext.toAst(considerPosition: Boolean = false) : Type = when (this) { is IntegerContext -> IntType(toPosition(considerPosition)) is DecimalContext -> DecimalType(toPosition(considerPosition)) else -> throw UnsupportedOperationException(this.javaClass.canonicalName) } fun BinaryOperationContext.toAst(considerPosition: Boolean = false) : Expression = when (operator.text) { "+" -> SumExpression(left.toAst(considerPosition), right.toAst(considerPosition), toPosition(considerPosition)) "-" -> SubtractionExpression(left.toAst(considerPosition), right.toAst(considerPosition), toPosition(considerPosition)) "*" -> MultiplicationExpression(left.toAst(considerPosition), right.toAst(considerPosition), toPosition(considerPosition)) "/" -> DivisionExpression(left.toAst(considerPosition), right.toAst(considerPosition), toPosition(considerPosition)) else -> throw UnsupportedOperationException(this.javaClass.canonicalName) } class SandyParseTreeToAstMapper : ParseTreeToAstMapper<SandyFileContext, SandyFile> { override fun map(parseTreeNode: SandyFileContext): SandyFile = parseTreeNode.toAst() }
apache-2.0
657e2e9b71f92e905e1c06b410549844
58.814815
194
0.786997
4.28382
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/macros/decl/DeclMacroExpander.kt
1
23203
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.macros.decl import com.intellij.lang.ASTNode import com.intellij.lang.PsiBuilder import com.intellij.lang.PsiBuilderUtil import com.intellij.lang.parser.GeneratedParserUtilBase import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtilRt import com.intellij.psi.PsiElement import com.intellij.psi.TokenType import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import com.intellij.util.SmartList import org.rust.lang.core.macros.* import org.rust.lang.core.macros.errors.DeclMacroExpansionError import org.rust.lang.core.macros.errors.MacroMatchingError import org.rust.lang.core.macros.errors.MacroMatchingError.* import org.rust.lang.core.parser.RustParserUtil.collapsedTokenType import org.rust.lang.core.parser.createAdaptedRustPsiBuilder import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsElementTypes.* import org.rust.lang.core.psi.ext.descendantsOfType import org.rust.lang.core.psi.ext.fragmentSpecifier import org.rust.openapiext.Testmark import org.rust.openapiext.forEachChild import org.rust.openapiext.isUnitTestMode import org.rust.stdext.* import org.rust.stdext.RsResult.Err import org.rust.stdext.RsResult.Ok import java.util.Collections.singletonMap /** * The actual algorithm for expansion is not too hard, but is pretty tricky. * `MacroSubstitution` structure is the key to understanding what we are doing here. * * On the high level, it stores mapping from meta variables to the bits of * syntax it should be substituted with. For example, if `$e:expr` is matched * with `1 + 1` by macro_rules, the `MacroSubstitution` will store `$e -> 1 + 1`. * * The tricky bit is dealing with repetitions (`$()*`). Consider this example: * * ``` * macro_rules! foo { * ($($ i:ident $($ e:expr),*);*) => { * $(fn $ i() { $($ e);*; })* * } * } * foo! { foo 1,2,3; bar 4,5,6 } * ``` * * Here, the `$i` meta variable is matched first with `foo` and then with * `bar`, and `$e` is matched in turn with `1`, `2`, `3`, `4`, `5`, `6`. * * To represent such "multi-mappings", we use a recursive structures: we map * variables not to values, but to *lists* of values or other lists (that is, * to the trees). * * For the above example, the MacroSubstitution would store * * ``` * i -> [foo, bar] * e -> [[1, 2, 3], [4, 5, 6]] * ``` * * The comment copied from [rust-analyzer](https://github.com/rust-analyzer/rust-analyzer/blob/2dd8ba2b21/crates/ra_mbe/src/mbe_expander.rs#L58) */ data class MacroSubstitution( val variables: Map<String, MetaVarValue> ) private fun MacroSubstitution.getVar(name: String, nesting: List<NestingState>): VarLookupResult { var value = variables[name] ?: return VarLookupResult.None loop@ for (nestingState in nesting) { nestingState.hit = true value = when (value) { is MetaVarValue.Fragment -> break@loop is MetaVarValue.Group -> { value.nested.getOrNull(nestingState.idx) ?: run { nestingState.atTheEnd = true return VarLookupResult.Error } } MetaVarValue.EmptyGroup -> { nestingState.atTheEnd = true return VarLookupResult.Error } } } return when (value) { is MetaVarValue.Fragment -> VarLookupResult.Ok(value) is MetaVarValue.Group -> VarLookupResult.Error MetaVarValue.EmptyGroup -> VarLookupResult.Error } } private sealed class VarLookupResult { class Ok(val value: MetaVarValue.Fragment) : VarLookupResult() object None : VarLookupResult() object Error : VarLookupResult() } sealed class MetaVarValue { data class Fragment( val value: String, val kind: FragmentKind?, val elementType: IElementType?, val offsetInCallBody: Int ) : MetaVarValue() data class Group(val nested: MutableList<MetaVarValue> = mutableListOf()) : MetaVarValue() object EmptyGroup : MetaVarValue() } private class NestingState( var idx: Int = 0, var hit: Boolean = false, var atTheEnd: Boolean = false ) class DeclMacroExpander(val project: Project): MacroExpander<RsDeclMacroData, DeclMacroExpansionError>() { override fun expandMacroAsTextWithErr( def: RsDeclMacroData, call: RsMacroCallData ): RsResult<Pair<CharSequence, RangeMap>, DeclMacroExpansionError> { val (case, subst, loweringRanges) = findMatchingPattern(def, call).unwrapOrElse { return Err(it) } val macroExpansion = case.macroExpansion?.macroExpansionContents ?: return Err(DeclMacroExpansionError.DefSyntax) val substWithGlobalVars = MacroSubstitution( subst.variables + singletonMap("crate", MetaVarValue.Fragment(MACRO_DOLLAR_CRATE_IDENTIFIER, null, null, -1)) ) val result = substituteMacro(macroExpansion, substWithGlobalVars).map { (text, ranges) -> text to loweringRanges.mapAll(ranges) }.unwrapOrElse { return Err(it) } checkRanges(call, result.first, result.second) return Ok(result) } private fun findMatchingPattern( def: RsDeclMacroData, call: RsMacroCallData ): RsResult<MatchedPattern, DeclMacroExpansionError> { val macroCallBodyText = (call.macroBody as? MacroCallBody.FunctionLike)?.text ?: return Err(DeclMacroExpansionError.DefSyntax) val (macroCallBody, ranges) = project .createAdaptedRustPsiBuilder(macroCallBodyText) .lowerDocCommentsToAdaptedPsiBuilder(project) macroCallBody.eof() // skip whitespace var start = macroCallBody.mark() val macroCaseList = def.macroBody.value?.macroCaseList ?: return Err(DeclMacroExpansionError.DefSyntax) val errors = mutableListOf<MacroMatchingError>() for (case in macroCaseList) { when (val result = case.pattern.match(macroCallBody)) { is Ok -> return Ok(MatchedPattern(case, result.ok, ranges)) is Err -> { errors += result.err // TODO map offset using `ranges` start.rollbackTo() start = macroCallBody.mark() } } } return Err(DeclMacroExpansionError.Matching(errors)) } private data class MatchedPattern(val case: RsMacroCase, val subst: MacroSubstitution, val ranges: RangeMap) private fun substituteMacro(root: PsiElement, subst: MacroSubstitution): RsResult<Pair<CharSequence, RangeMap>, DeclMacroExpansionError> { val sb = StringBuilder() val ranges = SmartList<MappedTextRange>() if (!substituteMacro(sb, ranges, root.node, subst, mutableListOf())) { if (sb.length > FileUtilRt.LARGE_FOR_CONTENT_LOADING) { return Err(DeclMacroExpansionError.TooLargeExpansion) } return Err(DeclMacroExpansionError.DefSyntax) } return Ok(sb to RangeMap.from(ranges)) } private fun substituteMacro( sb: StringBuilder, ranges: MutableList<MappedTextRange>, root: ASTNode, subst: MacroSubstitution, nesting: MutableList<NestingState> ): Boolean { if (sb.length > FileUtilRt.LARGE_FOR_CONTENT_LOADING) return false root.forEachChild { child -> when (child.elementType) { in RS_REGULAR_COMMENTS -> Unit MACRO_EXPANSION, MACRO_EXPANSION_CONTENTS -> if (!substituteMacro(sb, ranges, child, subst, nesting)) return false MACRO_REFERENCE -> { when (val result = subst.getVar((child.psi as RsMacroReference).referenceName, nesting)) { is VarLookupResult.Ok -> { val value = result.value val parensNeeded = value.kind == FragmentKind.Expr && value.elementType !in USELESS_PARENS_EXPRS if (parensNeeded) { sb.append("(") sb.append(value.value) sb.append(")") } else { sb.safeAppend(value.value) } if (value.offsetInCallBody != -1 && value.value.isNotEmpty()) { ranges.mergeAdd( MappedTextRange( value.offsetInCallBody, sb.length - value.value.length - if (parensNeeded) 1 else 0, value.value.length ) ) } } VarLookupResult.None -> { MacroExpansionMarks.SubstMetaVarNotFound.hit() sb.safeAppend(child.text) return@forEachChild } VarLookupResult.Error -> { return true } } } MACRO_EXPANSION_REFERENCE_GROUP -> { val childPsi = child.psi as RsMacroExpansionReferenceGroup childPsi.macroExpansionContents?.let { contents -> nesting += NestingState() val separator = childPsi.macroExpansionGroupSeparator?.text ?: "" for (i in 0 until 65536) { val lastPosition = sb.length if (!substituteMacro(sb, ranges, contents.node, subst, nesting)) return false val nestingState = nesting.last() if (nestingState.atTheEnd || !nestingState.hit) { sb.delete(lastPosition, sb.length) if (i != 0) { sb.delete(sb.length - separator.length, sb.length) } while (ranges.isNotEmpty() && ranges.last().dstOffset >= sb.length) { ranges.removeLast() } break } nestingState.idx += 1 nestingState.hit = false sb.append(separator) } nesting.removeLast() } } else -> { // ranges += MappedTextRange(child.offsetInDefBody, sb.length, child.textLength, SourceType.MACRO_DEFINITION) sb.safeAppend(child.chars) } } } return true } /** Ensures that the buffer ends (or [str] starts) with a whitespace and appends [str] to the buffer */ private fun StringBuilder.safeAppend(str: CharSequence) { if (!isEmpty() && !last().isWhitespace() && str.isNotEmpty() && !str.first().isWhitespace()) { append(" ") } append(str) } private fun checkRanges(call: RsMacroCallData, expandedText: CharSequence, ranges: RangeMap) { if (!isUnitTestMode) return val callBody = (call.macroBody as? MacroCallBody.FunctionLike)?.text ?: return for (range in ranges.ranges) { val callBodyFragment = callBody.subSequence(range.srcOffset, range.srcEndOffset) val expandedFragment = expandedText.subSequence(range.dstOffset, range.dstEndOffset) check(callBodyFragment == expandedFragment) { "`$callBodyFragment` != `$expandedFragment`" } } } companion object { const val EXPANDER_VERSION = 16 private val USELESS_PARENS_EXPRS = tokenSetOf( LIT_EXPR, MACRO_EXPR, PATH_EXPR, PAREN_EXPR, TUPLE_EXPR, ARRAY_EXPR, UNIT_EXPR ) } } /** * A synthetic identifier produced from `$crate` metavar expansion. * * We can't just expand `$crate` to something like `::crate_name` because * we can pass a result of `$crate` expansion to another macro as a single identifier. * * Let's look at the example: * ``` * // foo_crate * macro_rules! foo { * () => { bar!($crate); } // $crate consumed as a single identifier by `bar!` * } * // bar_crate * macro_rules! bar { * ($i:ident) => { fn f() { $i::some_item(); } } * } * // baz_crate * mod baz { * foo!(); * } * ``` * Imagine that macros `foo`, `bar` and the foo's call are located in different * crates. In this case, when expanding `foo!()`, we should expand $crate to * `::foo_crate`. This `::` is needed to make the path to the crate guaranteed * absolutely (and also to make it work on rust 2015 edition). * Ok, let's look at the result of single step of `foo` macro expansion: * `foo!()` => `bar!(::foo_crate)`. Syntactic construction `::foo_crate` consists * of 2 tokens: `::` and `foo_crate` (identifier). BUT `bar` expects a single * identifier as an input! And this is successfully complied by the rust compiler!! * * The secret is that we should not really expand `$crate` to `::foo_crate`. * We should expand it to "something" that can be passed to another macro * as a single identifier. * * Rustc figures it out by synthetic token (without text representation). * Rustc can do it this way because its macro substitution is based on AST. * But our expansion is text-based, so we must provide something textual * that can be parsed as an identifier. * * It's a very awful hack and we know it. * DON'T TRY THIS AT HOME */ const val MACRO_DOLLAR_CRATE_IDENTIFIER: String = "IntellijRustDollarCrate" val MACRO_DOLLAR_CRATE_IDENTIFIER_REGEX: Regex = Regex(MACRO_DOLLAR_CRATE_IDENTIFIER) typealias MacroMatchingResult = RsResult<MacroSubstitution, MacroMatchingError> typealias GroupMatchingResult = RsResult<List<MacroSubstitution>, MacroMatchingError> class MacroPattern private constructor( val pattern: Sequence<ASTNode> ) { fun match(macroCallBody: PsiBuilder): MacroMatchingResult { return matchPartial(macroCallBody).andThen { result -> if (!macroCallBody.eof()) { MacroExpansionMarks.FailMatchPatternByExtraInput.hit() err(::ExtraInput, macroCallBody) } else { Ok(result) } } } private fun isEmpty() = pattern.firstOrNull() == null private fun matchPartial(macroCallBody: PsiBuilder): MacroMatchingResult { ProgressManager.checkCanceled() val map = HashMap<String, MetaVarValue>() for (node in pattern) { when (node.elementType) { MACRO_BINDING -> { val psi = node.psi as RsMacroBinding val name = psi.metaVarIdentifier.text ?: return err(::PatternSyntax, macroCallBody) val fragmentSpecifier = psi.fragmentSpecifier ?: return err(::PatternSyntax, macroCallBody) val kind = FragmentKind.fromString(fragmentSpecifier) ?: return err(::PatternSyntax, macroCallBody) val lastOffset = macroCallBody.currentOffset val parsed = kind.parse(macroCallBody) if (!parsed || (lastOffset == macroCallBody.currentOffset && kind != FragmentKind.Vis)) { MacroExpansionMarks.FailMatchPatternByBindingType.hit() return err(::FragmentIsNotParsed, macroCallBody, name, kind) } val text = macroCallBody.originalText.substring(lastOffset, macroCallBody.currentOffset) val elementType = macroCallBody.latestDoneMarker?.tokenType map[name] = MetaVarValue.Fragment(text, kind, elementType, lastOffset) } MACRO_BINDING_GROUP -> { val psi = node.psi as RsMacroBindingGroup val nesteds = matchGroup(psi, macroCallBody).unwrapOrElse { return Err(it) } nesteds.forEachIndexed { i, nested -> for ((key, value) in nested.variables) { val it = map.getOrPut(key) { MetaVarValue.Group() } as? MetaVarValue.Group ?: return err(::Nesting, macroCallBody, key) while (it.nested.size < i) { it.nested += MetaVarValue.Group() } it.nested += value } } if (nesteds.isEmpty()) { val vars = psi.descendantsOfType<RsMacroBinding>().mapNotNullToSet { it.name } for (v in vars) { map[v] = MetaVarValue.EmptyGroup } } } else -> { if (!macroCallBody.isSameToken(node)) { MacroExpansionMarks.FailMatchPatternByToken.hit() val actualToken = macroCallBody.tokenType?.toString() val actualTokenText = macroCallBody.tokenText return if (actualToken != null && actualTokenText != null) { Err( UnmatchedToken( macroCallBody.currentOffset, node.elementType.toString(), node.text, actualToken, actualTokenText ) ) } else { err(::EndOfInput, macroCallBody) } } } } } return Ok(MacroSubstitution(map)) } private fun matchGroup(group: RsMacroBindingGroup, macroCallBody: PsiBuilder): GroupMatchingResult { val groups = mutableListOf<MacroSubstitution>() val pattern = valueOf(group.macroPatternContents ?: return err(::PatternSyntax, macroCallBody)) if (pattern.isEmpty()) return err(::PatternSyntax, macroCallBody) val separator = group.macroBindingGroupSeparator?.node?.firstChildNode macroCallBody.eof() // skip whitespace var mark: PsiBuilder.Marker? = macroCallBody.mark() while (true) { if (macroCallBody.eof()) { MacroExpansionMarks.GroupInputEnd1.hit() mark?.rollbackTo() break } val lastOffset = macroCallBody.currentOffset val result = pattern.matchPartial(macroCallBody) if (result is Ok) { if (macroCallBody.currentOffset == lastOffset) { MacroExpansionMarks.GroupMatchedEmptyTT.hit() return err(::EmptyGroup, macroCallBody) } groups += result.ok } else { MacroExpansionMarks.GroupInputEnd2.hit() mark?.rollbackTo() break } if (macroCallBody.eof()) { MacroExpansionMarks.GroupInputEnd3.hit() // Don't need to roll the marker back: we just successfully parsed a group break } if (group.q != null) { // `$(...)?` means "0 or 1 occurrences" MacroExpansionMarks.QuestionMarkGroupEnd.hit() break } mark?.drop() mark = macroCallBody.mark() if (separator != null) { if (!macroCallBody.isSameToken(separator)) { MacroExpansionMarks.FailMatchGroupBySeparator.hit() break } } } val isExpectedAtLeastOne = group.plus != null if (isExpectedAtLeastOne && groups.isEmpty()) { MacroExpansionMarks.FailMatchGroupTooFewElements.hit() return err(::TooFewGroupElements, macroCallBody) } return Ok(groups) } private fun <E> err( ctor: (offsetInCallBody: Int) -> E, macroCallBody: PsiBuilder ): Err<E> { return Err(ctor(macroCallBody.currentOffset)) } private fun <E, P1> err( ctor: (offsetInCallBody: Int, P1) -> E, macroCallBody: PsiBuilder, p1: P1 ): Err<E> { return Err(ctor(macroCallBody.currentOffset, p1)) } private fun <E, P1, P2> err( ctor: (offsetInCallBody: Int, P1, P2) -> E, macroCallBody: PsiBuilder, p1: P1, p2: P2 ): Err<E> { return Err(ctor(macroCallBody.currentOffset, p1, p2)) } companion object { fun valueOf(psi: RsMacroPatternContents?): MacroPattern = MacroPattern(psi?.node?.childrenSkipWhitespaceAndComments()?.flatten() ?: emptySequence()) private fun Sequence<ASTNode>.flatten(): Sequence<ASTNode> = flatMap { when (it.elementType) { MACRO_PATTERN, MACRO_PATTERN_CONTENTS -> it.childrenSkipWhitespaceAndComments().flatten() else -> sequenceOf(it) } } private fun ASTNode.childrenSkipWhitespaceAndComments(): Sequence<ASTNode> = generateSequence(firstChildNode) { it.treeNext } .filter { it.elementType != TokenType.WHITE_SPACE && it.elementType !in RS_COMMENTS } } } private val RsMacroCase.pattern: MacroPattern get() = MacroPattern.valueOf(macroPattern.macroPatternContents) private val COMPARE_BY_TEXT_TOKES = TokenSet.orSet(tokenSetOf(IDENTIFIER, QUOTE_IDENTIFIER), RS_LITERALS) fun PsiBuilder.isSameToken(node: ASTNode): Boolean { val (elementType, size) = collapsedTokenType(this) ?: (tokenType to 1) val result = node.elementType == elementType && (elementType !in COMPARE_BY_TEXT_TOKES || GeneratedParserUtilBase.nextTokenIsFast(this, node.text, true) == size) if (result) { PsiBuilderUtil.advance(this, size) } return result } object MacroExpansionMarks { object FailMatchPatternByToken : Testmark() object FailMatchPatternByExtraInput : Testmark() object FailMatchPatternByBindingType : Testmark() object FailMatchGroupBySeparator : Testmark() object FailMatchGroupTooFewElements : Testmark() object QuestionMarkGroupEnd : Testmark() object GroupInputEnd1 : Testmark() object GroupInputEnd2 : Testmark() object GroupInputEnd3 : Testmark() object GroupMatchedEmptyTT : Testmark() object SubstMetaVarNotFound : Testmark() object DocsLowering : Testmark() }
mit
7ed5042c1a8eb0448ffd00deb8c57a0e
40.140071
144
0.58139
4.660173
false
false
false
false
TakWolf/Android-HeaderAndFooterRecyclerView
app/src/main/java/com/takwolf/android/demo/hfrecyclerview/ui/activity/MultiRecyclerViewActivity.kt
1
2959
package com.takwolf.android.demo.hfrecyclerview.ui.activity import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.takwolf.android.demo.hfrecyclerview.databinding.ActivityMultiRecyclerViewBinding import com.takwolf.android.demo.hfrecyclerview.ui.adapter.LinearVerticalAdapter import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotoDeleteListener import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotosSwapListener import com.takwolf.android.demo.hfrecyclerview.vm.MultiListViewModel import com.takwolf.android.demo.hfrecyclerview.vm.holder.setupView class MultiRecyclerViewActivity : AppCompatActivity() { private val viewModel: MultiListViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMultiRecyclerViewBinding.inflate(layoutInflater) binding.toolbar.setNavigationOnClickListener { finish() } val recycledViewPool = RecyclerView.RecycledViewPool() binding.recyclerViewLeft.setRecycledViewPool(recycledViewPool) binding.recyclerViewLeft.layoutManager = LinearLayoutManager(this) viewModel.extraHolder1.setupVertical(layoutInflater, binding.recyclerViewLeft) val adapter1 = LinearVerticalAdapter(layoutInflater).apply { onPhotosSwapListener = OnPhotosSwapListener(viewModel.photosHolder1) onPhotoDeleteListener = OnPhotoDeleteListener(viewModel.photosHolder1) } binding.recyclerViewLeft.adapter = adapter1 viewModel.photosHolder1.setupView(this, adapter1) binding.recyclerViewRight.setRecycledViewPool(recycledViewPool) binding.recyclerViewRight.layoutManager = LinearLayoutManager(this) viewModel.extraHolder2.setupVertical(layoutInflater, binding.recyclerViewRight) val adapter2 = LinearVerticalAdapter(layoutInflater).apply { onPhotosSwapListener = OnPhotosSwapListener(viewModel.photosHolder2) onPhotoDeleteListener = OnPhotoDeleteListener(viewModel.photosHolder2) } binding.recyclerViewRight.adapter = adapter2 viewModel.photosHolder2.setupView(this, adapter2) binding.btnReplaceAdapters.setOnClickListener { val adapter = binding.recyclerViewLeft.adapter binding.recyclerViewLeft.adapter = binding.recyclerViewRight.adapter binding.recyclerViewRight.adapter = adapter } binding.btnSwapAdapters.setOnClickListener { val adapter = binding.recyclerViewLeft.adapter binding.recyclerViewLeft.swapAdapter(binding.recyclerViewRight.adapter, false) binding.recyclerViewRight.swapAdapter(adapter, false) } setContentView(binding.root) } }
apache-2.0
bfd6f3397f331dbd19c5553d8523803b
46.725806
91
0.772558
5.218695
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/helpers/MarkdownParser.kt
1
5102
package com.habitrpg.android.habitica.ui.helpers import android.content.Context import android.content.Intent import android.graphics.Rect import android.net.Uri import android.text.SpannableString import android.text.Spanned import android.text.method.LinkMovementMethod import android.widget.TextView import com.habitrpg.android.habitica.BuildConfig import com.habitrpg.android.habitica.extensions.handleUrlClicks import com.habitrpg.android.habitica.helpers.RxErrorHandler import io.noties.markwon.AbstractMarkwonPlugin import io.noties.markwon.Markwon import io.noties.markwon.MarkwonConfiguration import io.noties.markwon.MarkwonPlugin import io.noties.markwon.ext.strikethrough.StrikethroughPlugin import io.noties.markwon.image.ImageSize import io.noties.markwon.image.ImageSizeResolverDef import io.noties.markwon.image.ImagesPlugin import io.noties.markwon.image.file.FileSchemeHandler import io.noties.markwon.image.network.OkHttpNetworkSchemeHandler import io.noties.markwon.movement.MovementMethodPlugin import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.functions.Consumer import io.reactivex.rxjava3.schedulers.Schedulers object MarkdownParser { internal var markwon: Markwon? = null fun setup(context: Context) { markwon = Markwon.builder(context) .usePlugin(StrikethroughPlugin.create()) .usePlugin( ImagesPlugin.create { it.addSchemeHandler(OkHttpNetworkSchemeHandler.create()) .addSchemeHandler(FileSchemeHandler.createWithAssets(context.assets)) } ) .usePlugin(this.createImageSizeResolverScaleDpiPlugin(context)) .usePlugin(MovementMethodPlugin.create(LinkMovementMethod.getInstance())) .build() } /** * Custom markwon plugin to scale image size according to dpi */ private fun createImageSizeResolverScaleDpiPlugin(context: Context): MarkwonPlugin { return object : AbstractMarkwonPlugin() { override fun configureConfiguration(builder: MarkwonConfiguration.Builder) { builder.imageSizeResolver(object : ImageSizeResolverDef() { override fun resolveImageSize(imageSize: ImageSize?, imageBounds: Rect, canvasWidth: Int, textSize: Float): Rect { val dpi = context.resources.displayMetrics.density var width = imageBounds.width() if (dpi > 1) { width = (dpi * width.toFloat()).toInt() } if (width > canvasWidth) { width = canvasWidth } val ratio = imageBounds.width().toFloat() / imageBounds.height() val height = (width / ratio + .5f).toInt() return Rect(0, 0, width, height) } }) } } } /** * Parses formatted markdown and returns it as styled CharSequence * * @param input Markdown formatted String * @return Stylized CharSequence */ fun parseMarkdown(input: String?): Spanned { if (input == null) { return SpannableString("") } val text = EmojiParser.parseEmojis(input) ?: input // Adding this space here bc for some reason some markdown is not rendered correctly when the whole string is supposed to be formatted return markwon?.toMarkdown("$text ") ?: SpannableString(text) } fun parseMarkdownAsync(input: String?, onSuccess: Consumer<Spanned>) { Single.just(input ?: "") .map { this.parseMarkdown(it) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(onSuccess, RxErrorHandler.handleEmptyError()) } /** * Converts stylized CharSequence into markdown * * @param input Stylized CharSequence * @return Markdown formatted String */ fun parseCompiled(input: CharSequence): String? { return EmojiParser.convertToCheatCode(input.toString()) } } fun TextView.setMarkdown(input: String?) { MarkdownParser.markwon?.setParsedMarkdown(this, MarkdownParser.parseMarkdown(input)) this.handleUrlClicks { handleUrlClicks(this.context, it) } } fun TextView.setParsedMarkdown(input: Spanned?) { if (input != null) { MarkdownParser.markwon?.setParsedMarkdown(this, input) this.handleUrlClicks { handleUrlClicks(this.context, it) } } else { text = null } } private fun handleUrlClicks(context: Context, url: String) { val webpage = if (url.startsWith("/")) { Uri.parse("${BuildConfig.BASE_URL}$url") } else { Uri.parse(url) } val intent = Intent(Intent.ACTION_VIEW, webpage) if (intent.resolveActivity(context.packageManager) != null) { context.startActivity(intent) } }
gpl-3.0
d7f45392557c19c0f2aaf1cb2248f574
36.240876
142
0.658369
4.768224
false
false
false
false
androidx/androidx
metrics/metrics-performance/src/androidTest/java/androidx/metrics/performance/test/DelayedView.kt
3
1874
package androidx.metrics.performance.test import android.content.Context import android.graphics.Canvas import android.os.Build import android.util.AttributeSet import android.view.View import androidx.annotation.RequiresApi import androidx.metrics.performance.PerformanceMetricsState class DelayedView(context: Context?, attrs: AttributeSet?) : View(context, attrs) { var delayMs: Long = 0 var repetitions: Int = 0 var maxReps: Int = 0 var perFrameStateData: List<JankStatsTest.FrameStateInputData> = listOf() @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) override fun onDraw(canvas: Canvas?) { repetitions++ if (delayMs > 0) { try { Thread.sleep(delayMs) } catch (_: Exception) { } } val randomColor: Int = 0xff000000.toInt() or (((Math.random() * 127) + 128).toInt() shl 16) or (((Math.random() * 127) + 128).toInt() shl 8) or ((Math.random() * 127) + 128).toInt() canvas!!.drawColor(randomColor) if (perFrameStateData.isNotEmpty()) { val metricsState = PerformanceMetricsState.getHolderForHierarchy(this).state!! val stateData = perFrameStateData[repetitions - 1] for (state in stateData.addSFStates) { metricsState.putSingleFrameState(state.first, state.second) } for (state in stateData.addStates) { metricsState.putState(state.first, state.second) } for (stateName in stateData.removeStates) { metricsState.removeState(stateName) } } if (repetitions < maxReps) { if (Build.VERSION.SDK_INT >= 16) { postInvalidateOnAnimation() } else { postInvalidate() } } } }
apache-2.0
e68681d98ba6b18375432d557b76b41b
33.090909
90
0.598719
4.472554
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/TextFieldKeyInput.kt
3
11519
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text import androidx.compose.foundation.text.selection.BaseTextPreparedSelection.Companion.NoCharacterFound import androidx.compose.foundation.text.selection.TextFieldPreparedSelection import androidx.compose.foundation.text.selection.TextFieldSelectionManager import androidx.compose.foundation.text.selection.TextPreparedSelectionState import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.onKeyEvent import androidx.compose.ui.input.key.type import androidx.compose.ui.input.key.utf16CodePoint import androidx.compose.ui.text.input.CommitTextCommand import androidx.compose.ui.text.input.DeleteSurroundingTextCommand import androidx.compose.ui.text.input.EditCommand import androidx.compose.ui.text.input.FinishComposingTextCommand import androidx.compose.ui.text.input.OffsetMapping import androidx.compose.ui.text.input.TextFieldValue // AWT and Android have similar but different key event models. In android there are two main // types of events: ACTION_DOWN and ACTION_UP. In AWT there is additional KEY_TYPED which should // be used to get "typed character". By this simple function we are introducing common // denominator for both systems: if KeyEvent.isTypedEvent then it's safe to use // KeyEvent.utf16CodePoint internal expect val KeyEvent.isTypedEvent: Boolean /** * It handles [KeyEvent]s and either process them as typed events or maps to * [KeyCommand] via [KeyMapping]. [KeyCommand] then is executed * using utility class [TextFieldPreparedSelection] */ internal class TextFieldKeyInput( val state: TextFieldState, val selectionManager: TextFieldSelectionManager, val value: TextFieldValue = TextFieldValue(), val editable: Boolean = true, val singleLine: Boolean = false, val preparedSelectionState: TextPreparedSelectionState, val offsetMapping: OffsetMapping = OffsetMapping.Identity, val undoManager: UndoManager? = null, private val keyMapping: KeyMapping = platformDefaultKeyMapping, private val onValueChange: (TextFieldValue) -> Unit = {} ) { private fun List<EditCommand>.apply() { val newTextFieldValue = state.processor.apply( this.toMutableList().apply { add(0, FinishComposingTextCommand()) } ) onValueChange(newTextFieldValue) } private fun EditCommand.apply() { listOf(this).apply() } private fun typedCommand(event: KeyEvent): CommitTextCommand? = if (event.isTypedEvent) { val text = StringBuilder().appendCodePointX(event.utf16CodePoint) .toString() CommitTextCommand(text, 1) } else { null } fun process(event: KeyEvent): Boolean { typedCommand(event)?.let { return if (editable) { it.apply() preparedSelectionState.resetCachedX() true } else { false } } if (event.type != KeyEventType.KeyDown) { return false } val command = keyMapping.map(event) if (command == null || (command.editsText && !editable)) { return false } var consumed = true commandExecutionContext { when (command) { KeyCommand.COPY -> selectionManager.copy(false) // TODO(siyamed): cut & paste will cause a reset input KeyCommand.PASTE -> selectionManager.paste() KeyCommand.CUT -> selectionManager.cut() KeyCommand.LEFT_CHAR -> collapseLeftOr { moveCursorLeft() } KeyCommand.RIGHT_CHAR -> collapseRightOr { moveCursorRight() } KeyCommand.LEFT_WORD -> moveCursorLeftByWord() KeyCommand.RIGHT_WORD -> moveCursorRightByWord() KeyCommand.PREV_PARAGRAPH -> moveCursorPrevByParagraph() KeyCommand.NEXT_PARAGRAPH -> moveCursorNextByParagraph() KeyCommand.UP -> moveCursorUpByLine() KeyCommand.DOWN -> moveCursorDownByLine() KeyCommand.PAGE_UP -> moveCursorUpByPage() KeyCommand.PAGE_DOWN -> moveCursorDownByPage() KeyCommand.LINE_START -> moveCursorToLineStart() KeyCommand.LINE_END -> moveCursorToLineEnd() KeyCommand.LINE_LEFT -> moveCursorToLineLeftSide() KeyCommand.LINE_RIGHT -> moveCursorToLineRightSide() KeyCommand.HOME -> moveCursorToHome() KeyCommand.END -> moveCursorToEnd() KeyCommand.DELETE_PREV_CHAR -> deleteIfSelectedOr { DeleteSurroundingTextCommand( selection.end - getPrecedingCharacterIndex(), 0 ) }?.apply() KeyCommand.DELETE_NEXT_CHAR -> { // Note that some software keyboards, such as Samsungs, go through this code // path instead of making calls on the InputConnection directly. deleteIfSelectedOr { val nextCharacterIndex = getNextCharacterIndex() // If there's no next character, it means the cursor is at the end of the // text, and this should be a no-op. See b/199919707. if (nextCharacterIndex != NoCharacterFound) { DeleteSurroundingTextCommand(0, nextCharacterIndex - selection.end) } else { null } }?.apply() } KeyCommand.DELETE_PREV_WORD -> deleteIfSelectedOr { getPreviousWordOffset()?.let { DeleteSurroundingTextCommand(selection.end - it, 0) } }?.apply() KeyCommand.DELETE_NEXT_WORD -> deleteIfSelectedOr { getNextWordOffset()?.let { DeleteSurroundingTextCommand(0, it - selection.end) } }?.apply() KeyCommand.DELETE_FROM_LINE_START -> deleteIfSelectedOr { getLineStartByOffset()?.let { DeleteSurroundingTextCommand(selection.end - it, 0) } }?.apply() KeyCommand.DELETE_TO_LINE_END -> deleteIfSelectedOr { getLineEndByOffset()?.let { DeleteSurroundingTextCommand(0, it - selection.end) } }?.apply() KeyCommand.NEW_LINE -> if (!singleLine) { CommitTextCommand("\n", 1).apply() } else { consumed = false } KeyCommand.TAB -> if (!singleLine) { CommitTextCommand("\t", 1).apply() } else { consumed = false } KeyCommand.SELECT_ALL -> selectAll() KeyCommand.SELECT_LEFT_CHAR -> moveCursorLeft().selectMovement() KeyCommand.SELECT_RIGHT_CHAR -> moveCursorRight().selectMovement() KeyCommand.SELECT_LEFT_WORD -> moveCursorLeftByWord().selectMovement() KeyCommand.SELECT_RIGHT_WORD -> moveCursorRightByWord().selectMovement() KeyCommand.SELECT_PREV_PARAGRAPH -> moveCursorPrevByParagraph().selectMovement() KeyCommand.SELECT_NEXT_PARAGRAPH -> moveCursorNextByParagraph().selectMovement() KeyCommand.SELECT_LINE_START -> moveCursorToLineStart().selectMovement() KeyCommand.SELECT_LINE_END -> moveCursorToLineEnd().selectMovement() KeyCommand.SELECT_LINE_LEFT -> moveCursorToLineLeftSide().selectMovement() KeyCommand.SELECT_LINE_RIGHT -> moveCursorToLineRightSide().selectMovement() KeyCommand.SELECT_UP -> moveCursorUpByLine().selectMovement() KeyCommand.SELECT_DOWN -> moveCursorDownByLine().selectMovement() KeyCommand.SELECT_PAGE_UP -> moveCursorUpByPage().selectMovement() KeyCommand.SELECT_PAGE_DOWN -> moveCursorDownByPage().selectMovement() KeyCommand.SELECT_HOME -> moveCursorToHome().selectMovement() KeyCommand.SELECT_END -> moveCursorToEnd().selectMovement() KeyCommand.DESELECT -> deselect() KeyCommand.UNDO -> { undoManager?.makeSnapshot(value) undoManager?.undo()?.let { [email protected](it) } } KeyCommand.REDO -> { undoManager?.redo()?.let { [email protected](it) } } KeyCommand.CHARACTER_PALETTE -> { showCharacterPalette() } } } undoManager?.forceNextSnapshot() return consumed } private fun commandExecutionContext(block: TextFieldPreparedSelection.() -> Unit) { val preparedSelection = TextFieldPreparedSelection( currentValue = value, offsetMapping = offsetMapping, layoutResultProxy = state.layoutResult, state = preparedSelectionState ) block(preparedSelection) if (preparedSelection.selection != value.selection || preparedSelection.annotatedString != value.annotatedString ) { onValueChange(preparedSelection.value) } } } @Suppress("ModifierInspectorInfo") internal fun Modifier.textFieldKeyInput( state: TextFieldState, manager: TextFieldSelectionManager, value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit = {}, editable: Boolean, singleLine: Boolean, offsetMapping: OffsetMapping, undoManager: UndoManager ) = composed { val preparedSelectionState = remember { TextPreparedSelectionState() } val processor = TextFieldKeyInput( state = state, selectionManager = manager, value = value, editable = editable, singleLine = singleLine, offsetMapping = offsetMapping, preparedSelectionState = preparedSelectionState, undoManager = undoManager, onValueChange = onValueChange ) Modifier.onKeyEvent(processor::process) }
apache-2.0
3fad9e1fc8719abeba1551e1b2b097ba
43.996094
102
0.605261
5.191077
false
false
false
false
Ztiany/AndroidBase
lib_base/src/main/java/com/android/base/kotlin/AttrStyleEx.kt
1
1402
package com.android.base.kotlin import android.content.Context import android.content.ContextWrapper import android.content.res.TypedArray import android.support.annotation.AttrRes import android.support.annotation.StyleRes import android.util.TypedValue import android.view.ContextThemeWrapper import android.view.View /** 属性相关扩展:https://github.com/Kotlin/anko/issues/16*/ val View.contextThemeWrapper: ContextThemeWrapper get() = context.contextThemeWrapper val Context.contextThemeWrapper: ContextThemeWrapper get() = when (this) { is ContextThemeWrapper -> this is ContextWrapper -> baseContext.contextThemeWrapper else -> throw IllegalStateException("Context is not an Activity, can't get theme: $this") } @StyleRes fun View.attrStyle(@AttrRes attrColor: Int): Int = contextThemeWrapper.attrStyle(attrColor) @StyleRes private fun ContextThemeWrapper.attrStyle(@AttrRes attrRes: Int): Int = attr(attrRes) { it.getResourceId(0, 0) } private fun <R> ContextThemeWrapper.attr(@AttrRes attrRes: Int, block: (TypedArray)->R): R { val typedValue = TypedValue() if (!theme.resolveAttribute(attrRes, typedValue, true)) throw IllegalArgumentException("$attrRes is not resolvable") val a = obtainStyledAttributes(typedValue.data, intArrayOf(attrRes)) val result = block(a) a.recycle() return result }
apache-2.0
818d4ce1cb009560d2999766dcf6458c
35.526316
120
0.752882
4.535948
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/wizards/unitWizards.kt
1
2523
/******************************************************************************* * Copyright 2000-2016 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.wizards import org.eclipse.core.resources.IFile import org.eclipse.core.runtime.IPath import org.eclipse.jface.viewers.IStructuredSelection import org.eclipse.ui.IWorkbench import org.eclipse.ui.dialogs.WizardNewFileCreationPage import org.eclipse.ui.ide.IDE import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard import org.jetbrains.kotlin.parsing.KotlinParserDefinition class NewClassWizard : NewUnitWizard(WizardType.CLASS) class NewEnumWizard : NewUnitWizard(WizardType.ENUM) class NewObjectWizard : NewUnitWizard(WizardType.OBJECT) class NewInterfaceWizard : NewUnitWizard(WizardType.INTERFACE) class NewScriptWizard : BasicNewResourceWizard() { companion object { private const val pageName = "New Kotlin Script" } private lateinit var mainPage: WizardNewFileCreationPage override fun addPages() { super.addPages() mainPage = WizardNewFileCreationPage(pageName, getSelection()).apply { setFileExtension(KotlinParserDefinition.STD_SCRIPT_SUFFIX) setTitle("Kotlin Script") setDescription("Create a new Kotlin script") } addPage(mainPage) } override fun init(workbench: IWorkbench, currentSelection: IStructuredSelection) { super.init(workbench, currentSelection) setWindowTitle(pageName) } override fun performFinish(): Boolean { val file = mainPage.createNewFile() ?: return false selectAndReveal(file) workbench.activeWorkbenchWindow?.let { val page = it.activePage if (page != null) { IDE.openEditor(page, file, true) } } return true } }
apache-2.0
241feb784d073ad7f51daf7a318c6f51
35.057143
86
0.662703
4.715888
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/oauth/signpost/commonshttp/CommonsHttpOAuthProvider.kt
1
3085
/* * Copyright (c) 2009 Matthias Kaeppler 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 oauth.signpost.commonshttp import cz.msebera.android.httpclient.client.HttpClient import cz.msebera.android.httpclient.client.methods.HttpPost import cz.msebera.android.httpclient.client.methods.HttpUriRequest import cz.msebera.android.httpclient.impl.client.DefaultHttpClient import oauth.signpost.AbstractOAuthProvider import oauth.signpost.http.HttpRequest import oauth.signpost.http.HttpResponse import org.andstatus.app.util.MyLog import java.io.IOException /** * This implementation uses the Apache Commons [HttpClient] 4.x HTTP * implementation to fetch OAuth tokens from a service provider. Android users * should use this provider implementation in favor of the default one, since * the latter is known to cause problems with Android's Apache Harmony * underpinnings. * * @author Matthias Kaeppler */ class CommonsHttpOAuthProvider : AbstractOAuthProvider { @Transient private var httpClient: HttpClient constructor(requestTokenEndpointUrl: String?, accessTokenEndpointUrl: String?, authorizationWebsiteUrl: String?) : super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl) { httpClient = DefaultHttpClient() } constructor(requestTokenEndpointUrl: String?, accessTokenEndpointUrl: String?, authorizationWebsiteUrl: String?, httpClient: HttpClient) : super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl) { this.httpClient = httpClient } fun setHttpClient(httpClient: HttpClient) { this.httpClient = httpClient } override fun createRequest(endpointUrl: String?): HttpRequest { val request = HttpPost(endpointUrl) return HttpRequestAdapter(request) } override fun sendRequest(request: HttpRequest): HttpResponse { val response = httpClient.execute(request.unwrap() as HttpUriRequest) return HttpResponseAdapter(response) } override fun closeConnection(request: HttpRequest?, response: HttpResponse?) { if (response == null) return val entity = (response.unwrap() as cz.msebera.android.httpclient.HttpResponse).entity if (entity != null) { try { // free the connection entity.consumeContent() } catch (e: IOException) { MyLog.v(this, "HTTP keep-alive is not possible", e) } } } companion object { private const val serialVersionUID = 1L } }
apache-2.0
1380e5f5600f6f6749e3e7bbdfd69775
39.592105
157
0.729335
4.760802
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/stubs/LuaDocTagFieldStub.kt
2
4751
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.stubs import com.intellij.lang.ASTNode import com.intellij.psi.stubs.IndexSink import com.intellij.psi.stubs.StubElement import com.intellij.psi.stubs.StubInputStream import com.intellij.psi.stubs.StubOutputStream import com.intellij.util.BitUtil import com.intellij.util.io.StringRef import com.tang.intellij.lua.comment.LuaCommentUtil import com.tang.intellij.lua.comment.psi.LuaDocTagField import com.tang.intellij.lua.comment.psi.impl.LuaDocTagFieldImpl import com.tang.intellij.lua.psi.LuaElementType import com.tang.intellij.lua.psi.Visibility import com.tang.intellij.lua.stubs.index.LuaClassMemberIndex import com.tang.intellij.lua.stubs.index.StubKeys import com.tang.intellij.lua.ty.ITy import com.tang.intellij.lua.ty.Ty /** * Created by tangzx on 2016/12/10. */ class LuaDocTagFieldType : LuaStubElementType<LuaDocTagFieldStub, LuaDocTagField>("CLASS_DOC_FIELD") { override fun createPsi(stub: LuaDocTagFieldStub) = LuaDocTagFieldImpl(stub, this) override fun shouldCreateStub(node: ASTNode): Boolean { val element = node.psi as LuaDocTagField if (element.nameIdentifier == null) return false if (element.classNameRef != null) return true val comment = LuaCommentUtil.findContainer(element) return comment.tagClass != null } override fun createStub(tagField: LuaDocTagField, stubElement: StubElement<*>): LuaDocTagFieldStub { val name = tagField.name!! var className: String? = null val classRef = tagField.classNameRef if (classRef != null) { className = classRef.id.text } else { val comment = LuaCommentUtil.findContainer(tagField) val classDef = comment.tagClass if (classDef != null) { className = classDef.name } } var flags = BitUtil.set(0, tagField.visibility.bitMask, true) flags = BitUtil.set(flags, FLAG_DEPRECATED, tagField.isDeprecated) return LuaDocFieldDefStubImpl(stubElement, flags, name, className, tagField.ty?.getType() ?: Ty.UNKNOWN) } override fun serialize(stub: LuaDocTagFieldStub, stubOutputStream: StubOutputStream) { stubOutputStream.writeName(stub.name) stubOutputStream.writeName(stub.className) Ty.serialize(stub.type, stubOutputStream) stubOutputStream.writeShort(stub.flags) } override fun deserialize(stubInputStream: StubInputStream, stubElement: StubElement<*>): LuaDocTagFieldStub { val name = stubInputStream.readName() val className = stubInputStream.readName() val type = Ty.deserialize(stubInputStream) val flags = stubInputStream.readShort() return LuaDocFieldDefStubImpl(stubElement, flags.toInt(), StringRef.toString(name)!!, StringRef.toString(className)!!, type) } override fun indexStub(stub: LuaDocTagFieldStub, indexSink: IndexSink) { val className = stub.className className ?: return LuaClassMemberIndex.indexStub(indexSink, className, stub.name) indexSink.occurrence(StubKeys.SHORT_NAME, stub.name) } companion object { const val FLAG_DEPRECATED = 0x20 } } interface LuaDocTagFieldStub : LuaClassMemberStub<LuaDocTagField> { val name: String val type: ITy val className: String? val flags: Int } class LuaDocFieldDefStubImpl(parent: StubElement<*>, override val flags: Int, override val name: String, override val className: String?, override val type: ITy) : LuaDocStubBase<LuaDocTagField>(parent, LuaElementType.CLASS_FIELD_DEF), LuaDocTagFieldStub { override val docTy = type override val isDeprecated: Boolean get() = BitUtil.isSet(flags, LuaDocTagFieldType.FLAG_DEPRECATED) override val visibility: Visibility get() = Visibility.getWithMask(flags) }
apache-2.0
869c086a6070bca614e9550dcf809301
34.2
113
0.682593
4.456848
false
false
false
false
SiimKinks/sqlitemagic
sqlitemagic-tests/app-kotlin/src/main/kotlin/com/siimkinks/sqlitemagic/model/immutable/ComplexObject.kt
1
641
package com.siimkinks.sqlitemagic.model.immutable import com.siimkinks.sqlitemagic.annotation.Id import com.siimkinks.sqlitemagic.annotation.Table import com.siimkinks.sqlitemagic.annotation.Unique @Table data class ComplexObject( @Id val id: Long? = null, val number: String, val childObject: ChildObject? = null ) @Table data class ComplexObjectWithUniqueColumn( @Id val id: Long? = null, @Unique val externalId: String, val number: String, val childObject: ChildObject? = null ) @Table data class ChildObject( @Id val id: Long? = null, val address: String? = null, val comment: String? = null )
apache-2.0
89e807ddee744d974e01e539d3b77e4e
22.777778
50
0.728549
3.748538
false
false
false
false
xdtianyu/CallerInfo
app/src/main/java/org/xdty/callerinfo/model/setting/SettingImpl.kt
1
11595
package org.xdty.callerinfo.model.setting import android.content.Context import android.content.SharedPreferences import android.content.res.Resources import android.preference.PreferenceManager import androidx.annotation.StringRes import androidx.core.content.ContextCompat import com.google.gson.Gson import org.xdty.callerinfo.BuildConfig import org.xdty.callerinfo.R import org.xdty.callerinfo.model.Status import org.xdty.callerinfo.utils.Utils import java.util.* import kotlin.collections.ArrayList class SettingImpl private constructor() : Setting { private val mPrefs: SharedPreferences private val mWindowPrefs: SharedPreferences private var isOutgoing = false override val screenWidth: Int get() = Resources.getSystem().displayMetrics.widthPixels override val screenHeight: Int get() = Resources.getSystem().displayMetrics.heightPixels override val statusBarHeight: Int get() { var result = 0 val resourceId = sContext!!.resources .getIdentifier("status_bar_height", "dimen", "android") if (resourceId > 0) { result = sContext!!.resources.getDimensionPixelSize(resourceId) } return result } override val isEulaSet: Boolean get() = mPrefs.getBoolean("eula", false) override val windowHeight: Int get() = mPrefs.getInt(getString(R.string.window_height_key), defaultHeight) override val defaultHeight: Int get() = screenHeight / 8 override val isShowCloseAnim: Boolean get() = mPrefs.getBoolean(getString(R.string.window_close_anim_key), true) override val isTransBackOnly: Boolean get() = mPrefs.getBoolean(getString(R.string.window_trans_back_only_key), true) override val isEnableTextColor: Boolean get() = mPrefs.getBoolean(getString(R.string.window_text_color_key), false) override val textPadding: Int get() = mPrefs.getInt(getString(R.string.window_text_padding_key), 0) override val textAlignment: Int get() = mPrefs.getInt(getString(R.string.window_text_alignment_key), 1) override val textSize: Int get() = mPrefs.getInt(getString(R.string.window_text_size_key), 20) override val windowTransparent: Int get() = mPrefs.getInt(getString(R.string.window_transparent_key), 80) override val isDisableMove: Boolean get() = mPrefs.getBoolean(getString(R.string.disable_move_key), false) override val isAutoReportEnabled: Boolean get() = mPrefs.getBoolean(getString(R.string.auto_report_key), false) override val isMarkingEnabled: Boolean get() = mPrefs.getBoolean(getString(R.string.enable_marking_key), false) override fun addPaddingMark(number: String) { val key = getString(R.string.padding_mark_numbers_key) val list = paddingMarks if (list.contains(number)) { return } list.add(number) val paddingNumbers = gson.toJson(list) mPrefs.edit().putString(key, paddingNumbers).apply() } override fun removePaddingMark(number: String) { val key = getString(R.string.padding_mark_numbers_key) val list = paddingMarks if (!list.contains(number)) { return } list.remove(number) val paddingNumbers = gson.toJson(list) mPrefs.edit().putString(key, paddingNumbers).apply() } override val paddingMarks: ArrayList<String> get() { val key = getString(R.string.padding_mark_numbers_key) return if (mPrefs.contains(key)) { val paddingNumbers = mPrefs.getString(key, null) ArrayList( Arrays.asList(*gson.fromJson(paddingNumbers, Array<String>::class.java))) } else { ArrayList() } } override val uid: String get() { val key = getString(R.string.uid_key) return if (mPrefs.contains(key)) { mPrefs.getString(key, "")!! } else { val uid = Utils.getDeviceId(sContext!!) mPrefs.edit().putString(key, uid).apply() uid } } override fun updateLastScheduleTime() { updateLastScheduleTime(System.currentTimeMillis()) } override fun updateLastScheduleTime(timestamp: Long) { mPrefs.edit() .putLong(getString(R.string.last_schedule_time_key), timestamp) .apply() } override fun lastScheduleTime(): Long { return mPrefs.getLong(getString(R.string.last_schedule_time_key), 0) } override fun lastCheckDataUpdateTime(): Long { return mPrefs.getLong(getString(R.string.last_check_data_update_time_key), 0) } override fun updateLastCheckDataUpdateTime(timestamp: Long) { mPrefs.edit() .putLong(getString(R.string.last_check_data_update_time_key), timestamp) .apply() } override var status: Status get() = Status( mPrefs.getInt(getString(R.string.offline_status_version_key), 0), mPrefs.getInt(getString(R.string.offline_status_count_key), 0), mPrefs.getInt(getString(R.string.offline_status_new_count_key), 0), mPrefs.getLong(getString(R.string.offline_status_timestamp_key), 0), "", "" ) set(status) { mPrefs.edit().putInt(getString(R.string.offline_status_version_key), status.version).apply() mPrefs.edit().putInt(getString(R.string.offline_status_count_key), status.count).apply() mPrefs.edit().putInt(getString(R.string.offline_status_new_count_key), status.newCount).apply() mPrefs.edit().putLong(getString(R.string.offline_status_timestamp_key), status.timestamp).apply() } override val isNotMarkContact: Boolean get() = mPrefs.getBoolean(getString(R.string.not_mark_contact_key), false) override val isDisableOutGoingHangup: Boolean get() = mPrefs.getBoolean(getString(R.string.disable_outgoing_blacklist_key), false) override val isTemporaryDisableHangup: Boolean get() = mPrefs.getBoolean(getString(R.string.temporary_disable_blacklist_key), false) override val repeatedCountIndex: Int get() = mPrefs.getInt(getString(R.string.repeated_incoming_count_key), 1) override fun clear() { mPrefs.edit().clear().apply() mWindowPrefs.edit().clear().apply() } override val normalColor: Int get() = mPrefs.getInt("color_normal", ContextCompat.getColor(sContext!!, R.color.blue_light)) override val poiColor: Int get() = mPrefs.getInt("color_poi", ContextCompat.getColor(sContext!!, R.color.orange_dark)) override val reportColor: Int get() = mPrefs.getInt("color_report", ContextCompat.getColor(sContext!!, R.color.red_light)) override val isOnlyOffline: Boolean get() = mPrefs.getBoolean(sContext!!.getString(R.string.only_offline_key), false) override fun fix() { // fix api type because baidu api is dead val type = mPrefs.getInt(getString(R.string.api_type_key), 1) if (type == 0) { mPrefs.edit().remove(getString(R.string.api_type_key)).apply() } } override fun setOutgoing(isOutgoing: Boolean) { this.isOutgoing = isOutgoing } override val isOutgoingPositionEnabled: Boolean get() = mPrefs.getBoolean(getString(R.string.outgoing_window_position_key), false) override val isAddingRingOnceCallLog: Boolean get() = mPrefs.getBoolean(getString(R.string.ring_once_and_auto_hangup_key), false) override val isOfflineDataAutoUpgrade: Boolean get() = mPrefs.getBoolean(getString(R.string.offline_data_auto_upgrade_key), true) override val isHidingWhenTouch: Boolean get() = mPrefs.getBoolean(getString(R.string.hide_when_touch_key), false) override fun setEula() { val editor = mPrefs.edit() editor.putBoolean("eula", true) editor.putInt("eula_version", 1) editor.putInt("version", BuildConfig.VERSION_CODE) editor.apply() } override val ignoreRegex: String get() = mPrefs.getString(getString(R.string.ignore_regex_key), "")!!.replace("*", "[0-9]").replace(" ", "|") override val isHidingOffHook: Boolean get() = mPrefs.getBoolean(getString(R.string.hide_when_off_hook_key), false) override val isShowingOnOutgoing: Boolean get() = mPrefs.getBoolean(getString(R.string.display_on_outgoing_key), false) override val isIgnoreKnownContact: Boolean get() = mPrefs.getBoolean(getString(R.string.ignore_known_contact_key), false) override val isShowingContactOffline: Boolean get() = mPrefs.getBoolean(getString(R.string.contact_offline_key), false) override val isAutoHangup: Boolean get() = mPrefs.getBoolean(getString(R.string.auto_hangup_key), false) override val isAddingCallLog: Boolean get() = mPrefs.getBoolean(getString(R.string.add_call_log_key), false) override val isCatchCrash: Boolean get() = mPrefs.getBoolean(getString(R.string.catch_crash_key), false) override val isForceChinese: Boolean get() = mPrefs.getBoolean(getString(R.string.force_chinese_key), false) override val keywords: String get() { val keywordKey = getString(R.string.hangup_keyword_key) val keywordDefault = getString(R.string.hangup_keyword_default) var keywords = mPrefs.getString(keywordKey, keywordDefault)!!.trim { it <= ' ' } if (keywords.isEmpty()) { keywords = keywordDefault } return keywords } override val geoKeyword: String get() = mPrefs.getString(getString(R.string.hangup_geo_keyword_key), "")!!.trim { it <= ' ' } override val numberKeyword: String get() = mPrefs.getString(getString(R.string.hangup_number_keyword_key), "")!!.trim { it <= ' ' } override val windowX: Int get() { val prefix = if (isOutgoing && isOutgoingPositionEnabled) "out_" else "" return mWindowPrefs.getInt(prefix + "x", -1) } override val windowY: Int get() { val prefix = if (isOutgoing && isOutgoingPositionEnabled) "out_" else "" return mWindowPrefs.getInt(prefix + "y", -1) } override fun setWindow(x: Int, y: Int) { val prefix = if (isOutgoing && isOutgoingPositionEnabled) "out_" else "" val editor = mWindowPrefs.edit() editor.putInt(prefix + "x", x) editor.putInt(prefix + "y", y) editor.apply() } private fun getString(@StringRes resId: Int): String { return sContext!!.getString(resId) } private object SingletonHelper { val INSTANCE = SettingImpl() } companion object { private val gson = Gson() private var sContext: Context? = null fun init(context: Context) { sContext = context.applicationContext } val instance: Setting get() { checkNotNull(sContext) { "Setting is not initialized!" } return SingletonHelper.INSTANCE } } init { mPrefs = PreferenceManager.getDefaultSharedPreferences(sContext) mWindowPrefs = sContext!!.getSharedPreferences("window", Context.MODE_PRIVATE) } }
gpl-3.0
e1eb8b604b4385cf80852a5f3ee2df52
35.812698
109
0.643122
4.275442
false
false
false
false
PoweRGbg/AndroidAPS
app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtilsKtTest.kt
3
16968
package info.nightscout.androidaps.plugins.constraints.versionChecker import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.utils.SP import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers import org.mockito.Mockito.* import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class VersionCheckerUtilsKtTest { @Test fun `should keep 2 digit version`() { assertEquals("1.2", "1.2".numericVersionPart()) } @Test fun `should keep 3 digit version`() { assertEquals("1.2.3", "1.2.3".numericVersionPart()) } @Test fun `should keep 4 digit version`() { assertEquals("1.2.3.4", "1.2.3.4".numericVersionPart()) } @Test fun `should strip 2 digit version RC`() { assertEquals("1.2", "1.2-RC1".numericVersionPart()) } @Test fun `should strip 2 digit version RC old format`() { assertEquals("1.2", "1.2RC1".numericVersionPart()) } @Test fun `should strip 2 digit version RC without digit`() { assertEquals("1.2", "1.2-RC".numericVersionPart()) } @Test fun `should strip 2 digit version dev`() { assertEquals("1.2", "1.2-dev".numericVersionPart()) } @Test fun `should strip 2 digit version dev old format 1`() { assertEquals("1.2", "1.2dev".numericVersionPart()) } @Test fun `should strip 2 digit version dev old format 2`() { assertEquals("1.2", "1.2dev-a3".numericVersionPart()) } @Test fun `should strip 3 digit version RC`() { assertEquals("1.2.3", "1.2.3-RC1".numericVersionPart()) } @Test fun `should strip 4 digit version RC`() { assertEquals("1.2.3.4", "1.2.3.4-RC5".numericVersionPart()) } @Test fun `should strip even with dot`() { assertEquals("1.2", "1.2.RC5".numericVersionPart()) } @Test fun findVersionMatchesRegularVersion() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "2.2.2" | appName = "Aaoeu" """.trimMargin() val detectedVersion: String? = findVersion(buildGradle) assertEquals("2.2.2", detectedVersion) } // In case we merge a "x.x.x-dev" into master, don't see it as update. @Test fun `should return null on non-digit versions on master`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "2.2.2-nefarious-underground-mod" | appName = "Aaoeu" """.trimMargin() val detectedVersion: String? = findVersion(buildGradle) assertEquals(null, detectedVersion) } @Test fun findVersionMatchesDoesNotMatchErrorResponse() { val buildGradle = """<html><body>Balls! No build.gradle here. Move along</body><html>""" val detectedVersion: String? = findVersion(buildGradle) assertEquals(null, detectedVersion) } @Test fun testVersionStrip() { assertEquals("2.2.2", "2.2.2".versionStrip()) assertEquals("2.2.2", "2.2.2-dev".versionStrip()) assertEquals("2.2.2", "2.2.2dev".versionStrip()) assertEquals("2.2.2", """"2.2.2"""".versionStrip()) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update1`() { prepareMainApp() compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.2.1") //verify(bus, times(1)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update2`() { prepareMainApp() compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.2.1-dev") //verify(bus, times(1)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update3`() { prepareMainApp() compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.1") //verify(bus, times(1)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update4`() { prepareMainApp() compareWithCurrentVersion(newVersion = "2.2", currentVersion = "2.1.1") //verify(bus, times(1)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update5`() { prepareMainApp() compareWithCurrentVersion(newVersion = "2.2.1", currentVersion = "2.2-dev") //verify(bus, times(1)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update6`() { prepareMainApp() compareWithCurrentVersion(newVersion = "2.2.1", currentVersion = "2.2dev") //verify(bus, times(1)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should not find update on fourth version digit`() { prepareMainApp() compareWithCurrentVersion(newVersion = "2.5.0", currentVersion = "2.5.0.1") //verify(bus, times(0)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should not find update on personal version with same number` (){ prepareMainApp() compareWithCurrentVersion(newVersion = "2.5.0", currentVersion = "2.5.0-myversion") //verify(bus, times(0)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `find same version`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "2.2.2" | appName = "Aaoeu" """.trimMargin() prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.2.2") //verify(bus, times(0)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `find higher version`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "3.0.0" | appName = "Aaoeu" """.trimMargin() prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.2.2") PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `find higher version with longer number`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "3.0" | appName = "Aaoeu" """.trimMargin() prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.2.2") PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `find higher version after RC`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "3.0.0" | appName = "Aaoeu" """.trimMargin() prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "3.0-RC04") PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `find higher version after RC 2 - typo`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "3.0.0" | appName = "Aaoeu" """.trimMargin() prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "3.0RC04") PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `find higher version after RC 3 - typo`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "3.0.0" | appName = "Aaoeu" """.trimMargin() prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "3.RC04") PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `find higher version after RC 4 - typo`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "3.0.0" | appName = "Aaoeu" """.trimMargin() prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "3.0.RC04") PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `find higher version on multi digit numbers`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "3.7.12" | appName = "Aaoeu" """.trimMargin() prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "3.7.9") PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `don't find higher version on higher but shorter version`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "2.2.2" | appName = "Aaoeu" """.trimMargin() prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.3") //verify(bus, times(0)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `don't find higher version if on next RC`() { val buildGradle = """blabla | android { | aosenuthoae | } | version = "2.2.2" | appName = "Aaoeu" """.trimMargin() prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.3-RC") //verify(bus, times(0)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong()) PowerMockito.verifyNoMoreInteractions(SP::class.java) } @Test @PrepareForTest(System::class) fun `set time`() { PowerMockito.spy(System::class.java) PowerMockito.`when`(System.currentTimeMillis()).thenReturn(100L) assertEquals(100L, System.currentTimeMillis()) } private fun prepareMainApp() { PowerMockito.mockStatic(MainApp::class.java) val mainApp = mock<MainApp>(MainApp::class.java) `when`(MainApp.instance()).thenReturn(mainApp) `when`(MainApp.gs(ArgumentMatchers.anyInt())).thenReturn("some dummy string") prepareSP() } private fun prepareSP() { PowerMockito.mockStatic(SP::class.java) } private fun prepareLogging() { PowerMockito.mockStatic(L::class.java) `when`(L.isEnabled(any())).thenReturn(true) } }
agpl-3.0
4030e9d79a2c5b02bec61139e7c162f7
34.497908
96
0.623527
4.018948
false
true
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/storage/dao/VideoTimestampDaoImpl.kt
2
1644
package org.stepic.droid.storage.dao import android.content.ContentValues import android.database.Cursor import org.stepic.droid.storage.operations.DatabaseOperations import org.stepic.droid.storage.structure.DbStructureVideoTimestamp import org.stepik.android.cache.video_player.model.VideoTimestamp import javax.inject.Inject class VideoTimestampDaoImpl @Inject constructor(databaseOperations: DatabaseOperations) : DaoBase<VideoTimestamp>(databaseOperations) { public override fun getDbName() = DbStructureVideoTimestamp.VIDEO_TIMESTAMP public override fun getDefaultPrimaryColumn() = DbStructureVideoTimestamp.Column.VIDEO_ID public override fun getDefaultPrimaryValue(persistentObject: VideoTimestamp) = persistentObject.videoId.toString() public override fun getContentValues(persistentObject: VideoTimestamp): ContentValues { val contentValues = ContentValues() contentValues.put(DbStructureVideoTimestamp.Column.VIDEO_ID, persistentObject.videoId) contentValues.put(DbStructureVideoTimestamp.Column.TIMESTAMP, persistentObject.timestamp) return contentValues } public override fun parsePersistentObject(cursor: Cursor): VideoTimestamp { val indexVideoId = cursor.getColumnIndex(DbStructureVideoTimestamp.Column.VIDEO_ID) val indexTimestamp = cursor.getColumnIndex(DbStructureVideoTimestamp.Column.TIMESTAMP) val videoId: Long = cursor.getLong(indexVideoId) val timestamp: Long = cursor.getLong(indexTimestamp) return VideoTimestamp( videoId, timestamp ) } }
apache-2.0
205053cf4ef0f84882b0b86bc5221086
39.097561
135
0.76764
5.443709
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/remote/comment/CommentRemoteDataSourceImpl.kt
2
1888
package org.stepik.android.remote.comment import io.reactivex.Completable import io.reactivex.Single import io.reactivex.functions.Function import org.stepik.android.data.comment.source.CommentRemoteDataSource import org.stepik.android.domain.comment.model.CommentsData import org.stepik.android.model.comments.Comment import org.stepik.android.remote.comment.model.CommentRequest import org.stepik.android.remote.comment.model.CommentResponse import org.stepik.android.remote.comment.service.CommentService import javax.inject.Inject class CommentRemoteDataSourceImpl @Inject constructor( private val commentService: CommentService ) : CommentRemoteDataSource { private val commentResponseMapper = Function { response: CommentResponse -> CommentsData( comments = response.comments ?: emptyList(), users = response.users ?: emptyList(), votes = response.votes ?: emptyList(), attempts = response.attempts ?: emptyList(), submissions = response.submissions ?: emptyList() ) } override fun getComments(vararg commentIds: Long): Single<CommentsData> = if (commentIds.isEmpty()) { Single .just(CommentsData()) } else { commentService .getComments(commentIds) .map(commentResponseMapper) } override fun createComment(comment: Comment): Single<CommentsData> = commentService .createComment(CommentRequest(comment)) .map(commentResponseMapper) override fun saveComment(comment: Comment): Single<CommentsData> = commentService .saveComment(comment.id, CommentRequest(comment)) .map(commentResponseMapper) override fun removeComment(commentId: Long): Completable = commentService .removeComment(commentId) }
apache-2.0
f754212d32d17a7fe1fea1e7edc6700c
35.326923
79
0.697564
4.98153
false
false
false
false
Obaied/Dinger-kotlin
app/src/main/java/com/obaied/sohan/ui/quote/QuoteActivity.kt
1
4754
package com.joseph.sohan.ui.quote import android.Manifest import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.View import com.karumi.dexter.Dexter import com.karumi.dexter.PermissionToken import com.karumi.dexter.listener.PermissionDeniedResponse import com.karumi.dexter.listener.PermissionGrantedResponse import com.karumi.dexter.listener.PermissionRequest import com.karumi.dexter.listener.single.PermissionListener import com.joseph.sohan.R import com.joseph.sohan.data.model.Quote import com.joseph.sohan.ui.base.BaseActivity import com.joseph.sohan.util.e import kotlinx.android.synthetic.main.activity_quote.* import javax.inject.Inject class QuoteActivity : BaseActivity(), QuoteMvpView { @Inject lateinit var mPresenter: QuotePresenter private var quote: Quote? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_quote) activityComponent()?.inject(this) mPresenter.attachView(this) quote = intent.getParcelableExtra<Quote>(EXTRA_QUOTE) ?: throw IllegalArgumentException("Quote activity requires a quote instance") val imageTag: String? = intent.getStringExtra(EXTRA_IMAGE_TAG) val colorFilter: Int? = intent.getIntExtra(EXTRA_COLOR_FILTER, 0) quote_fap.setOnClickListener { if (quote != null) shareQuote() } fillQuote(quote!!, imageTag, colorFilter) } //TODO: put both takeScreenshot() and shareQuote() inside Presenter private fun takeScreenshot(): Bitmap { val view = window.decorView.rootView val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) view.draw(canvas) return bitmap } private fun shareQuote() { Dexter.withActivity(this) .withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) .withListener(object : PermissionListener { override fun onPermissionGranted(response: PermissionGrantedResponse) { quote_fap.visibility = View.GONE val bitmapPath = MediaStore.Images.Media.insertImage(contentResolver, takeScreenshot(), quote?.author, null) quote_fap.visibility = View.VISIBLE val bitmapUri = Uri.parse(bitmapPath) val intent = Intent() intent.action = Intent.ACTION_SEND intent.type = "image/*" intent.putExtra(Intent.EXTRA_STREAM, bitmapUri) startActivity(intent) } override fun onPermissionDenied(response: PermissionDeniedResponse) {/* ... */ e { "onPermissionDenied" } } override fun onPermissionRationaleShouldBeShown(permission: PermissionRequest, token: PermissionToken) {/* ... */ e { "onPermissionRationaleShouldBeShown" } } }).check() } private fun fillQuote(quote: Quote, imageTag: String?, colorFilter: Int?) { quote_textview_author.text = quote.author quote_textview_quote.text = quote.text // (colorFilter != 0).let { // quote_imageview_shade.setColorFilter(colorFilter) // quote_textview_quote.setTextColor(Colour.blackOrWhiteContrastingColor(colorFilter)) // } // imageTag?.let { // val (width, height) = DisplayMetricsUtil.getScreenMetrics() // Glide.with(this) // .load("https://unsplash.it/$width/$height/?image=$imageTag") // .diskCacheStrategy(DiskCacheStrategy.RESULT) // .crossFade() // .into(quote_imageview_cover) // } } companion object { val EXTRA_QUOTE = "com.joseph.sohan.ui.quote.EXTRA_QUOTE" val EXTRA_IMAGE_TAG = "com.joseph.sohan.ui.quote.EXTRA_IMAGE_TAG" val EXTRA_COLOR_FILTER = "com.joseph.sohan.ui.quote.EXTRA_COLOR_FILTER" fun getStartIntent(context: Context, quote: Quote): Intent { val intent = Intent(context, QuoteActivity::class.java) intent.putExtra(EXTRA_QUOTE, quote) // intent.putExtra(EXTRA_IMAGE_TAG, quote.imageTag!!) // intent.putExtra(EXTRA_COLOR_FILTER, quote.colorFilter!!) return intent } } }
mit
b726dd430796731fbf381455f3ebefb1
37.032
133
0.63252
4.611057
false
false
false
false
MarkNKamau/JustJava-Android
app/src/main/java/com/marknkamau/justjava/ui/productDetails/ProductDetailsActivity.kt
1
5159
package com.marknkamau.justjava.ui.productDetails import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.viewModels import androidx.core.app.ActivityOptionsCompat import androidx.core.util.Pair import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.marknjunge.core.data.model.Product import com.marknkamau.justjava.R import com.marknkamau.justjava.data.models.AppProduct import com.marknkamau.justjava.data.models.toAppModel import com.marknkamau.justjava.databinding.ActivityProductDetailsBinding import com.marknkamau.justjava.ui.base.BaseActivity import com.marknkamau.justjava.utils.CurrencyFormatter import com.marknkamau.justjava.utils.getStatusBarHeight import com.marknkamau.justjava.utils.replace import com.squareup.picasso.Picasso import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ProductDetailsActivity : BaseActivity() { companion object { private const val PRODUCT_KEY = "product_key" fun start(context: Context, product: Product, vararg sharedElements: Pair<View, String>) { val intent = Intent(context, ProductDetailsActivity::class.java) intent.putExtra(PRODUCT_KEY, product) val options = ActivityOptionsCompat.makeSceneTransitionAnimation( context as Activity, *sharedElements ) context.startActivity(intent, options.toBundle()) } } private lateinit var appProduct: AppProduct private var quantity = 1 private val productDetailsViewModel: ProductDetailsViewModel by viewModels() private lateinit var binding: ActivityProductDetailsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityProductDetailsBinding.inflate(layoutInflater) setContentView(binding.root) val product = intent.extras?.get(PRODUCT_KEY) as Product? ?: throw IllegalArgumentException("No product passed") appProduct = product.toAppModel() setProductDetails() val statusBarHeight = getStatusBarHeight() binding.imgBackDetail.layoutParams = (binding.imgBackDetail.layoutParams as ViewGroup.MarginLayoutParams).apply { topMargin = statusBarHeight } binding.imgBackDetail.setOnClickListener { finish() } binding.content.imgMinusQtyDetail.setOnClickListener { minusQty() } binding.content.imgAddQtyDetail.setOnClickListener { addQty() } binding.content.btnAddToCart.setOnClickListener { addToCart() } } private fun setProductDetails() { binding.content.tvProductName.text = appProduct.name binding.content.tvProductDescription.text = appProduct.description binding.content.tvProductPrice.text = resources.getString(R.string.price_listing, CurrencyFormatter.format(appProduct.price)) binding.content.tvSubtotalDetail.text = resources.getString(R.string.price_listing, CurrencyFormatter.format(appProduct.price)) binding.content.tvQuantityDetail.text = quantity.toString() Picasso.get().load(appProduct.image).noFade().into(binding.imgProductImage) appProduct.choices?.let { c -> // Use new object so that it is mutable var choices = c val choicesAdapter = ChoicesAdapter(this) binding.content.rvProductChoices.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false) binding.content.rvProductChoices.adapter = choicesAdapter choicesAdapter.setItems(choices.sortedBy { it.id }) choicesAdapter.onChoiceUpdated = { choice -> val existing = choices.first { it.id == choice.id } choices = choices.replace(existing, choice) appProduct.choices = choices updateTotal() } } updateTotal() } private fun addToCart() { val errors = appProduct.validate() if (errors.isNotEmpty()) { Toast.makeText( this, "You have not selected a choice for: ${errors.joinToString(", ")}", Toast.LENGTH_LONG ) .show() return } productDetailsViewModel.addItemToCart(appProduct, quantity).observe(this, { finish() }) } private fun addQty() { quantity += 1 binding.content.tvQuantityDetail.text = quantity.toString() updateTotal() } private fun minusQty() { if (quantity == 1) return quantity -= 1 binding.content.tvQuantityDetail.text = quantity.toString() updateTotal() } private fun updateTotal() { val total = appProduct.calculateTotal(quantity) binding.content.tvSubtotalDetail.text = getString(R.string.price_listing, CurrencyFormatter.format(total)) } }
apache-2.0
af2417ebb122eff0057b9ab4cef796d6
36.115108
120
0.691219
4.92271
false
false
false
false
da1z/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/launcher/GuiTestLocalLauncher.kt
1
16715
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.launcher import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.testGuiFramework.impl.GuiTestStarter import com.intellij.testGuiFramework.launcher.classpath.ClassPathBuilder import com.intellij.testGuiFramework.launcher.classpath.PathUtils import com.intellij.testGuiFramework.launcher.ide.CommunityIde import com.intellij.testGuiFramework.launcher.ide.Ide import com.intellij.testGuiFramework.launcher.system.SystemInfo import org.jetbrains.jps.model.JpsElementFactory import org.jetbrains.jps.model.JpsProject import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.jps.model.serialization.JpsProjectLoader import org.junit.Assert.fail import java.io.BufferedReader import java.io.File import java.io.InputStreamReader import java.lang.management.ManagementFactory import java.net.URL import java.nio.file.Paths import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.jar.JarInputStream import java.util.stream.Collectors import kotlin.concurrent.thread /** * @author Sergey Karashevich */ object GuiTestLocalLauncher { private val LOG = Logger.getInstance("#com.intellij.testGuiFramework.launcher.GuiTestLocalLauncher") var process: Process? = null private val TEST_GUI_FRAMEWORK_MODULE_NAME = "testGuiFramework" val project: JpsProject by lazy { val home = PathManager.getHomePath() val model = JpsElementFactory.getInstance().createModel() val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global) val jpsProject = model.project JpsProjectLoader.loadProject(jpsProject, pathVariables, home) jpsProject.changeOutputIfNeeded() jpsProject } private val modulesList: List<JpsModule> by lazy { project.modules } private val testGuiFrameworkModule: JpsModule by lazy { modulesList.module(TEST_GUI_FRAMEWORK_MODULE_NAME) ?: throw Exception("Unable to find module '$TEST_GUI_FRAMEWORK_MODULE_NAME'") } private fun killProcessIfPossible() { try { if (process?.isAlive == true) process!!.destroyForcibly() } catch (e: KotlinNullPointerException) { LOG.error("Seems that process has already destroyed, right after condition") } } fun runIdeLocally(ide: Ide = Ide(CommunityIde(), 0, 0), port: Int = 0, testClassNames: List<String> = emptyList()) { //todo: check that we are going to run test locally val args = createArgs(ide = ide, port = port, testClassNames = testClassNames) return startIde(ide = ide, args = args) } fun runIdeByPath(path: String, ide: Ide = Ide(CommunityIde(), 0, 0), port: Int = 0) { //todo: check that we are going to run test locally val args = createArgsByPath(path, port) return startIde(ide = ide, args = args) } fun firstStartIdeLocally(ide: Ide = Ide(CommunityIde(), 0, 0), firstStartClassName: String = "undefined") { val args = createArgsForFirstStart(ide = ide, firstStartClassName = firstStartClassName) return startIdeAndWait(ide = ide, args = args) } private fun startIde(ide: Ide, needToWait: Boolean = false, timeOut: Long = 0, timeOutUnit: TimeUnit = TimeUnit.SECONDS, args: List<String>) { LOG.info("Running $ide locally \n with args: $args") val startLatch = CountDownLatch(1) thread(start = true, name = "IdeaTestThread") { val ideaStartTest = ProcessBuilder().inheritIO().command(args) process = ideaStartTest.start() startLatch.countDown() } if (needToWait) { startLatch.await() if (timeOut != 0L) process!!.waitFor(timeOut, timeOutUnit) else process!!.waitFor() try { if (process!!.exitValue() == 0) { println("${ide.ideType} process completed successfully") LOG.info("${ide.ideType} process completed successfully") } else { System.err.println("${ide.ideType} process execution error:") val collectedError = BufferedReader(InputStreamReader(process!!.errorStream)).lines().collect(Collectors.joining("\n")) System.err.println(collectedError) LOG.error("${ide.ideType} process execution error:") LOG.error(collectedError) fail("Starting ${ide.ideType} failed.") } } catch (e: IllegalThreadStateException) { killProcessIfPossible() throw e } } } private fun startIdeAndWait(ide: Ide, args: List<String>) = startIde(ide = ide, needToWait = true, timeOut = 180, args = args) private fun createArgs(ide: Ide, mainClass: String = "com.intellij.idea.Main", port: Int = 0, testClassNames: List<String>): List<String> = createArgsBase(ide = ide, mainClass = mainClass, commandName = GuiTestStarter.COMMAND_NAME, port = port, testClassNames = testClassNames) private fun createArgsForFirstStart(ide: Ide, firstStartClassName: String = "undefined", port: Int = 0): List<String> = createArgsBase(ide = ide, mainClass = "com.intellij.testGuiFramework.impl.FirstStarterKt", firstStartClassName = firstStartClassName, commandName = null, port = port, testClassNames = emptyList()) /** * customVmOptions should contain a full VM options formatted items like: customVmOptions = listOf("-Dapple.laf.useScreenMenuBar=true", "-Dide.mac.file.chooser.native=false"). * GuiTestLocalLauncher passed all VM options from test, that starts with "-Dpass." */ private fun createArgsBase(ide: Ide, mainClass: String, commandName: String?, firstStartClassName: String = "undefined", port: Int, testClassNames: List<String>): List<String> { val customVmOptions = getCustomPassedOptions() var resultingArgs = listOf<String>() .plus(getCurrentJavaExec()) .plus(getDefaultAndCustomVmOptions(ide, customVmOptions)) .plus("-Didea.gui.test.first.start.class=$firstStartClassName") .plus("-classpath") .plus(getOsSpecificClasspath(ide.ideType.mainModule, testClassNames)) .plus(mainClass) if (commandName != null) resultingArgs = resultingArgs.plus(commandName) if (port != 0) resultingArgs = resultingArgs.plus("port=$port") LOG.info("Running with args: ${resultingArgs.joinToString(" ")}") return resultingArgs } private fun createArgsByPath(path: String, port: Int = 0): List<String> { val resultingArgs = mutableListOf( path, "--args", GuiTestStarter.COMMAND_NAME ) if (SystemInfo.isMac()) resultingArgs.add(0, "open") if (port != 0) resultingArgs.add("port=$port") LOG.info("Running with args: ${resultingArgs.joinToString(" ")}") return resultingArgs } private fun getCurrentProcessVmOptions(): List<String> { val runtimeMxBean = ManagementFactory.getRuntimeMXBean() return runtimeMxBean.inputArguments } private fun getPassedVmOptions(): List<String> { return getCurrentProcessVmOptions().filter { it.startsWith("-Dpass.") } } private fun getCustomPassedOptions(): List<String> { return getPassedVmOptions().map { it.replace("-Dpass.", "-D") } } /** * Default VM options to start IntelliJ IDEA (or IDEA-based IDE). To customize options use com.intellij.testGuiFramework.launcher.GuiTestOptions */ private fun getDefaultAndCustomVmOptions(ide: Ide, customVmOptions: List<String> = emptyList()): List<String> { return listOf<String>() .plus("-Xmx${GuiTestOptions.getXmxSize()}m") .plus("-XX:ReservedCodeCacheSize=240m") .plus("-XX:+UseConcMarkSweepGC") .plus("-XX:SoftRefLRUPolicyMSPerMB=50") .plus("-XX:MaxJavaStackTraceDepth=10000") .plus("-ea") .plus("-Xbootclasspath/p:${GuiTestOptions.getBootClasspath()}") .plus("-Dsun.awt.disablegrab=true") .plus("-Dsun.io.useCanonCaches=false") .plus("-Djava.net.preferIPv4Stack=true") .plus("-Dapple.laf.useScreenMenuBar=${GuiTestOptions.useAppleScreenMenuBar()}") .plus("-Didea.is.internal=${GuiTestOptions.isInternal()}") .plus("-Didea.debug.mode=true") .plus("-Didea.config.path=${GuiTestOptions.getConfigPath()}") .plus("-Didea.system.path=${GuiTestOptions.getSystemPath()}") .plus("-Dfile.encoding=${GuiTestOptions.getEncoding()}") .plus("-Didea.platform.prefix=${ide.ideType.platformPrefix}") .plus(customVmOptions) .plus("-Xdebug") .plus("-Xrunjdwp:transport=dt_socket,server=y,suspend=${GuiTestOptions.suspendDebug()},address=${GuiTestOptions.getDebugPort()}") .plus("-Duse.linux.keychain=false") } private fun getCurrentJavaExec(): String { return PathUtils.getJreBinPath() } private fun getOsSpecificClasspath(moduleName: String, testClassNames: List<String>): String = ClassPathBuilder.buildOsSpecific( getFullClasspath(moduleName, testClassNames).map { it.path }) /** * return union of classpaths for current test (get from classloader) and classpaths of main and testGuiFramework modules* */ private fun getFullClasspath(moduleName: String, testClassNames: List<String>): List<File> { val classpath: MutableSet<File> = substituteAllMacro(getExtendedClasspath(moduleName)) classpath.addAll(getTestClasspath(testClassNames)) classpath.add(getToolsJarFile()) return classpath.toList() } private fun getToolsJarFile(): File { val toolsJarUrl = getUrlPathsFromClassloader().firstOrNull { it.endsWith("/tools.jar") or it.endsWith("\\tools.jar") } ?: throw Exception("Unable to find tools.jar URL in the classloader URLs of ${GuiTestLocalLauncher::class.java.name} class") return File(toolsJarUrl) } /** * Finds in a current classpath that built from a test module dependencies resolved macro path * macroName = "\$MAVEN_REPOSITORY\$" */ private fun resolveMacro(classpath: MutableSet<File>, macroName: String): String { val pathWithMacro = classpath.firstOrNull { it.startsWith(macroName) }?.path ?: throw Exception( "Unable to find file in a classpath starting with next macro: '$macroName'") val tailOfPathWithMacro = pathWithMacro.substring(macroName.length) val urlPaths = getUrlPathsFromClassloader() val fullPathWithResolvedMacro = urlPaths.firstOrNull { it.endsWith(tailOfPathWithMacro) } ?: throw Exception( "Unable to find in classpath URL with the next tail: $tailOfPathWithMacro") return fullPathWithResolvedMacro.substring(0..(fullPathWithResolvedMacro.length - tailOfPathWithMacro.length)) } private fun substituteAllMacro(classpath: MutableSet<File>): MutableSet<File> { val macroList = listOf("\$MAVEN_REPOSITORY\$", "\$KOTLIN_BUNDLED\$") val macroMap = mutableMapOf<String, String>() macroList.forEach { macroMap.put(it, resolveMacro(classpath, it)) } val mutableClasspath = mutableListOf<File>() classpath.forEach { file -> val macro = file.path.findStartsWith(macroList) if (macro != null) { val resolvedMacro = macroMap.get(macro) val newPath = resolvedMacro + file.path.substring(macro.length + 1) mutableClasspath.add(File(newPath)) } else mutableClasspath.add(file) } return mutableClasspath.toMutableSet() } private fun String.findStartsWith(list: List<String>): String? { return list.find { this.startsWith(it) } } private fun getUrlPathsFromClassloader(): List<String> { val classLoader = this.javaClass.classLoader val urlClassLoaderClass = classLoader.javaClass val getUrlsMethod = urlClassLoaderClass.methods.firstOrNull { it.name.toLowerCase() == "geturls" }!! @Suppress("UNCHECKED_CAST") val urlsListOrArray = getUrlsMethod.invoke(classLoader) var urls = (urlsListOrArray as? List<*> ?: (urlsListOrArray as Array<*>).toList()).filterIsInstance(URL::class.java) if (SystemInfo.isWin()) { val classPathUrl = urls.find { it.toString().contains(Regex("classpath[\\d]*.jar")) } if (classPathUrl != null) { val jarStream = JarInputStream(File(classPathUrl.path).inputStream()) val mf = jarStream.manifest urls = mf.mainAttributes.getValue("Class-Path").split(" ").map { URL(it) } } } return urls.map { Paths.get(it.toURI()).toFile().path } } private fun getTestClasspath(testClassNames: List<String>): List<File> { if (testClassNames.isEmpty()) return emptyList() val fileSet = mutableSetOf<File>() testClassNames.forEach { fileSet.add(getClassFile(it)) } return fileSet.toList() } /** * returns a file (directory or a jar) containing class loaded by a class loader with a given name */ private fun getClassFile(className: String): File { val classLoader = this.javaClass.classLoader val cls = classLoader.loadClass(className) ?: throw Exception( "Unable to load class ($className) with a given classloader. Check the path to class or a classloader URLs.") val name = "${cls.simpleName}.class" val packagePath = cls.`package`.name.replace(".", "/") val fullPath = "$packagePath/$name" val resourceUrl = classLoader.getResource(fullPath) ?: throw Exception( "Unable to get resource path to a \"$fullPath\". Check the path to class or a classloader URLs.") var cutPath = resourceUrl.path.substring(0, resourceUrl.path.length - fullPath.length) if (cutPath.endsWith("!") or cutPath.endsWith("!/")) cutPath = cutPath.substring(0..(cutPath.length - 3)) // in case of it is a jar val file = File(cutPath) if (!file.exists()) throw Exception("File for a class '$className' doesn't exist by path: $cutPath") return file } /** * return union of classpaths for @moduleName and testGuiFramework modules */ private fun getExtendedClasspath(moduleName: String): MutableSet<File> { // here we trying to analyze output path for project from classloader path and from modules classpath. // If they didn't match than change it to output path from classpath val resultSet = LinkedHashSet<File>() val module = modulesList.module(moduleName) ?: throw Exception("Unable to find module with name: $moduleName") resultSet.addAll(module.getClasspath()) return resultSet } private fun List<JpsModule>.module(moduleName: String): JpsModule? = this.firstOrNull { it.name == moduleName } private fun JpsModule.getClasspath(): MutableCollection<File> = JpsJavaExtensionService.dependencies(this).productionOnly().runtimeOnly().recursively().classes().roots private fun getOutputRootFromClassloader(): File { val pathFromClassloader = PathManager.getJarPathForClass(GuiTestLocalLauncher::class.java) val productionDir = File(pathFromClassloader).parentFile assert(productionDir.isDirectory) val outputDir = productionDir.parentFile assert(outputDir.isDirectory) return outputDir } /** * @return true if classloader's output path is the same to module's output path (and also same to project) */ private fun needToChangeProjectOutput(project: JpsProject): Boolean = JpsJavaExtensionService.getInstance().getProjectExtension(project)?.outputUrl == getOutputRootFromClassloader().path private fun JpsProject.changeOutputIfNeeded() { if (!needToChangeProjectOutput(this)) { val projectExtension = JpsJavaExtensionService.getInstance().getOrCreateProjectExtension(this) projectExtension.outputUrl = VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(getOutputRootFromClassloader().path)) } } }
apache-2.0
ba5eccc8b0ddd3d879023b4049e0576a
41.861538
177
0.703201
4.683385
false
true
false
false
YasarTutuk/ReportingWebApp
src/main/kotlin/org/sample/homework/controller/LoginController.kt
1
1727
package org.sample.homework.controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController //import java.util.concurrent.atomic.AtomicLong import org.sample.homework.domain.LoginRequest import org.sample.homework.domain.LoginResponse import org.sample.homework.domain.TokenStatus import org.sample.homework.service.CommonClient import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import java.time.LocalDateTime import javax.servlet.http.HttpSession @RestController class LoginController(val client: CommonClient) { @Autowired private lateinit var token: TokenStatus // val counter = AtomicLong() @GetMapping("/login") fun login(session: HttpSession, @RequestParam(value = "email", defaultValue = "[email protected]") email: String, @RequestParam(value = "password", defaultValue = "cjaiU8CV") password: String): ResponseEntity<Any> { // counter.incrementAndGet() client.endPoint = "/merchant/user/login" val request = LoginRequest(email, password) val (response, error) = this.client.post(request, LoginResponse::class.java) return if (response != null) { session.setAttribute("token", response.token) session.setAttribute("validTo", LocalDateTime.now().plusMinutes(10)) token.value = response.token token.validTo = LocalDateTime.now().plusMinutes(10) ResponseEntity(response, HttpStatus.OK) } else ResponseEntity(error as Any, HttpStatus.OK) } }
unlicense
844cd2111129ad34106b696249d8e8ac
39.162791
117
0.743486
4.394402
false
false
false
false
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeSettingResponsePacket.kt
1
1393
package info.nightscout.androidaps.diaconn.packet import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import javax.inject.Inject /** * TimeSettingResponsePacket */ class TimeSettingResponsePacket( injector: HasAndroidInjector ) : DiaconnG8Packet(injector ) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump var result = 0 init { msgType = 0x8F.toByte() aapsLogger.debug(LTag.PUMPCOMM, "TimeSettingResponsePacket init ") } override fun handleMessage(data: ByteArray?) { val defectCheck = defect(data) if (defectCheck != 0) { aapsLogger.debug(LTag.PUMPCOMM, "TimeSettingResponsePacket Got some Error") failed = true return } else failed = false val bufferData = prefixDecode(data) result = getByteToInt(bufferData) if(!isSuccSettingResponseResult(result)) { diaconnG8Pump.resultErrorCode = result failed = true return } diaconnG8Pump.otpNumber = getIntToInt(bufferData) aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") } override fun getFriendlyName(): String { return "PUMP_TIME_SETTING_RESPONSE" } }
agpl-3.0
b51ec16c7a31c485971b7ce3c9a958b7
28.659574
87
0.673367
4.612583
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt
1
17867
package info.nightscout.androidaps.activities.fragments import android.annotation.SuppressLint import android.graphics.Paint import android.os.Bundle import android.util.SparseArray import android.view.* import androidx.core.util.forEach import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.fragments.TreatmentsProfileSwitchFragment.RecyclerProfileViewAdapter.ProfileSwitchViewHolder import info.nightscout.androidaps.data.ProfileSealed import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.database.transactions.InvalidateProfileSwitchTransaction import info.nightscout.androidaps.databinding.TreatmentsProfileswitchFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsProfileswitchItemBinding import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.events.EventEffectiveProfileSwitchChanged import info.nightscout.androidaps.events.EventProfileSwitchChanged import info.nightscout.androidaps.extensions.getCustomizedName import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged import info.nightscout.androidaps.utils.ActionModeHelper import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy import javax.inject.Inject class TreatmentsProfileSwitchFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var sp: SP @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var dateUtil: DateUtil @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var repository: AppRepository @Inject lateinit var uel: UserEntryLogger private var _binding: TreatmentsProfileswitchFragmentBinding? = null // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! private var menu: Menu? = null private lateinit var actionHelper: ActionModeHelper<ProfileSealed> private val disposable = CompositeDisposable() private val millsToThePast = T.days(30).msecs() private var showInvalidated = false override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = TreatmentsProfileswitchFragmentBinding.inflate(inflater, container, false).also { _binding = it }.root @SuppressLint("NotifyDataSetChanged") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) actionHelper = ActionModeHelper(rh, activity, this) actionHelper.setUpdateListHandler { binding.recyclerview.adapter?.notifyDataSetChanged() } actionHelper.setOnRemoveHandler { removeSelected(it) } setHasOptionsMenu(true) binding.recyclerview.setHasFixedSize(true) binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.recyclerview.emptyView = binding.noRecordsText binding.recyclerview.loadingView = binding.progressBar } private fun refreshFromNightscout() { activity?.let { activity -> OKDialog.showConfirmation(activity, rh.gs(R.string.refresheventsfromnightscout) + "?") { uel.log(Action.TREATMENTS_NS_REFRESH, Sources.Treatments) disposable += Completable.fromAction { repository.deleteAllEffectiveProfileSwitches() repository.deleteAllProfileSwitches() } .subscribeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.main) .subscribeBy( onError = { aapsLogger.error("Error removing entries", it) }, onComplete = { rxBus.send(EventProfileSwitchChanged()) rxBus.send(EventEffectiveProfileSwitchChanged(0L)) rxBus.send(EventNewHistoryData(0, false)) } ) rxBus.send(EventNSClientRestart()) } } } private fun profileSwitchWithInvalid(now: Long) = repository .getProfileSwitchDataIncludingInvalidFromTime(now - millsToThePast, false) .map { bolus -> bolus.map { ProfileSealed.PS(it) } } private fun effectiveProfileSwitchWithInvalid(now: Long) = repository .getEffectiveProfileSwitchDataIncludingInvalidFromTime(now - millsToThePast, false) .map { carb -> carb.map { ProfileSealed.EPS(it) } } private fun profileSwitches(now: Long) = repository .getProfileSwitchDataFromTime(now - millsToThePast, false) .map { bolus -> bolus.map { ProfileSealed.PS(it) } } private fun effectiveProfileSwitches(now: Long) = repository .getEffectiveProfileSwitchDataFromTime(now - millsToThePast, false) .map { carb -> carb.map { ProfileSealed.EPS(it) } } fun swapAdapter() { val now = System.currentTimeMillis() binding.recyclerview.isLoading = true disposable += if (showInvalidated) profileSwitchWithInvalid(now) .zipWith(effectiveProfileSwitchWithInvalid(now)) { first, second -> first + second } .map { ml -> ml.sortedByDescending { it.timestamp } } .observeOn(aapsSchedulers.main) .subscribe { list -> binding.recyclerview.swapAdapter(RecyclerProfileViewAdapter(list), true) } else profileSwitches(now) .zipWith(effectiveProfileSwitches(now)) { first, second -> first + second } .map { ml -> ml.sortedByDescending { it.timestamp } } .observeOn(aapsSchedulers.main) .subscribe { list -> binding.recyclerview.swapAdapter(RecyclerProfileViewAdapter(list), true) } } @Synchronized override fun onResume() { super.onResume() swapAdapter() disposable += rxBus .toObservable(EventProfileSwitchChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe({ swapAdapter() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventEffectiveProfileSwitchChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe({ swapAdapter() }, fabricPrivacy::logException) } @Synchronized override fun onPause() { super.onPause() actionHelper.finish() disposable.clear() } @Synchronized override fun onDestroyView() { super.onDestroyView() binding.recyclerview.adapter = null // avoid leaks _binding = null } inner class RecyclerProfileViewAdapter(private var profileSwitchList: List<ProfileSealed>) : RecyclerView.Adapter<ProfileSwitchViewHolder>() { override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ProfileSwitchViewHolder = ProfileSwitchViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.treatments_profileswitch_item, viewGroup, false)) override fun onBindViewHolder(holder: ProfileSwitchViewHolder, position: Int) { val profileSwitch = profileSwitchList[position] holder.binding.ph.visibility = (profileSwitch is ProfileSealed.EPS).toVisibility() holder.binding.ns.visibility = (profileSwitch.interfaceIDs_backing?.nightscoutId != null).toVisibility() val newDay = position == 0 || !dateUtil.isSameDayGroup(profileSwitch.timestamp, profileSwitchList[position - 1].timestamp) holder.binding.date.visibility = newDay.toVisibility() holder.binding.date.text = if (newDay) dateUtil.dateStringRelative(profileSwitch.timestamp, rh) else "" holder.binding.time.text = dateUtil.timeString(profileSwitch.timestamp) holder.binding.duration.text = rh.gs(R.string.format_mins, T.msecs(profileSwitch.duration ?: 0L).mins()) holder.binding.name.text = if (profileSwitch is ProfileSealed.PS) profileSwitch.value.getCustomizedName() else if (profileSwitch is ProfileSealed.EPS) profileSwitch.value.originalCustomizedName else "" if (profileSwitch.isInProgress(dateUtil)) holder.binding.date.setTextColor(rh.gac(context , R.attr.activeColor)) else holder.binding.date.setTextColor(holder.binding.duration.currentTextColor) holder.binding.clone.tag = profileSwitch holder.binding.name.tag = profileSwitch holder.binding.date.tag = profileSwitch holder.binding.invalid.visibility = profileSwitch.isValid.not().toVisibility() holder.binding.duration.visibility = (profileSwitch.duration != 0L && profileSwitch.duration != null).toVisibility() holder.binding.cbRemove.visibility = (actionHelper.isRemoving && profileSwitch is ProfileSealed.PS).toVisibility() if (actionHelper.isRemoving) { holder.binding.cbRemove.setOnCheckedChangeListener { _, value -> actionHelper.updateSelection(position, profileSwitch, value) } holder.binding.root.setOnClickListener { holder.binding.cbRemove.toggle() actionHelper.updateSelection(position, profileSwitch, holder.binding.cbRemove.isChecked) } holder.binding.cbRemove.isChecked = actionHelper.isSelected(position) } holder.binding.clone.visibility = (profileSwitch is ProfileSealed.PS).toVisibility() holder.binding.spacer.visibility = (profileSwitch is ProfileSealed.PS).toVisibility() } override fun getItemCount() = profileSwitchList.size inner class ProfileSwitchViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { val binding = TreatmentsProfileswitchItemBinding.bind(itemView) init { binding.clone.setOnClickListener { activity?.let { activity -> val profileSwitch = (it.tag as ProfileSealed.PS).value val profileSealed = it.tag as ProfileSealed OKDialog.showConfirmation( activity, rh.gs(R.string.careportal_profileswitch), rh.gs(R.string.copytolocalprofile) + "\n" + profileSwitch.getCustomizedName() + "\n" + dateUtil.dateAndTimeString(profileSwitch.timestamp), Runnable { uel.log( Action.PROFILE_SWITCH_CLONED, Sources.Treatments, profileSwitch.getCustomizedName() + " " + dateUtil.dateAndTimeString(profileSwitch.timestamp).replace(".", "_"), ValueWithUnit.Timestamp(profileSwitch.timestamp), ValueWithUnit.SimpleString(profileSwitch.profileName) ) val nonCustomized = profileSealed.convertToNonCustomizedProfile(dateUtil) localProfilePlugin.addProfile( localProfilePlugin.copyFrom( nonCustomized, profileSwitch.getCustomizedName() + " " + dateUtil.dateAndTimeString(profileSwitch.timestamp).replace(".", "_") ) ) rxBus.send(EventLocalProfileChanged()) }) } } binding.clone.paintFlags = binding.clone.paintFlags or Paint.UNDERLINE_TEXT_FLAG binding.name.setOnClickListener { ProfileViewerDialog().also { pvd -> pvd.arguments = Bundle().also { args -> args.putLong("time", (it.tag as ProfileSealed).timestamp) args.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal) } pvd.show(childFragmentManager, "ProfileViewDialog") } } binding.date.setOnClickListener { ProfileViewerDialog().also { pvd -> pvd.arguments = Bundle().also { args -> args.putLong("time", (it.tag as ProfileSealed).timestamp) args.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal) } pvd.show(childFragmentManager, "ProfileViewDialog") } } } } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { this.menu = menu inflater.inflate(R.menu.menu_treatments_profile_switch, menu) super.onCreateOptionsMenu(menu, inflater) } private fun updateMenuVisibility() { menu?.findItem(R.id.nav_hide_invalidated)?.isVisible = showInvalidated menu?.findItem(R.id.nav_show_invalidated)?.isVisible = !showInvalidated } override fun onPrepareOptionsMenu(menu: Menu) { updateMenuVisibility() val nsUploadOnly = !sp.getBoolean(R.string.key_ns_receive_profile_switch, false) || !buildHelper.isEngineeringMode() menu.findItem(R.id.nav_refresh_ns)?.isVisible = !nsUploadOnly return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.nav_remove_items -> actionHelper.startRemove() R.id.nav_show_invalidated -> { showInvalidated = true updateMenuVisibility() ToastUtils.showToastInUiThread(context, rh.gs(R.string.show_invalidated_records)) swapAdapter() true } R.id.nav_hide_invalidated -> { showInvalidated = false updateMenuVisibility() ToastUtils.showToastInUiThread(context, rh.gs(R.string.hide_invalidated_records)) swapAdapter() true } R.id.nav_refresh_ns -> { refreshFromNightscout() true } else -> false } private fun getConfirmationText(selectedItems: SparseArray<ProfileSealed>): String { if (selectedItems.size() == 1) { val profileSwitch = selectedItems.valueAt(0) return rh.gs(R.string.careportal_profileswitch) + ": " + profileSwitch.profileName + "\n" + rh.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(profileSwitch.timestamp) } return rh.gs(R.string.confirm_remove_multiple_items, selectedItems.size()) } private fun removeSelected(selectedItems: SparseArray<ProfileSealed>) { activity?.let { activity -> OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord), getConfirmationText(selectedItems), Runnable { selectedItems.forEach { _, profileSwitch -> uel.log( Action.PROFILE_SWITCH_REMOVED, Sources.Treatments, profileSwitch.profileName, ValueWithUnit.Timestamp(profileSwitch.timestamp) ) disposable += repository.runTransactionForResult(InvalidateProfileSwitchTransaction(profileSwitch.id)) .subscribe( { result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated ProfileSwitch $it") } }, { aapsLogger.error(LTag.DATABASE, "Error while invalidating ProfileSwitch", it) } ) } actionHelper.finish() }) } } }
agpl-3.0
6c5c581016dc8e2992b84a352878a6d4
50.341954
190
0.649857
5.396255
false
false
false
false
kvakil/venus
src/main/kotlin/venus/riscv/insts/dsl/BTypeInstruction.kt
1
746
package venus.riscv.insts.dsl import venus.riscv.insts.dsl.disasms.BTypeDisassembler import venus.riscv.insts.dsl.formats.BTypeFormat import venus.riscv.insts.dsl.impls.BTypeImplementation32 import venus.riscv.insts.dsl.impls.NoImplementation import venus.riscv.insts.dsl.parsers.BTypeParser class BTypeInstruction( name: String, opcode: Int, funct3: Int, cond32: (Int, Int) -> Boolean, cond64: (Long, Long) -> Boolean = { _, _ -> throw NotImplementedError("no rv64") } ) : Instruction( name = name, format = BTypeFormat(opcode, funct3), parser = BTypeParser, impl32 = BTypeImplementation32(cond32), impl64 = NoImplementation, disasm = BTypeDisassembler )
mit
50dd3c08277f44dac9d4d3f8d4ae32ff
32.909091
90
0.689008
3.674877
false
false
false
false
world-federation-of-advertisers/virtual-people-core-serving
src/main/kotlin/org/wfanet/virtualpeople/core/model/SparseUpdateMatrixImpl.kt
1
7182
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.virtualpeople.core.model import org.wfanet.virtualpeople.common.LabelerEvent import org.wfanet.virtualpeople.common.SparseUpdateMatrix import org.wfanet.virtualpeople.common.fieldfilter.FieldFilter import org.wfanet.virtualpeople.core.model.utils.* /** * ``` * A representation of update matrix, which only contains the entries that the * probabilities are not zero. * Example: * The following sparse update matrix * columns { * column_attrs { person_country_code: "COUNTRY_1" } * rows { person_country_code: "UPDATED_COUNTRY_1" } * rows { person_country_code: "UPDATED_COUNTRY_2" } * probabilities: 0.8 * probabilities: 0.2 * } * columns { * column_attrs { person_country_code: "COUNTRY_2" } * rows { person_country_code: "UPDATED_COUNTRY_1" } * rows { person_country_code: "UPDATED_COUNTRY_2" } * rows { person_country_code: "UPDATED_COUNTRY_3" } * probabilities: 0.2 * probabilities: 0.4 * probabilities: 0.4 * } * columns { * column_attrs { person_country_code: "COUNTRY_3" } * rows { person_country_code: "UPDATED_COUNTRY_3" } * probabilities: 1.0 * } * pass_through_non_matches: false * random_seed: "TestSeed" * represents the matrix * "COUNTRY_1" "COUNTRY_2" "COUNTRY_3" * "UPDATED_COUNTRY_1" 0.8 0.2 0 * "UPDATED_COUNTRY_2" 0.2 0.4 0 * "UPDATED_COUNTRY_3" 0 0.4 1.0 * The column is selected by the matched person_country_code, and the row is * selected by probabilities of the selected column. * ``` * * @param hashMatcher The matcher used to match input events to the column events when using hash * field mask. * @param filtersMatcher The matcher used to match input events to the column conditions when not * using hash field mask. * @param rowHashings Each entry of the list represents a hashing based on the probability * distribution of a column. The size of the list is the columns count. * @param randomSeed The seed used in hashing. * @param rows Each entry of the vector contains all the rows of the corresponding column. The * selected row will be merged to the input event. * @param passThroughNonMatches When calling Update, if no column matches, throws error if * passThroughNonMatches is [PassThroughNonMatches.NO]. */ internal class SparseUpdateMatrixImpl private constructor( private val hashMatcher: HashFieldMaskMatcher?, private val filtersMatcher: FieldFiltersMatcher?, private val rowHashings: List<DistributedConsistentHashing>, private val randomSeed: String, private val rows: List<List<LabelerEvent>>, private val passThroughNonMatches: PassThroughNonMatches ) : AttributesUpdaterInterface { /** * Updates [event] with selected row. The row is selected in 2 steps * 1. Select the column with [event] matches the condition. * 2. Use hashing to select the row based on the probability distribution of the column. * * Throws an error if no column matches [event], and [passThroughNonMatches] is * [PassThroughNonMatches.NO]. */ override fun update(event: LabelerEvent.Builder) { val indexes = selectFromMatrix(hashMatcher, filtersMatcher, rowHashings, randomSeed, event.build()) if (indexes.columnIndex == -1) { if (passThroughNonMatches == PassThroughNonMatches.YES) { return } else { error("No column matching for event: $event") } } if (indexes.rowIndex < 0 || indexes.rowIndex >= rows[indexes.columnIndex].size) { error("The returned row index is out of range.") } event.mergeFrom(rows[indexes.columnIndex][indexes.rowIndex]) return } internal companion object { /** * Always use [AttributesUpdaterInterface].build to get an [AttributesUpdaterInterface] object. * Users should not call the factory method or the constructor of the derived classes directly. * * Throws an error when any of the following happens: * 1. [config].columns is empty. * 2. [config].columns.column_attrs is not set. * 3. [config].columns.rows is empty. In any [config].columns, the counts of probabilities and * rows are not equal. * 4. Fails to build [FieldFilter] from any [config].columns.column_attrs. Fails to build * [DistributedConsistentHashing] from the probabilities distribution of any [config].columns. */ internal fun build(config: SparseUpdateMatrix): SparseUpdateMatrixImpl { if (config.columnsCount == 0) { error("No column exists in SparseUpdateMatrix: $config") } config.columnsList.forEach { column -> if (!column.hasColumnAttrs()) { error("No column_attrs in the column in SparseUpdateMatrix: $column") } if (column.rowsCount == 0) { error("No row exists in the column in SparseUpdateMatrix: $column") } if (column.rowsCount != column.probabilitiesCount) { error( "Rows and probabilities are not aligned in the column in SparseUpdateMatrix: $column" ) } } val hashMatcher: HashFieldMaskMatcher? = if (config.hasHashFieldMask()) { HashFieldMaskMatcher.build( config.columnsList.map { it.columnAttrs }, config.hashFieldMask ) } else { null } val filtersMatcher: FieldFiltersMatcher? = if (!config.hasHashFieldMask()) { FieldFiltersMatcher(config.columnsList.map { FieldFilter.create(it.columnAttrs) }) } else { null } /** Converts the probability distribution of each column to DistributedConsistentHashing. */ val rowHashings: List<DistributedConsistentHashing> = config.columnsList.map { column -> val distributionChoices = (0 until column.probabilitiesCount).map { DistributionChoice(it, column.getProbabilities(it).toDouble()) } DistributedConsistentHashing(distributionChoices) } val rows: List<List<LabelerEvent>> = config.columnsList.map { it.rowsList } val passThroughNonMatches = if (config.passThroughNonMatches) PassThroughNonMatches.YES else PassThroughNonMatches.NO return SparseUpdateMatrixImpl( hashMatcher, filtersMatcher, rowHashings, config.randomSeed, rows, passThroughNonMatches ) } } }
apache-2.0
eb1f58a6659155c01198df5e0ffbad9c
38.9
99
0.670287
4.275
false
true
false
false
jainsahab/AndroidSnooper
Snooper/src/main/java/com/prateekj/snooper/networksnooper/viewmodel/HttpCallViewModel.kt
1
1928
package com.prateekj.snooper.networksnooper.viewmodel import android.view.View.GONE import android.view.View.VISIBLE import androidx.annotation.ColorRes import com.prateekj.snooper.R import com.prateekj.snooper.networksnooper.model.HttpCallRecord import com.prateekj.snooper.networksnooper.model.HttpHeader import java.text.SimpleDateFormat import java.util.Locale.US class HttpCallViewModel(private val httpCall: HttpCallRecord) { val url: String? = httpCall.url val method: String? = httpCall.method val statusCode: String = httpCall.statusCode.toString() val statusText: String? = httpCall.statusText val requestHeaders: List<HttpHeader> = httpCall.requestHeaders ?: listOf() val responseHeaders: List<HttpHeader> = httpCall.responseHeaders ?: listOf() val timeStamp: String get() { val df = SimpleDateFormat(TIMESTAMP_FORMAT, US) return df.format(httpCall.date) } val responseInfoVisibility: Int = if (httpCall.hasError()) GONE else VISIBLE val failedTextVisibility: Int = if (httpCall.hasError()) VISIBLE else GONE val responseHeaderVisibility: Int = if (hasHeaders(httpCall.responseHeaders)) VISIBLE else GONE val requestHeaderVisibility: Int = if (hasHeaders(httpCall.requestHeaders)) VISIBLE else GONE @ColorRes fun getStatusColor(): Int { val statusCode = httpCall.statusCode return when { statusCode in RANGE_START_HTTP_OK..RANGE_END_HTTP_OK -> R.color.snooper_green statusCode <= RANGE_END_HTTP_REDIRECTION -> R.color.snooper_yellow else -> R.color.snooper_red } } private fun hasHeaders(headers: List<HttpHeader>?): Boolean { return headers != null && headers.isNotEmpty() } companion object { private const val TIMESTAMP_FORMAT = "MM/dd/yyyy HH:mm:ss" private const val RANGE_START_HTTP_OK = 200 private const val RANGE_END_HTTP_OK = 299 private const val RANGE_END_HTTP_REDIRECTION = 399 } }
apache-2.0
1bd389ddf5a6f69f01c9b2f3c33e14b2
31.133333
97
0.746888
4.191304
false
false
false
false
Adventech/sabbath-school-android-2
common/design-compose/src/main/kotlin/app/ss/design/compose/theme/Type.kt
1
4203
/* * Copyright (c) 2022. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.design.compose.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import app.ss.design.compose.R val LatoFontFamily = FontFamily( Font(R.font.lato_regular, FontWeight.Normal), Font(R.font.lato_medium, FontWeight.Medium), Font(R.font.lato_bold, FontWeight.Bold), Font(R.font.lato_black, FontWeight.Black) ) val SsTypography = Typography( displayLarge = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Bold, fontSize = 57.sp, lineHeight = 64.sp ), displayMedium = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Medium, fontSize = 45.sp, lineHeight = 52.sp ), displaySmall = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Normal, fontSize = 36.sp, lineHeight = 44.sp ), headlineLarge = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Bold, fontSize = 32.sp, lineHeight = 40.sp ), headlineMedium = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Bold, fontSize = 28.sp, lineHeight = 36.sp ), headlineSmall = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Bold, fontSize = 24.sp, lineHeight = 32.sp ), titleLarge = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Bold, fontSize = 20.sp, lineHeight = 26.sp ), titleMedium = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Medium, fontSize = 16.sp, lineHeight = 24.sp ), titleSmall = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Bold, fontSize = 14.sp, lineHeight = 20.sp ), labelLarge = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Medium, fontSize = 14.sp, lineHeight = 20.sp ), bodyLarge = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp ), bodyMedium = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Medium, fontSize = 14.sp, lineHeight = 20.sp ), bodySmall = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Normal, fontSize = 13.sp, lineHeight = 16.sp ), labelMedium = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Medium, fontSize = 17.sp, lineHeight = 16.sp ), labelSmall = TextStyle( fontFamily = LatoFontFamily, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp ) )
mit
32697ba3cf71cf18d7be6163586a8559
31.083969
80
0.656198
4.40566
false
false
false
false
square/wire
wire-library/wire-schema-tests/src/main/java/com/squareup/wire/SchemaBuilder.kt
1
2250
/* * Copyright 2022 Block Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire import com.squareup.wire.schema.Location import com.squareup.wire.schema.Schema import com.squareup.wire.schema.SchemaLoader import okio.FileSystem import okio.IOException import okio.Path import okio.Path.Companion.toPath import okio.fakefilesystem.FakeFileSystem /** Builds a schema out of written `.proto` files. */ class SchemaBuilder { private val sourcePath: Path = "/source".toPath() private val fileSystem: FileSystem = FakeFileSystem() init { fileSystem.createDirectories(sourcePath) } /** * Add a file to be loaded into the schema. * @param name The qualified name of the file. * @param protoFile The content of the file. */ fun add(name: Path, protoFile: String): SchemaBuilder { require(name.toString().endsWith(".proto")) { "unexpected file extension for $name. Proto files should use the '.proto' extension" } try { val resolvedPath = sourcePath / name val parent = resolvedPath.parent if (parent != null) { fileSystem.createDirectories(parent) } fileSystem.write(resolvedPath) { writeUtf8(protoFile) } } catch (e: IOException) { throw AssertionError(e) } return this } fun build(): Schema { val schemaLoader = SchemaLoader(fileSystem) schemaLoader.initRoots( sourcePath = listOf(Location.get(sourcePath.toString())), protoPath = listOf(), ) return schemaLoader.loadSchema() } } /** Builds a schema out of written `.proto` files. */ inline fun buildSchema(builderAction: SchemaBuilder.() -> Unit): Schema { return SchemaBuilder().apply(builderAction).build() }
apache-2.0
9cc285c8e62b9aae9ab6bbb4dbcaebf3
29.405405
90
0.706222
4.229323
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideMemberChooserObject.kt
1
16476
// 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.core.overrideImplement import com.intellij.codeInsight.generation.ClassMember import com.intellij.codeInsight.generation.MemberChooserObject import com.intellij.codeInsight.generation.MemberChooserObjectBase import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocCommentOwner import com.intellij.psi.PsiElement import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.TemplateKind import org.jetbrains.kotlin.idea.core.getFunctionBodyTextFromTemplate import org.jetbrains.kotlin.idea.core.overrideImplement.BodyType.* import org.jetbrains.kotlin.idea.core.util.DescriptorMemberChooserObject import org.jetbrains.kotlin.idea.j2k.IdeaDocCommentConverter import org.jetbrains.kotlin.idea.kdoc.KDocElementFactory import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.approximateFlexibleTypes import org.jetbrains.kotlin.idea.util.expectedDescriptors import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.findDocComment.findDocComment import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier import org.jetbrains.kotlin.renderer.ClassifierNamePolicy import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.renderer.DescriptorRenderer.Companion.withOptions import org.jetbrains.kotlin.renderer.DescriptorRendererModifier.* import org.jetbrains.kotlin.renderer.OverrideRenderingPolicy import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.checkers.ExplicitApiDeclarationChecker.Companion.explicitVisibilityIsNotRequired import org.jetbrains.kotlin.resolve.checkers.OptInNames import org.jetbrains.kotlin.resolve.checkers.explicitApiEnabled import org.jetbrains.kotlin.resolve.descriptorUtil.setSingleOverridden import org.jetbrains.kotlin.util.findCallableMemberBySignature interface OverrideMemberChooserObject : ClassMember { val descriptor: CallableMemberDescriptor val immediateSuper: CallableMemberDescriptor val bodyType: BodyType val preferConstructorParameter: Boolean companion object { fun create( project: Project, descriptor: CallableMemberDescriptor, immediateSuper: CallableMemberDescriptor, bodyType: BodyType, preferConstructorParameter: Boolean = false ): OverrideMemberChooserObject { val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) return if (declaration != null) { create(declaration, descriptor, immediateSuper, bodyType, preferConstructorParameter) } else { WithoutDeclaration(descriptor, immediateSuper, bodyType, preferConstructorParameter) } } fun create( declaration: PsiElement, descriptor: CallableMemberDescriptor, immediateSuper: CallableMemberDescriptor, bodyType: BodyType, preferConstructorParameter: Boolean = false ): OverrideMemberChooserObject = WithDeclaration(descriptor, declaration, immediateSuper, bodyType, preferConstructorParameter) private class WithDeclaration( descriptor: CallableMemberDescriptor, declaration: PsiElement, override val immediateSuper: CallableMemberDescriptor, override val bodyType: BodyType, override val preferConstructorParameter: Boolean ) : DescriptorMemberChooserObject(declaration, descriptor), OverrideMemberChooserObject { override val descriptor: CallableMemberDescriptor get() = super.descriptor as CallableMemberDescriptor } private class WithoutDeclaration( override val descriptor: CallableMemberDescriptor, override val immediateSuper: CallableMemberDescriptor, override val bodyType: BodyType, override val preferConstructorParameter: Boolean ) : MemberChooserObjectBase( DescriptorMemberChooserObject.getText(descriptor), DescriptorMemberChooserObject.getIcon(null, descriptor) ), OverrideMemberChooserObject { override fun getParentNodeDelegate(): MemberChooserObject? { val parentClassifier = descriptor.containingDeclaration as? ClassifierDescriptor ?: return null return MemberChooserObjectBase( DescriptorMemberChooserObject.getText(parentClassifier), DescriptorMemberChooserObject.getIcon(null, parentClassifier) ) } } } } fun OverrideMemberChooserObject.generateMember( targetClass: KtClassOrObject, copyDoc: Boolean ) = generateMember(targetClass, copyDoc, targetClass.project, mode = MemberGenerateMode.OVERRIDE) fun OverrideMemberChooserObject.generateMember( targetClass: KtClassOrObject?, copyDoc: Boolean, project: Project, mode: MemberGenerateMode ): KtCallableDeclaration { val descriptor = immediateSuper val bodyType = when { targetClass?.hasExpectModifier() == true -> NO_BODY descriptor.extensionReceiverParameter != null && mode == MemberGenerateMode.OVERRIDE -> FROM_TEMPLATE else -> bodyType } val baseRenderer = when (mode) { MemberGenerateMode.OVERRIDE -> OVERRIDE_RENDERER MemberGenerateMode.ACTUAL -> ACTUAL_RENDERER MemberGenerateMode.EXPECT -> EXPECT_RENDERER } val renderer = baseRenderer.withOptions { if (descriptor is ClassConstructorDescriptor && descriptor.isPrimary) { val containingClass = descriptor.containingDeclaration if (containingClass.kind == ClassKind.ANNOTATION_CLASS || containingClass.isInline || containingClass.isValue) { renderPrimaryConstructorParametersAsProperties = true } } if (MemberGenerateMode.OVERRIDE != mode) { val languageVersionSettings = targetClass?.module?.languageVersionSettings ?: project.languageVersionSettings if (languageVersionSettings.explicitApiEnabled && !explicitVisibilityIsNotRequired([email protected])) { renderDefaultVisibility = true } } } if (preferConstructorParameter && descriptor is PropertyDescriptor) { return generateConstructorParameter(project, descriptor, renderer, mode == MemberGenerateMode.OVERRIDE) } val newMember: KtCallableDeclaration = when (descriptor) { is FunctionDescriptor -> generateFunction(project, descriptor, renderer, bodyType, mode == MemberGenerateMode.OVERRIDE) is PropertyDescriptor -> generateProperty(project, descriptor, renderer, bodyType, mode == MemberGenerateMode.OVERRIDE) else -> error("Unknown member to override: $descriptor") } when (mode) { MemberGenerateMode.ACTUAL -> newMember.addModifier(KtTokens.ACTUAL_KEYWORD) MemberGenerateMode.EXPECT -> if (targetClass == null) { newMember.addModifier(KtTokens.EXPECT_KEYWORD) } MemberGenerateMode.OVERRIDE -> { if (targetClass?.hasActualModifier() == true) { val expectClassDescriptors = targetClass.resolveToDescriptorIfAny()?.expectedDescriptors()?.filterIsInstance<ClassDescriptor>().orEmpty() if (expectClassDescriptors.any { expectClassDescriptor -> val expectMemberDescriptor = expectClassDescriptor.findCallableMemberBySignature(immediateSuper) expectMemberDescriptor?.isExpect == true && expectMemberDescriptor.kind != CallableMemberDescriptor.Kind.FAKE_OVERRIDE } ) { newMember.addModifier(KtTokens.ACTUAL_KEYWORD) } } } } if (copyDoc) { val kDoc = when (val superDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor)?.navigationElement) { is KtDeclaration -> findDocComment(superDeclaration) is PsiDocCommentOwner -> { val kDocText = superDeclaration.docComment?.let { IdeaDocCommentConverter.convertDocComment(it) } if (kDocText.isNullOrEmpty()) null else KDocElementFactory(project).createKDocFromText(kDocText) } else -> null } if (kDoc != null) { newMember.addAfter(kDoc, null) } } return newMember } private val OVERRIDE_RENDERER = withOptions { defaultParameterValueRenderer = null modifiers = setOf(OVERRIDE, ANNOTATIONS) withDefinedIn = false classifierNamePolicy = ClassifierNamePolicy.SOURCE_CODE_QUALIFIED overrideRenderingPolicy = OverrideRenderingPolicy.RENDER_OVERRIDE unitReturnType = false enhancedTypes = true typeNormalizer = IdeDescriptorRenderers.APPROXIMATE_FLEXIBLE_TYPES renderUnabbreviatedType = false annotationFilter = { val annotations = it.type.constructor.declarationDescriptor?.annotations annotations != null && (annotations.hasAnnotation(OptInNames.REQUIRES_OPT_IN_FQ_NAME) || annotations.hasAnnotation(OptInNames.OLD_EXPERIMENTAL_FQ_NAME)) } presentableUnresolvedTypes = true informativeErrorType = false } private val EXPECT_RENDERER = OVERRIDE_RENDERER.withOptions { modifiers = setOf(VISIBILITY, MODALITY, OVERRIDE, INNER, MEMBER_KIND) renderConstructorKeyword = false secondaryConstructorsAsPrimary = false renderDefaultVisibility = false renderDefaultModality = false } private val ACTUAL_RENDERER = EXPECT_RENDERER.withOptions { modifiers = modifiers + ACTUAL actualPropertiesInPrimaryConstructor = true renderConstructorDelegation = true } private fun PropertyDescriptor.wrap(forceOverride: Boolean): PropertyDescriptor { val delegate = copy(containingDeclaration, if (forceOverride) Modality.OPEN else modality, visibility, kind, true) as PropertyDescriptor val newDescriptor = object : PropertyDescriptor by delegate { override fun isExpect() = false } if (forceOverride) { newDescriptor.setSingleOverridden(this) } return newDescriptor } private fun FunctionDescriptor.wrap(forceOverride: Boolean): FunctionDescriptor { if (this is ClassConstructorDescriptor) return this.wrap() return object : FunctionDescriptor by this { override fun isExpect() = false override fun getModality() = if (forceOverride) Modality.OPEN else [email protected] override fun getReturnType() = [email protected]?.approximateFlexibleTypes(preferNotNull = true, preferStarForRaw = true) override fun getOverriddenDescriptors() = if (forceOverride) listOf(this@wrap) else [email protected] override fun <R : Any?, D : Any?> accept(visitor: DeclarationDescriptorVisitor<R, D>, data: D) = visitor.visitFunctionDescriptor(this, data) } } private fun ClassConstructorDescriptor.wrap(): ClassConstructorDescriptor { return object : ClassConstructorDescriptor by this { override fun isExpect() = false override fun getModality() = Modality.FINAL override fun getReturnType() = [email protected](preferNotNull = true, preferStarForRaw = true) override fun getOverriddenDescriptors(): List<ClassConstructorDescriptor> = emptyList() override fun <R : Any?, D : Any?> accept(visitor: DeclarationDescriptorVisitor<R, D>, data: D) = visitor.visitConstructorDescriptor(this, data) } } private fun generateProperty( project: Project, descriptor: PropertyDescriptor, renderer: DescriptorRenderer, bodyType: BodyType, forceOverride: Boolean ): KtProperty { val newDescriptor = descriptor.wrap(forceOverride) val returnType = descriptor.returnType val returnsNotUnit = returnType != null && !KotlinBuiltIns.isUnit(returnType) val body = if (bodyType != NO_BODY) { buildString { append("\nget()") append(" = ") append(generateUnsupportedOrSuperCall(project, descriptor, bodyType, !returnsNotUnit)) if (descriptor.isVar) { append("\nset(value) {}") } } } else "" return KtPsiFactory(project).createProperty(renderer.render(newDescriptor) + body) } private fun generateConstructorParameter( project: Project, descriptor: PropertyDescriptor, renderer: DescriptorRenderer, forceOverride: Boolean ): KtParameter { val newDescriptor = descriptor.wrap(forceOverride) newDescriptor.setSingleOverridden(descriptor) return KtPsiFactory(project).createParameter(renderer.render(newDescriptor)) } private fun generateFunction( project: Project, descriptor: FunctionDescriptor, renderer: DescriptorRenderer, bodyType: BodyType, forceOverride: Boolean ): KtFunction { val newDescriptor = descriptor.wrap(forceOverride) val returnType = descriptor.returnType val returnsNotUnit = returnType != null && !KotlinBuiltIns.isUnit(returnType) val body = if (bodyType != NO_BODY) { val delegation = generateUnsupportedOrSuperCall(project, descriptor, bodyType, !returnsNotUnit) val returnPrefix = if (returnsNotUnit && bodyType.requiresReturn) "return " else "" "{$returnPrefix$delegation\n}" } else "" val factory = KtPsiFactory(project) val functionText = renderer.render(newDescriptor) + body return when (descriptor) { is ClassConstructorDescriptor -> { if (descriptor.isPrimary) { factory.createPrimaryConstructor(functionText) } else { factory.createSecondaryConstructor(functionText) } } else -> factory.createFunction(functionText) } } fun generateUnsupportedOrSuperCall( project: Project, descriptor: CallableMemberDescriptor, bodyType: BodyType, canBeEmpty: Boolean = true ): String { when (bodyType.effectiveBodyType(canBeEmpty)) { EMPTY_OR_TEMPLATE -> return "" FROM_TEMPLATE -> { val templateKind = if (descriptor is FunctionDescriptor) TemplateKind.FUNCTION else TemplateKind.PROPERTY_INITIALIZER return getFunctionBodyTextFromTemplate( project, templateKind, descriptor.name.asString(), descriptor.returnType?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } ?: "Unit", null ) } else -> return buildString { if (bodyType is Delegate) { append(bodyType.receiverName) } else { append("super") if (bodyType == QUALIFIED_SUPER) { val superClassFqName = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName( descriptor.containingDeclaration as ClassifierDescriptor ) append("<").append(superClassFqName).append(">") } } append(".").append(descriptor.name.render()) if (descriptor is FunctionDescriptor) { val paramTexts = descriptor.valueParameters.map { val renderedName = it.name.render() if (it.varargElementType != null) "*$renderedName" else renderedName } paramTexts.joinTo(this, prefix = "(", postfix = ")") } } } } fun KtModifierListOwner.makeNotActual() { removeModifier(KtTokens.ACTUAL_KEYWORD) removeModifier(KtTokens.IMPL_KEYWORD) } fun KtModifierListOwner.makeActual() { addModifier(KtTokens.ACTUAL_KEYWORD) }
apache-2.0
582a7a9aefe3327310d399e41ee427a4
42.13089
158
0.702962
5.532572
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/compiler-plugins/allopen/tests/test/TestAllOpenForLightClass.kt
3
2687
// 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.compilerPlugin.allopen.test import com.intellij.lang.jvm.JvmModifier import com.intellij.testFramework.LightProjectDescriptor import org.jetbrains.kotlin.allopen.AbstractAllOpenDeclarationAttributeAltererExtension import org.jetbrains.kotlin.idea.compilerPlugin.allopen.ALL_OPEN_ANNOTATION_OPTION_PREFIX import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.facet.KotlinFacet import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinProjectDescriptorWithFacet import org.jetbrains.kotlin.psi.KtFile import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class TestAllOpenForLightClass : KotlinLightCodeInsightFixtureTestCase() { companion object { val allOpenAnnotationName = AbstractAllOpenDeclarationAttributeAltererExtension.ANNOTATIONS_FOR_TESTS.first() const val targetClassName = "TargetClassName" } override fun getProjectDescriptor(): LightProjectDescriptor = KotlinProjectDescriptorWithFacet(KotlinPluginLayout.standaloneCompilerVersion.languageVersion, multiPlatform = false) override fun setUp() { super.setUp() val facet = KotlinFacet.get(module) ?: error { "Facet not found" } val configurationArguments = facet.configuration.settings.compilerArguments ?: error { "CompilerArguments not found" } configurationArguments.pluginClasspaths = arrayOf("SomeClasspath") configurationArguments.pluginOptions = arrayOf("$ALL_OPEN_ANNOTATION_OPTION_PREFIX$allOpenAnnotationName") } fun testAllOpenAnnotation() { val file = myFixture.configureByText( "A.kt", "annotation class $allOpenAnnotationName\n" + "@$allOpenAnnotationName class $targetClassName(val e: Int)\n {" + " fun a() {}\n" + " val b = 32\n" + "}" ) as KtFile val classes = file.classes assertEquals(2, classes.size) val targetClass = classes.firstOrNull { it.name == targetClassName } ?: error { "Expected class $targetClassName not found" } assertFalse(targetClass.hasModifier(JvmModifier.FINAL)) targetClass.methods .filter { !it.isConstructor } .forEach { assertFalse(it.hasModifier(JvmModifier.FINAL)) } } }
apache-2.0
193ff4e05cddaed7ea413b0c03e6baf6
41
158
0.722739
5.060264
false
true
false
false
theScrabi/NewPipe
app/src/main/java/org/schabi/newpipe/settings/custom/DurationListPreference.kt
3
1913
package org.schabi.newpipe.settings.custom import android.content.Context import android.util.AttributeSet import androidx.preference.ListPreference import org.schabi.newpipe.util.Localization /** * An extension of a common ListPreference where it sets the duration values to human readable strings. * * The values in the entry values array will be interpreted as seconds. If the value of a specific position * is less than or equals to zero, its original entry title will be used. * * If the entry values array have anything other than numbers in it, an exception will be raised. */ class DurationListPreference : ListPreference { constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?) : super(context) override fun onAttached() { super.onAttached() val originalEntryTitles = entries val originalEntryValues = entryValues val newEntryTitles = arrayOfNulls<CharSequence>(originalEntryValues.size) for (i in originalEntryValues.indices) { val currentDurationValue: Int try { currentDurationValue = (originalEntryValues[i] as String).toInt() } catch (e: NumberFormatException) { throw RuntimeException("Invalid number was set in the preference entry values array", e) } if (currentDurationValue <= 0) { newEntryTitles[i] = originalEntryTitles[i] } else { newEntryTitles[i] = Localization.localizeDuration(context, currentDurationValue) } } entries = newEntryTitles } }
gpl-3.0
df0feda40b7e866429bd32733aa666db
40.586957
144
0.695766
4.930412
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/functionalities/randomgenerators/GaussianDistributedRandom.kt
1
1420
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.functionalities.randomgenerators import java.util.* import kotlin.math.sqrt /** * A generator of random numbers with a Gaussian distribution. * * @property variance the variance of the distribution (e.g. 2.0 / n) * @property enablePseudoRandom whether to use a pseudo-random generation with the given [seed] * @property seed seed used for the pseudo-random generation */ class GaussianDistributedRandom( val variance: Double = 1.0, val enablePseudoRandom: Boolean = true, val seed: Long = 1 ) : RandomGenerator { companion object { /** * Private val used to serialize the class (needed by Serializable). */ @Suppress("unused") private const val serialVersionUID: Long = 1L } /** * A random numbers generator with a uniform distribution. */ private val rndGenerator = if (enablePseudoRandom) Random(seed) else Random() /** * @return a random value generated following a Gaussian distribution */ override fun next(): Double = rndGenerator.nextGaussian() * sqrt(variance) }
mpl-2.0
8df3d627deb1697760990194cf435c32
31.272727
95
0.684507
4.277108
false
false
false
false
spinnaker/orca
orca-sql/src/main/kotlin/com/netflix/spinnaker/orca/sql/cleanup/TopApplicationExecutionCleanupPollingNotificationAgent.kt
1
5766
/* * 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.sql.cleanup import com.netflix.spectator.api.Registry import com.netflix.spinnaker.config.OrcaSqlProperties import com.netflix.spinnaker.config.TopApplicationExecutionCleanupAgentConfigurationProperties import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType import com.netflix.spinnaker.orca.notifications.NotificationClusterLock import com.netflix.spinnaker.orca.notifications.scheduling.PipelineDependencyCleanupOperator import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import java.util.concurrent.atomic.AtomicInteger import org.jooq.DSLContext import org.jooq.impl.DSL import org.jooq.impl.DSL.name import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.stereotype.Component @Component @ConditionalOnExpression("\${pollers.top-application-execution-cleanup.enabled:false} && \${execution-repository.sql.enabled:false}") @EnableConfigurationProperties(TopApplicationExecutionCleanupAgentConfigurationProperties::class, OrcaSqlProperties::class) class TopApplicationExecutionCleanupPollingNotificationAgent( clusterLock: NotificationClusterLock, private val jooq: DSLContext, registry: Registry, private val executionRepository: ExecutionRepository, private val configurationProperties: TopApplicationExecutionCleanupAgentConfigurationProperties, private val orcaSqlProperties: OrcaSqlProperties, private val pipelineDependencyCleanupOperators: List<PipelineDependencyCleanupOperator> ) : AbstractCleanupPollingAgent( clusterLock, configurationProperties.intervalMs, registry ) { override fun performCleanup() { // We don't have an index on partition/application so a query on a given partition is very expensive. // Instead perform a query without partition constraint to get potential candidates. // Then use the results of this candidate query to perform partial queries with partition set val candidateApplicationGroups = jooq .select(DSL.field("application")) .from(DSL.table("orchestrations")) .groupBy(DSL.field("application")) .having(DSL.count(DSL.field("id")).gt(configurationProperties.threshold)) .fetch(DSL.field("application"), String::class.java) .groupBy { app -> configurationProperties.exceptionApplicationThresholds[app] ?: configurationProperties.threshold } candidateApplicationGroups.forEach { (thresholdToUse, candidateApplications) -> for (chunk in candidateApplications.chunked(5)) { val applicationsWithLotsOfOrchestrations = jooq .select(DSL.field("application")) .from(DSL.table("orchestrations")) .where( if (orcaSqlProperties.partitionName == null) { DSL.noCondition() } else { DSL.field(name("partition")).eq(orcaSqlProperties.partitionName) } ) .and(DSL.field("application").`in`(*chunk.toTypedArray())) .groupBy(DSL.field("application")) .having(DSL.count(DSL.field("id")).gt(thresholdToUse)) .fetch(DSL.field("application"), String::class.java) applicationsWithLotsOfOrchestrations .filter { !it.isNullOrEmpty() } .forEach { application -> try { val startTime = System.currentTimeMillis() log.debug("Cleaning up old orchestrations for $application") val deletedOrchestrationCount = performCleanup(application, thresholdToUse) log.debug( "Cleaned up {} old orchestrations for {} in {}ms", deletedOrchestrationCount, application, System.currentTimeMillis() - startTime ) } catch (e: Exception) { log.error("Failed to cleanup old orchestrations for $application", e) errorsCounter.increment() } } } } } /** * An application can have at most [threshold] completed orchestrations. */ private fun performCleanup(application: String, threshold: Int): Int { val deletedExecutionCount = AtomicInteger() val executionsToRemove = jooq .select(DSL.field("id")) .from(DSL.table("orchestrations")) .where( DSL.field("application").eq(application) .and(DSL.field("status").`in`(*completedStatuses.toTypedArray())) ) .orderBy(DSL.field("build_time").desc()) .limit(threshold, Int.MAX_VALUE) .fetch(DSL.field("id"), String::class.java) log.debug("Found {} old orchestrations for {}", executionsToRemove.size, application) pipelineDependencyCleanupOperators.forEach { it.cleanup(executionsToRemove) } executionsToRemove.chunked(configurationProperties.chunkSize).forEach { ids -> deletedExecutionCount.addAndGet(ids.size) executionRepository.delete(ExecutionType.ORCHESTRATION, ids) registry.counter(deletedId.withTag("application", application)).add(ids.size.toDouble()) } return deletedExecutionCount.toInt() } }
apache-2.0
e19d637ac0ce3afbc2836b83205abb58
41.711111
133
0.721124
4.722359
false
true
false
false
jsocle/jsocle-form
src/main/kotlin/com/github/jsocle/form/fields/MultipleSelectField.kt
2
671
package com.github.jsocle.form.fields import com.github.jsocle.form.Field import com.github.jsocle.form.FieldMapper import com.github.jsocle.html.elements.Select import kotlin.collections.forEach open class MultipleSelectField<T : Any>(var choices: List<Pair<T, String>>, defaults: List<T>, mapper: FieldMapper<T>) : Field<T, Select>(mapper, defaults) { override fun render(): Select { return Select(name = name, multiple = "multiple") { choices.forEach { option(value = mapper.toString(it.first), text_ = it.second, selected = if (it.first in values) "selected" else null) } } } }
mit
0eb5ac0c4671ba78a3f9e46d2ab26b70
36.333333
118
0.654247
3.707182
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/certificates/PluginCertificateManager.kt
2
7547
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins.certificates import com.intellij.ide.IdeBundle import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileTypeDescriptor import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.options.Configurable import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.IdeBorderFactory import com.intellij.ui.ToolbarDecorator import com.intellij.ui.components.JBScrollPane import com.intellij.ui.layout.* import com.intellij.ui.treeStructure.Tree import com.intellij.util.net.ssl.* import com.intellij.util.net.ssl.ConfirmingTrustManager.MutableTrustManager import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.CardLayout import java.security.cert.X509Certificate import javax.swing.JPanel import javax.swing.tree.TreeSelectionModel class PluginCertificateManager : BoundConfigurable( IdeBundle.message("plugin.manager.custom.certificates"), "plugin.certificates" ), Configurable.NoScroll, CertificateListener { private val myTree: Tree = Tree() private val myCertificatesListPanel: JPanel = panel { row { val decorator = ToolbarDecorator.createDecorator(myTree) .disableUpDownActions() .setAddAction { chooseFileAndAdd() } .setRemoveAction { removeSelectedCertificates() } .createPanel() decorator(growX) } } private val myDetailsPanel: JPanel = JPanel(CardLayout()) val myRootPanel = panel { row { myCertificatesListPanel() } row { myDetailsPanel(growX) } } private val myEmptyPanel = panel { row { label(IdeBundle.message("settings.certificate.no.certificate.selected")) } } private val CERTIFICATE_DESCRIPTOR = FileTypeDescriptor( IdeBundle.message("settings.certificate.choose.certificate"), ".crt", ".CRT", ".cer", ".CER", ".pem", ".PEM", ".der", ".DER" ) private val EMPTY_PANEL = "empty.panel" private val myTrustManager: MutableTrustManager = PluginCertificateStore.customTrustManager private val myTreeBuilder: CertificateTreeBuilder = CertificateTreeBuilder(myTree) private val myCertificates = mutableSetOf<X509Certificate>() override fun createPanel(): DialogPanel { init() return myRootPanel } override fun certificateAdded(certificate: X509Certificate) { UIUtil.invokeLaterIfNeeded { if (!myCertificates.contains(certificate)) { myCertificates.add(certificate) myTreeBuilder.addCertificate(certificate) addCertificatePanel(certificate) } } } override fun certificateRemoved(certificate: X509Certificate) { UIUtil.invokeLaterIfNeeded { if (myCertificates.contains(certificate)) { myCertificates.remove(certificate) myTreeBuilder.removeCertificate(certificate) } } } override fun isModified(): Boolean { return myCertificates != HashSet(myTrustManager.certificates) } @Throws(ConfigurationException::class) override fun apply() { val existing = myTrustManager.certificates val added = myCertificates - existing val removed = existing - myCertificates for (certificate in added) { if (!myTrustManager.addCertificate(certificate)) { throw ConfigurationException( IdeBundle.message( "settings.certificate.cannot.add.certificate.for", CertificateUtil.getCommonName(certificate) ), IdeBundle.message("settings.certificate.cannot.add.certificate")) } } for (certificate in removed) { if (!myTrustManager.removeCertificate(certificate)) { throw ConfigurationException( IdeBundle.message( "settings.certificate.cannot.remove.certificate.for", CertificateUtil.getCommonName(certificate) ), IdeBundle.message("settings.certificate.cannot.remove.certificate")) } } } override fun reset() { val original = myTrustManager.certificates myTreeBuilder.reset(original) myCertificates.clear() myCertificates.addAll(original) myDetailsPanel.removeAll() myDetailsPanel.add(myEmptyPanel, CertificateConfigurable.EMPTY_PANEL) // fill lower panel with cards for (certificate in original) { addCertificatePanel(certificate!!) } if (myCertificates.isNotEmpty()) { myTreeBuilder.selectFirstCertificate() } } override fun disposeUIResources() { Disposer.dispose(myTreeBuilder) myTrustManager.removeListener(this) } private fun init() { // show newly added certificates myTrustManager.addListener(this) myTree.emptyText.text = IdeBundle.message("settings.certificate.no.certificates") myTree.selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION myTree.isRootVisible = false myTree.addTreeSelectionListener { val certificate = myTreeBuilder.getFirstSelectedCertificate(true) if (certificate != null) { showCard(getCardName(certificate)) } } myCertificatesListPanel.border = IdeBorderFactory.createTitledBorder( IdeBundle.message("settings.trusted.certificates"), false, JBUI.insetsTop(8) ).setShowLine(false) } private fun chooseFileAndAdd() { FileChooser.chooseFile(CERTIFICATE_DESCRIPTOR, null, null) { file: VirtualFile -> val path = file.path val certificate = CertificateUtil.loadX509Certificate(path) when { certificate == null -> { Messages.showErrorDialog( myRootPanel, IdeBundle.message("settings.certificate.malformed.x509.server.certificate"), IdeBundle.message("settings.certificate.not.imported") ) } myCertificates.contains(certificate) -> { Messages.showWarningDialog( myRootPanel, IdeBundle.message("settings.certificate.certificate.already.exists"), IdeBundle.message("settings.certificate.not.imported") ) } else -> addCertificate(certificate) } } } private fun addCertificate(certificate: X509Certificate) { myCertificates.add(certificate) myTreeBuilder.addCertificate(certificate) addCertificatePanel(certificate) myTreeBuilder.selectCertificate(certificate) } private fun removeSelectedCertificates() { for (certificate in myTreeBuilder.getSelectedCertificates(true)) { myCertificates.remove(certificate) myTreeBuilder.removeCertificate(certificate) } if (myCertificates.isEmpty()) { showCard(EMPTY_PANEL) } else { myTreeBuilder.selectFirstCertificate() } } private fun showCard(cardName: String) { (myDetailsPanel.layout as CardLayout).show(myDetailsPanel, cardName) } private fun getCardName(certificate: X509Certificate): String = certificate.subjectX500Principal.name private fun addCertificatePanel(certificate: X509Certificate) { val uniqueName = getCardName(certificate) val infoPanel: JPanel = CertificateInfoPanel(certificate) UIUtil.addInsets(infoPanel, UIUtil.PANEL_REGULAR_INSETS) val scrollPane = JBScrollPane(infoPanel) myDetailsPanel.add(scrollPane, uniqueName) } }
apache-2.0
5357aa430d3945dc4210c7ccfdf8e340
32.105263
140
0.724394
4.859627
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/subscription/subscribe/SubscribeViewModel.kt
1
12718
package org.thoughtcrime.securesms.components.settings.app.subscription.subscribe import android.content.Intent import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.google.android.gms.wallet.PaymentData import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy import io.reactivex.rxjava3.subjects.PublishSubject import org.signal.core.util.logging.Log import org.signal.core.util.money.FiatMoney import org.signal.donations.GooglePayApi import org.thoughtcrime.securesms.components.settings.app.subscription.DonationEvent import org.thoughtcrime.securesms.components.settings.app.subscription.DonationPaymentRepository import org.thoughtcrime.securesms.components.settings.app.subscription.SubscriptionsRepository import org.thoughtcrime.securesms.components.settings.app.subscription.errors.DonationError import org.thoughtcrime.securesms.components.settings.app.subscription.errors.DonationErrorSource import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobs.MultiDeviceSubscriptionSyncRequestJob import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.subscription.LevelUpdate import org.thoughtcrime.securesms.subscription.Subscriber import org.thoughtcrime.securesms.subscription.Subscription import org.thoughtcrime.securesms.util.InternetConnectionObserver import org.thoughtcrime.securesms.util.PlatformCurrencyUtil import org.thoughtcrime.securesms.util.livedata.Store import org.whispersystems.signalservice.api.subscriptions.ActiveSubscription import org.whispersystems.signalservice.api.subscriptions.SubscriberId import java.util.Currency class SubscribeViewModel( private val subscriptionsRepository: SubscriptionsRepository, private val donationPaymentRepository: DonationPaymentRepository, private val fetchTokenRequestCode: Int ) : ViewModel() { private val store = Store(SubscribeState(currencySelection = SignalStore.donationsValues().getSubscriptionCurrency())) private val eventPublisher: PublishSubject<DonationEvent> = PublishSubject.create() private val disposables = CompositeDisposable() private val networkDisposable: Disposable val state: LiveData<SubscribeState> = store.stateLiveData val events: Observable<DonationEvent> = eventPublisher.observeOn(AndroidSchedulers.mainThread()) private var subscriptionToPurchase: Subscription? = null private val activeSubscriptionSubject = PublishSubject.create<ActiveSubscription>() init { networkDisposable = InternetConnectionObserver .observe() .distinctUntilChanged() .subscribe { isConnected -> if (isConnected) { retry() } } } override fun onCleared() { networkDisposable.dispose() disposables.dispose() } fun getPriceOfSelectedSubscription(): FiatMoney? { return store.state.selectedSubscription?.prices?.first { it.currency == store.state.currencySelection } } fun getSelectableCurrencyCodes(): List<String>? { return store.state.subscriptions.firstOrNull()?.prices?.map { it.currency.currencyCode } } fun retry() { if (!disposables.isDisposed && store.state.stage == SubscribeState.Stage.FAILURE) { store.update { it.copy(stage = SubscribeState.Stage.INIT) } refresh() } } fun refresh() { disposables.clear() val currency: Observable<Currency> = SignalStore.donationsValues().observableSubscriptionCurrency val allSubscriptions: Single<List<Subscription>> = subscriptionsRepository.getSubscriptions() refreshActiveSubscription() disposables += LevelUpdate.isProcessing.subscribeBy { store.update { state -> state.copy( hasInProgressSubscriptionTransaction = it ) } } disposables += allSubscriptions.subscribeBy( onSuccess = { subscriptions -> if (subscriptions.isNotEmpty()) { val priceCurrencies = subscriptions[0].prices.map { it.currency } val selectedCurrency = SignalStore.donationsValues().getSubscriptionCurrency() if (selectedCurrency !in priceCurrencies) { Log.w(TAG, "Unsupported currency selection. Defaulting to USD. $currency isn't supported.") val usd = PlatformCurrencyUtil.USD val newSubscriber = SignalStore.donationsValues().getSubscriber(usd) ?: Subscriber(SubscriberId.generate(), usd.currencyCode) SignalStore.donationsValues().setSubscriber(newSubscriber) donationPaymentRepository.scheduleSyncForAccountRecordChange() } } }, onError = {} ) disposables += Observable.combineLatest(allSubscriptions.toObservable(), activeSubscriptionSubject, ::Pair).subscribeBy( onNext = { (subs, active) -> store.update { it.copy( subscriptions = subs, selectedSubscription = it.selectedSubscription ?: resolveSelectedSubscription(active, subs), activeSubscription = active, stage = if (it.stage == SubscribeState.Stage.INIT || it.stage == SubscribeState.Stage.FAILURE) SubscribeState.Stage.READY else it.stage, ) } }, onError = this::handleSubscriptionDataLoadFailure ) disposables += currency.subscribe { selection -> store.update { it.copy(currencySelection = selection) } } } private fun handleSubscriptionDataLoadFailure(throwable: Throwable) { Log.w(TAG, "Could not load subscription data", throwable) store.update { it.copy(stage = SubscribeState.Stage.FAILURE) } } fun refreshActiveSubscription() { subscriptionsRepository .getActiveSubscription() .subscribeBy( onSuccess = { activeSubscriptionSubject.onNext(it) }, onError = { activeSubscriptionSubject.onNext(ActiveSubscription.EMPTY) } ) } private fun resolveSelectedSubscription(activeSubscription: ActiveSubscription, subscriptions: List<Subscription>): Subscription? { return if (activeSubscription.isActive) { subscriptions.firstOrNull { it.level == activeSubscription.activeSubscription.level } } else { subscriptions.firstOrNull() } } private fun cancelActiveSubscriptionIfNecessary(): Completable { return Single.just(SignalStore.donationsValues().shouldCancelSubscriptionBeforeNextSubscribeAttempt).flatMapCompletable { if (it) { donationPaymentRepository.cancelActiveSubscription().doOnComplete { SignalStore.donationsValues().updateLocalStateForManualCancellation() MultiDeviceSubscriptionSyncRequestJob.enqueue() } } else { Completable.complete() } } } fun cancel() { store.update { it.copy(stage = SubscribeState.Stage.CANCELLING) } disposables += donationPaymentRepository.cancelActiveSubscription().subscribeBy( onComplete = { eventPublisher.onNext(DonationEvent.SubscriptionCancelled) SignalStore.donationsValues().updateLocalStateForManualCancellation() refreshActiveSubscription() MultiDeviceSubscriptionSyncRequestJob.enqueue() donationPaymentRepository.scheduleSyncForAccountRecordChange() store.update { it.copy(stage = SubscribeState.Stage.READY) } }, onError = { throwable -> eventPublisher.onNext(DonationEvent.SubscriptionCancellationFailed(throwable)) store.update { it.copy(stage = SubscribeState.Stage.READY) } } ) } fun onActivityResult( requestCode: Int, resultCode: Int, data: Intent? ) { val subscription = subscriptionToPurchase subscriptionToPurchase = null donationPaymentRepository.onActivityResult( requestCode, resultCode, data, this.fetchTokenRequestCode, object : GooglePayApi.PaymentRequestCallback { override fun onSuccess(paymentData: PaymentData) { if (subscription != null) { eventPublisher.onNext(DonationEvent.RequestTokenSuccess) val ensureSubscriberId = donationPaymentRepository.ensureSubscriberId() val continueSetup = donationPaymentRepository.continueSubscriptionSetup(paymentData) val setLevel = donationPaymentRepository.setSubscriptionLevel(subscription.level.toString()) store.update { it.copy(stage = SubscribeState.Stage.PAYMENT_PIPELINE) } val setup = ensureSubscriberId .andThen(cancelActiveSubscriptionIfNecessary()) .andThen(continueSetup) .onErrorResumeNext { Completable.error(DonationError.getPaymentSetupError(DonationErrorSource.SUBSCRIPTION, it)) } setup.andThen(setLevel).subscribeBy( onError = { throwable -> refreshActiveSubscription() store.update { it.copy(stage = SubscribeState.Stage.READY) } val donationError: DonationError = if (throwable is DonationError) { throwable } else { Log.w(TAG, "Failed to complete payment or redemption", throwable, true) DonationError.genericBadgeRedemptionFailure(DonationErrorSource.SUBSCRIPTION) } DonationError.routeDonationError(ApplicationDependencies.getApplication(), donationError) }, onComplete = { store.update { it.copy(stage = SubscribeState.Stage.READY) } eventPublisher.onNext(DonationEvent.PaymentConfirmationSuccess(subscription.badge)) } ) } else { store.update { it.copy(stage = SubscribeState.Stage.READY) } } } override fun onError(googlePayException: GooglePayApi.GooglePayException) { store.update { it.copy(stage = SubscribeState.Stage.READY) } DonationError.routeDonationError(ApplicationDependencies.getApplication(), DonationError.getGooglePayRequestTokenError(DonationErrorSource.SUBSCRIPTION, googlePayException)) } override fun onCancelled() { store.update { it.copy(stage = SubscribeState.Stage.READY) } } } ) } fun updateSubscription() { store.update { it.copy(stage = SubscribeState.Stage.PAYMENT_PIPELINE) } cancelActiveSubscriptionIfNecessary().andThen(donationPaymentRepository.setSubscriptionLevel(store.state.selectedSubscription!!.level.toString())) .subscribeBy( onComplete = { store.update { it.copy(stage = SubscribeState.Stage.READY) } eventPublisher.onNext(DonationEvent.PaymentConfirmationSuccess(store.state.selectedSubscription!!.badge)) }, onError = { throwable -> store.update { it.copy(stage = SubscribeState.Stage.READY) } val donationError: DonationError = if (throwable is DonationError) { throwable } else { Log.w(TAG, "Failed to complete payment or redemption", throwable, true) DonationError.genericBadgeRedemptionFailure(DonationErrorSource.SUBSCRIPTION) } DonationError.routeDonationError(ApplicationDependencies.getApplication(), donationError) } ) } fun requestTokenFromGooglePay() { val snapshot = store.state if (snapshot.selectedSubscription == null) { return } store.update { it.copy(stage = SubscribeState.Stage.TOKEN_REQUEST) } val selectedCurrency = snapshot.currencySelection subscriptionToPurchase = snapshot.selectedSubscription donationPaymentRepository.requestTokenFromGooglePay(snapshot.selectedSubscription.prices.first { it.currency == selectedCurrency }, snapshot.selectedSubscription.name, fetchTokenRequestCode) } fun setSelectedSubscription(subscription: Subscription) { store.update { it.copy(selectedSubscription = subscription) } } class Factory( private val subscriptionsRepository: SubscriptionsRepository, private val donationPaymentRepository: DonationPaymentRepository, private val fetchTokenRequestCode: Int ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.cast(SubscribeViewModel(subscriptionsRepository, donationPaymentRepository, fetchTokenRequestCode))!! } } companion object { private val TAG = Log.tag(SubscribeViewModel::class.java) } }
gpl-3.0
273f938080b915f8656ef33e3466dd59
40.42671
194
0.729203
5.126159
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/conversation/colors/Colorizer.kt
1
1929
package org.thoughtcrime.securesms.conversation.colors import android.content.Context import android.graphics.Color import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId /** * Helper class for all things ChatColors. * * - Maintains a mapping for group recipient colors * - Gives easy access to different bubble colors * - Watches and responds to RecyclerView scroll and layout changes to update a ColorizerView */ class Colorizer { private var colorsHaveBeenSet = false private val groupSenderColors: MutableMap<RecipientId, NameColor> = mutableMapOf() @ColorInt fun getOutgoingBodyTextColor(context: Context): Int { return ContextCompat.getColor(context, R.color.white) } @ColorInt fun getOutgoingFooterTextColor(context: Context): Int { return ContextCompat.getColor(context, R.color.conversation_item_outgoing_footer_fg) } @ColorInt fun getOutgoingFooterIconColor(context: Context): Int { return ContextCompat.getColor(context, R.color.conversation_item_outgoing_footer_fg) } @ColorInt fun getIncomingGroupSenderColor(context: Context, recipient: Recipient): Int = groupSenderColors[recipient.id]?.getColor(context) ?: getDefaultColor(context, recipient.id) fun onNameColorsChanged(nameColorMap: Map<RecipientId, NameColor>) { groupSenderColors.clear() groupSenderColors.putAll(nameColorMap) colorsHaveBeenSet = true } @ColorInt private fun getDefaultColor(context: Context, recipientId: RecipientId): Int { return if (colorsHaveBeenSet) { val color = ChatColorsPalette.Names.all[groupSenderColors.size % ChatColorsPalette.Names.all.size] groupSenderColors[recipientId] = color return color.getColor(context) } else { Color.TRANSPARENT } } }
gpl-3.0
0278c398f3c57b1749440f1137651935
32.842105
173
0.77605
4.334831
false
false
false
false
emoji-gen/Emoji-Android
lib-slack/src/main/java/moe/pine/emoji/lib/slack/RegisterClient.kt
1
4348
package moe.pine.emoji.lib.slack import okhttp3.FormBody import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import org.jsoup.Connection import java.io.InputStream import java.io.OutputStream /** * RegisterClient * Created by pine on Apr 16, 2017. */ class RegisterClient { private data class InitialAccessResult( val isLoggedIn: Boolean, val signinFormData: List<Connection.KeyVal>?, val registerFormData: List<Connection.KeyVal>? ) private data class LoginResult( val isLoggedIn: Boolean, val registerFormData: List<Connection.KeyVal>? ) private val httpClient: HttpClient by lazy { HttpClient() } fun loadCookie(stream: InputStream) = this.httpClient.loadCookies(stream) fun saveCookie(stream: OutputStream) = this.httpClient.saveCookies(stream) fun register( team: String, email: String, password: String, emojiName: String, emojiUrl: String ): MessageResult { // Check login status val initialResult = this.tryInitialAccess(team) var loginResult: LoginResult? = null // Login if not logged in if (!initialResult.isLoggedIn) { initialResult.signinFormData ?: return MessageResult(false, "Login failed") loginResult = this.tryLogin(team, email, password, initialResult.signinFormData) if (!loginResult.isLoggedIn) return MessageResult(false, "Login failed") } // Fetch emoji image data val emojiBytes = this.fetchEmojiBytes(emojiUrl) // Send image data val registerFormData = initialResult.registerFormData ?: loginResult?.registerFormData registerFormData ?: return MessageResult(false, "Login failed") return this.tryRegister(team, emojiName, emojiBytes, registerFormData) } private fun tryInitialAccess(team: String): InitialAccessResult { val response = this.httpClient.doGetCustomizeEmoji(team) val body = response.body().string() val isLoggedIn = !HtmlParser.hasSigninForm(body) val signinFormData = HtmlParser.parseSigninFormData(body) val registerFormData = HtmlParser.parseRegisterFormData(body) return InitialAccessResult(isLoggedIn, signinFormData, registerFormData) } private fun tryLogin( team: String, email: String, password: String, signinFormData: List<Connection.KeyVal> ): LoginResult { val loginFormBody = FormBody.Builder().also { builder -> signinFormData.forEach { when (it.key()) { "email" -> builder.add(it.key(), email) "password" -> builder.add(it.key(), password) else -> builder.add(it.key(), it.value()) } } }.build() val response = this.httpClient.doPostSignin(team, loginFormBody) val body = response.body().string() val isLoggedIn = !HtmlParser.hasSigninForm(body) val registerFormData = HtmlParser.parseRegisterFormData(body) return LoginResult(isLoggedIn, registerFormData) } private fun tryRegister( team: String, emojiName: String, emojiBytes: ByteArray, registerFormData: List<Connection.KeyVal> ): MessageResult { val registerFormBody = MultipartBody.Builder().also { builder -> builder.setType(MultipartBody.FORM) registerFormData.forEach { when (it.key()) { "name" -> builder.addFormDataPart(it.key(), emojiName) "img" -> builder.addFormDataPart(it.key(), "emoji.png", RequestBody.create(MediaType.parse("image/png"), emojiBytes)) else -> builder.addFormDataPart(it.key(), it.value()) } } }.build() val registerResponse = this.httpClient.doPostCustomizeEmoji(team, registerFormBody) return HtmlParser.parseAlertMessage(registerResponse.body().string()) } private fun fetchEmojiBytes(emojiUrl: String): ByteArray { val response = this.httpClient.doGetEmojiImage(emojiUrl) return response.body().bytes() } }
mit
6c9ab6e596d0471faeb8e96d1e9bec94
36.17094
94
0.633165
4.841871
false
false
false
false
aerisweather/AerisAndroidSDK
Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/data/preferenceStore/Cache.kt
1
1601
package com.example.demoaerisproject.data.preferenceStore import java.time.Duration import java.time.ZonedDateTime object Cache { const val REQUEST_AIR_QUALITY = "air quality" const val REQUEST_MY_PLACE = "my place" const val REQUEST_LAT_LONG = "lat long" const val REQUEST_OVERVIEW = "overview" const val REQUEST_WEEKEND_FORECAST = "weekend forecast" const val REQUEST_EXT_FORECAST = "ext forecast" const val REQUEST_NEARBY_OBSERVATION = "nearby observation" const val REQUEST_DETAILED_OBSERVATION = "detailed observation" const val REQUEST_SUN_MOON = "sun moon" private var map = HashMap<String, Pair<ZonedDateTime, Any>?>() private val EXPIRE_IN_MINUTES = 10 private val MAX_COUNT = 10 fun isExpired(request: String): Boolean? { map[request]?.let { return Duration.between(it.first, ZonedDateTime.now()).toMinutes() > EXPIRE_IN_MINUTES } return null } fun remove(request: String) { map.remove(request) } /* * Insert or Update * - if too many, just dump all */ fun upsert(request:String, obj:Any) { if(map.size > MAX_COUNT) { map.clear() } map[request] = Pair<ZonedDateTime, Any>(ZonedDateTime.now(), obj) } /* * Call this to find request waiting for value * On Request -> (key, null) */ fun getLastRequestKey():List<String> { return map.filter{it.value == null}.keys.toList() } /* * Empty map at start and my_place change */ fun clear() { map.clear() } }
mit
89bdc30fbf25246837582cc2700a8322
27.105263
98
0.627108
3.953086
false
false
false
false
mdanielwork/intellij-community
python/tools/src/com/jetbrains/python/tools/BuildStubsForSdk.kt
1
4243
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.tools import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.openapi.application.PathManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileFilter import com.intellij.psi.stubs.PrebuiltStubsProviderBase.Companion.PREBUILT_INDICES_PATH_PROPERTY import com.intellij.psi.stubs.PrebuiltStubsProviderBase.Companion.SDK_STUBS_STORAGE_NAME import com.jetbrains.python.PythonFileType import com.jetbrains.python.PythonHelper import com.jetbrains.python.PythonModuleTypeBase import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.PyFileElementType import com.jetbrains.python.sdk.PythonSdkType import org.jetbrains.index.stubs.LanguageLevelAwareStubsGenerator import org.jetbrains.index.stubs.ProjectSdkStubsGenerator import org.jetbrains.index.stubs.mergeStubs import org.junit.Assert import java.io.File /** * @author traff */ const val stubsFileName: String = SDK_STUBS_STORAGE_NAME const val MERGE_STUBS_FROM_PATHS: String = "MERGE_STUBS_FROM_PATHS" const val PACK_STDLIB_FROM_PATH: String = "PACK_STDLIB_FROM_PATH" fun getBaseDirValue(): String? { val path: String? = System.getProperty(PREBUILT_INDICES_PATH_PROPERTY) if (path == null) { Assert.fail("$PREBUILT_INDICES_PATH_PROPERTY variable is not defined") } else { if (!File(path).exists()) { File(path).mkdirs() } return path } return null } val stubsVersion: String = PyFileElementType.INSTANCE.stubVersion.toString() fun main(args: Array<String>) { val baseDir = getBaseDirValue()!! if (System.getenv().containsKey(MERGE_STUBS_FROM_PATHS)) { mergeStubs(System.getenv(MERGE_STUBS_FROM_PATHS).split(File.pathSeparatorChar), baseDir, stubsFileName, "${PathManager.getHomePath()}/python/testData/empty", stubsVersion) } else if (System.getenv().containsKey(PACK_STDLIB_FROM_PATH)) { packStdlibFromPath(baseDir, System.getenv(PACK_STDLIB_FROM_PATH)) } else { PyProjectSdkStubsGenerator().buildStubs(baseDir) } } fun packStdlibFromPath(baseDir: String, root: String) { try { for (python in File(root).listFiles()) { if (python.name.startsWith(".")) { continue } val sdkHome = python.absolutePath val executable = File(PythonSdkType.getPythonExecutable(sdkHome) ?: throw AssertionError("No python on $sdkHome")) println("Packing stdlib of $sdkHome") val cph = CapturingProcessHandler(GeneralCommandLine(executable.absolutePath, PythonHelper.GENERATOR3.asParamString(), "-u", baseDir)) val output = cph.runProcess() println(output.stdout + output.stderr) } } finally { System.exit(0) } } class PyProjectSdkStubsGenerator : ProjectSdkStubsGenerator() { override val moduleTypeId: String get() = PythonModuleTypeBase.PYTHON_MODULE override fun createSdkProducer(sdkPath: String): (Project, Module) -> Sdk? = createPythonSdkProducer(sdkPath) override fun createStubsGenerator(stubsFilePath: String): PyStubsGenerator = PyStubsGenerator(stubsFilePath) override val root: String? get() = System.getenv(PYCHARM_PYTHONS) } class PyStubsGenerator(stubsStorageFilePath: String) : LanguageLevelAwareStubsGenerator<LanguageLevel>(PyFileElementType.INSTANCE.stubVersion.toString(), stubsStorageFilePath) { override fun defaultLanguageLevel(): LanguageLevel = LanguageLevel.getDefault() override fun languageLevelIterator(): MutableIterator<LanguageLevel> = LanguageLevel.SUPPORTED_LEVELS.iterator() override fun applyLanguageLevel(level: LanguageLevel) { LanguageLevel.FORCE_LANGUAGE_LEVEL = level } override val fileFilter: VirtualFileFilter get() = VirtualFileFilter { file: VirtualFile -> if (file.isDirectory && file.name == "parts") throw NoSuchElementException() else file.fileType == PythonFileType.INSTANCE } }
apache-2.0
99eaea0b02492818ee823a3bb2eaa3cc
32.409449
177
0.765732
4.27291
false
false
false
false
mdanielwork/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUVariable.kt
4
5877
/* * 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.uast.java import com.intellij.psi.* import com.intellij.psi.util.PsiTypesUtil import org.jetbrains.uast.* import org.jetbrains.uast.java.internal.JavaUElementWithComments abstract class AbstractJavaUVariable(givenParent: UElement?) : JavaAbstractUElement( givenParent), PsiVariable, UVariableEx, JavaUElementWithComments, UAnchorOwner { abstract override val javaPsi: PsiVariable @Suppress("unused") // Used in Kotlin 1.1.4, to be removed in 2018.1 @Deprecated("use AbstractJavaUVariable(givenParent) instead", ReplaceWith("AbstractJavaUVariable(givenParent)")) constructor() : this(null) override val uastInitializer: UExpression? by lz { val initializer = psi.initializer ?: return@lz null getLanguagePlugin().convertElement(initializer, this) as? UExpression } override val annotations: List<JavaUAnnotation> by lz { psi.annotations.map { JavaUAnnotation(it, this) } } override val typeReference: UTypeReferenceExpression? by lz { getLanguagePlugin().convertOpt<UTypeReferenceExpression>(psi.typeElement, this) } override val uastAnchor: UIdentifier get() = UIdentifier(psi.nameIdentifier, this) override fun equals(other: Any?): Boolean = other is AbstractJavaUVariable && psi == other.psi override fun hashCode(): Int = psi.hashCode() } open class JavaUVariable( psi: PsiVariable, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UVariableEx, PsiVariable by psi { override val psi: PsiVariable get() = javaPsi override val javaPsi: PsiVariable = unwrap<UVariable, PsiVariable>(psi) companion object { fun create(psi: PsiVariable, containingElement: UElement?): UVariable { return when (psi) { is PsiEnumConstant -> JavaUEnumConstant(psi, containingElement) is PsiLocalVariable -> JavaULocalVariable(psi, containingElement) is PsiParameter -> JavaUParameter(psi, containingElement) is PsiField -> JavaUField(psi, containingElement) else -> JavaUVariable(psi, containingElement) } } } } open class JavaUParameter( psi: PsiParameter, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UParameterEx, PsiParameter by psi { override val psi: PsiParameter get() = javaPsi override val javaPsi: PsiParameter = unwrap<UParameter, PsiParameter>(psi) } open class JavaUField( psi: PsiField, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UFieldEx, PsiField by psi { override val psi: PsiField get() = javaPsi override val javaPsi: PsiField = unwrap<UField, PsiField>(psi) } open class JavaULocalVariable( psi: PsiLocalVariable, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), ULocalVariableEx, PsiLocalVariable by psi { override val psi: PsiLocalVariable get() = javaPsi override val javaPsi: PsiLocalVariable = unwrap<ULocalVariable, PsiLocalVariable>(psi) override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let { when (it) { is PsiResourceList -> it.parent else -> it } } } open class JavaUEnumConstant( psi: PsiEnumConstant, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UEnumConstantEx, UCallExpressionEx, PsiEnumConstant by psi, UMultiResolvable { override val initializingClass: UClass? by lz { getLanguagePlugin().convertOpt<UClass>(psi.initializingClass, this) } override val psi: PsiEnumConstant get() = javaPsi override val javaPsi: PsiEnumConstant = unwrap<UEnumConstant, PsiEnumConstant>(psi) override val kind: UastCallKind get() = UastCallKind.CONSTRUCTOR_CALL override val receiver: UExpression? get() = null override val receiverType: PsiType? get() = null override val methodIdentifier: UIdentifier? get() = null override val classReference: UReferenceExpression? get() = JavaEnumConstantClassReference(psi, this) override val typeArgumentCount: Int get() = 0 override val typeArguments: List<PsiType> get() = emptyList() override val valueArgumentCount: Int get() = psi.argumentList?.expressions?.size ?: 0 override val valueArguments: List<UExpression> by lz { psi.argumentList?.expressions?.map { getLanguagePlugin().convertElement(it, this) as? UExpression ?: UastEmptyExpression(this) } ?: emptyList() } override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i) override val returnType: PsiType? get() = psi.type override fun resolve(): PsiMethod? = psi.resolveMethod() override fun multiResolve(): Iterable<ResolveResult> = listOfNotNull(psi.resolveMethodGenerics()) override val methodName: String? get() = null private class JavaEnumConstantClassReference( override val psi: PsiEnumConstant, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable { override fun resolve() = psi.containingClass override fun multiResolve(): Iterable<ResolveResult> = listOfNotNull(resolve()?.let { PsiTypesUtil.getClassType(it).resolveGenerics() }) override val resolvedName: String? get() = psi.containingClass?.name override val identifier: String get() = psi.containingClass?.name ?: "<error>" } }
apache-2.0
f8720fa1378de75fedebe237e99b9589
33.781065
145
0.745959
4.873134
false
false
false
false
dhis2/dhis2-android-sdk
core/src/androidTest/java/org/hisp/dhis/android/core/dataset/internal/DataSetInstanceStoreIntegrationShould.kt
1
4749
/* * 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.dataset.internal import com.google.common.truth.Truth.assertThat import org.hisp.dhis.android.core.common.State import org.hisp.dhis.android.core.datavalue.DataValue import org.hisp.dhis.android.core.datavalue.internal.DataValueStore import org.hisp.dhis.android.core.utils.integration.mock.BaseMockIntegrationTestMetadataDispatcher import org.junit.After import org.junit.Before import org.junit.Test class DataSetInstanceStoreIntegrationShould : BaseMockIntegrationTestMetadataDispatcher() { private lateinit var dataSetInstanceStore: DataSetInstanceStore private lateinit var dataValueStore: DataValueStore @Before fun setUp() { dataSetInstanceStore = DataSetInstanceStore.create(databaseAdapter) dataValueStore = DataValueStore.create(databaseAdapter) dataValueStore.delete() } @After fun tearDown() { dataValueStore.delete() } @Test fun should_prioritize_data_value_sync_states() { mapOf( listOf(State.SYNCED, State.TO_POST) to State.TO_POST, listOf(State.SYNCED, State.ERROR) to State.ERROR, listOf(State.SYNCED, State.WARNING) to State.WARNING, listOf(State.SYNCED, State.UPLOADING) to State.UPLOADING, listOf(State.TO_POST, State.ERROR) to State.ERROR, listOf(State.ERROR, State.TO_UPDATE) to State.ERROR, listOf(State.UPLOADING, State.TO_POST) to State.UPLOADING, listOf(State.UPLOADING, State.ERROR) to State.ERROR ).forEach { (valueStates, aggregated) -> insertDataValuesWithStates(valueStates[0], valueStates[1]) checkSyncState(aggregated) } } private fun insertDataValuesWithStates(state1: State, state2: State) { val dataElements = d2.dataSetModule().dataSets() .withDataSetElements() .one() .blockingGet() .dataSetElements()!!.map { it.dataElement() } val orgunit = d2.organisationUnitModule().organisationUnits().one().blockingGet()!! val period = d2.periodModule().periodHelper().blockingGetPeriodForPeriodId("202208") val optionCombo = d2.categoryModule().categoryOptionCombos().one().blockingGet() val baseBuilder = DataValue.builder() .value("") .organisationUnit(orgunit.uid()) .period(period.periodId()!!) .categoryOptionCombo(optionCombo.uid()) .attributeOptionCombo(optionCombo.uid()) dataValueStore.updateOrInsertWhere( baseBuilder .dataElement(dataElements[0].uid()) .syncState(state1) .build() ) dataValueStore.updateOrInsertWhere( baseBuilder .dataElement(dataElements[1].uid()) .syncState(state2) .build() ) } private fun checkSyncState(state: State) { val instances = d2.dataSetModule().dataSetInstances().blockingGet() assertThat(instances.size).isEqualTo(1) assertThat(instances.first().dataValueState()).isEqualTo(state) } }
bsd-3-clause
057463e986abec363d930094e7420c93
39.939655
98
0.695725
4.56196
false
false
false
false
dahlstrom-g/intellij-community
python/src/com/jetbrains/python/debugger/variablesview/usertyperenderers/PyUserTypeRenderersConfigurable.kt
6
24002
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.debugger.variablesview.usertyperenderers import com.intellij.ide.util.ElementsChooser import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionToolbarPosition import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.ComponentValidator import com.intellij.openapi.ui.Splitter import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Disposer import com.intellij.psi.util.QualifiedName import com.intellij.ui.* import com.intellij.ui.layout.* import com.intellij.ui.table.JBTable import com.intellij.util.textCompletion.TextFieldWithCompletion import com.intellij.xdebugger.XDebuggerManager import com.intellij.xdebugger.impl.XSourcePositionImpl import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl import com.intellij.xdebugger.impl.ui.XDebuggerExpressionEditor import com.jetbrains.python.PyBundle import com.jetbrains.python.debugger.PyDebugProcess import com.jetbrains.python.debugger.PyDebuggerEditorsProvider import com.jetbrains.python.debugger.variablesview.usertyperenderers.codeinsight.PyTypeNameResolver import com.jetbrains.python.debugger.variablesview.usertyperenderers.codeinsight.TypeNameCompletionProvider import com.jetbrains.python.debugger.variablesview.usertyperenderers.codeinsight.getClassesNumberInModuleRootWithName import com.jetbrains.python.psi.impl.PyExpressionCodeFragmentImpl import com.jetbrains.python.psi.resolve.QualifiedNameFinder import java.awt.BorderLayout import java.awt.event.ActionListener import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import java.util.function.Supplier import javax.swing.* import javax.swing.event.DocumentEvent import javax.swing.table.AbstractTableModel class PyUserTypeRenderersConfigurable : SearchableConfigurable { private val CONFIGURABLE_ID = "debugger.dataViews.python.type.renderers" private val CONFIGURABLE_NAME = PyBundle.message("configurable.PyUserTypeRenderersConfigurable.display.name") private val PANEL_SPLIT_PROPORTION = 0.3f private val myMainPanel: JPanel = JPanel(BorderLayout()) private var myCurrentRenderer: PyUserNodeRenderer? = null private val myProject: Project private val myRendererChooser: ElementsChooser<PyUserNodeRenderer> private var myRendererSettings: RendererSettings? = null private var myRendererIndexToSelect: Int? = null private var myNewRendererToAdd: PyUserNodeRenderer? = null init { val projectManager = ProjectManager.getInstance() val openProjects = projectManager.openProjects myProject = if (openProjects.isNotEmpty()) openProjects.first() else projectManager.defaultProject myRendererChooser = ElementsChooser(true) } fun setRendererIndexToSelect(index: Int?) { myRendererIndexToSelect = index } fun setNewRendererToAdd(renderer: PyUserNodeRenderer?) { myNewRendererToAdd = renderer } override fun createComponent(): JPanel { ApplicationManager.getApplication().invokeLater { if (myProject.isDisposed) return@invokeLater myRendererSettings = RendererSettings() setupRendererSettings() setupRendererChooser() val chooserDecorator = RendererChooserToolbarDecorator().decorator val splitter = Splitter(false).apply { proportion = PANEL_SPLIT_PROPORTION firstComponent = chooserDecorator.createPanel() secondComponent = myRendererSettings } if (myRendererChooser.elementCount > 0) { val index = myRendererIndexToSelect ?: 0 val first = myRendererChooser.getElementAt(index) myRendererChooser.selectElements(listOf(first)) } myMainPanel.removeAll() myMainPanel.add(splitter, BorderLayout.CENTER) } return myMainPanel } override fun reset() { myRendererChooser.removeAllElements() myCurrentRenderer = null val settings = PyUserTypeRenderersSettings.getInstance() val newRendererToAdd = myNewRendererToAdd if (newRendererToAdd != null) { val newRender = newRendererToAdd.clone() myRendererChooser.addElement(newRender, newRender.isEnabled) } for (render in settings.renderers) { val newRenderer = render.clone() myRendererChooser.addElement(newRenderer, newRenderer.isEnabled) } val selectedRenderers = mutableListOf<PyUserNodeRenderer>() val indexToSelect = myRendererIndexToSelect if (indexToSelect != null && indexToSelect >= 0 && indexToSelect < myRendererChooser.elementCount) { val renderer = myRendererChooser.getElementAt(indexToSelect) selectedRenderers.add(renderer) } else if (myRendererChooser.elementCount != 0) { val firstRenderer = myRendererChooser.getElementAt(0) selectedRenderers.add(firstRenderer) } myRendererChooser.selectElements(selectedRenderers) myRendererSettings?.reset() } override fun isModified(): Boolean { if (myRendererSettings?.isModified() == true) return true val settings = PyUserTypeRenderersSettings.getInstance() if (myRendererChooser.elementCount != settings.renderers.size) return true settings.renderers.withIndex().forEach { val element = myRendererChooser.getElementAt(it.index) if (!element.equalTo(it.value)) return true } return false } override fun apply() { myRendererSettings?.apply() val settings = PyUserTypeRenderersSettings.getInstance() val renderers = mutableListOf<PyUserNodeRenderer>() for (i in 0 until myRendererChooser.elementCount) { val element = myRendererChooser.getElementAt(i) renderers.add(element.clone()) } settings.setRenderers(renderers) applyRenderersToDebugger() } private fun applyRenderersToDebugger() { val debugSession = XDebuggerManager.getInstance(myProject).currentSession (debugSession?.debugProcess as? PyDebugProcess)?.let { debugProcess -> debugProcess.setUserTypeRenderersSettings() debugProcess.dropFrameCaches() debugProcess.session?.rebuildViews() } } override fun getDisplayName(): String = CONFIGURABLE_NAME override fun getId(): String = CONFIGURABLE_ID private fun setupRendererChooser() { myRendererChooser.emptyText.text = PyBundle.message("form.debugger.variables.view.user.type.renderers.no.renderers") myRendererChooser.addElementsMarkListener(ElementsChooser.ElementsMarkListener { element, isMarked -> element.isEnabled = isMarked }) myRendererChooser.addListSelectionListener { e -> if (!e.valueIsAdjusting) { updateCurrentRenderer(myRendererChooser.selectedElements) } } } private fun setupRendererSettings() { myRendererSettings?.isVisible = false } private fun updateCurrentRendererName(newName: String) { myCurrentRenderer?.let { it.name = newName myRendererChooser.refresh(it) } } private fun updateCurrentRenderer(selectedElements: List<PyUserNodeRenderer>) { when (selectedElements.size) { 1 -> setCurrentRenderer(selectedElements[0]) else -> setCurrentRenderer(null) } } private fun setCurrentRenderer(renderer: PyUserNodeRenderer?) { if (myCurrentRenderer === renderer) return if (myRendererSettings == null) return if (myRendererSettings?.isModified() == true) { myRendererSettings?.apply() } myCurrentRenderer = renderer myRendererSettings?.reset() } fun getCurrentlyVisibleNames(): List<String> { val resultList = mutableListOf<String>() for (i in 0 until myRendererChooser.elementCount) { myRendererChooser.getElementAt(i)?.name?.let { name -> resultList.add(name) } } return resultList } private inner class RendererChooserToolbarDecorator { val decorator = ToolbarDecorator.createDecorator(myRendererChooser.component) init { decorator.setToolbarPosition(ActionToolbarPosition.TOP) decorator.setAddAction(AddAction()) decorator.setRemoveAction(RemoveAction()) decorator.setMoveUpAction(MoveAction(true)) decorator.setMoveDownAction(MoveAction(false)) } private inner class AddAction : AnActionButtonRunnable { override fun run(button: AnActionButton?) { val renderer = PyUserNodeRenderer(true, getCurrentlyVisibleNames()) myRendererChooser.addElement(renderer, renderer.isEnabled) myRendererChooser.moveElement(renderer, 0) } } private inner class RemoveAction : AnActionButtonRunnable { override fun run(button: AnActionButton?) { myRendererChooser.selectedElements.forEach { myRendererChooser.removeElement(it) } } } private inner class MoveAction(val myMoveUp: Boolean) : AnActionButtonRunnable { override fun run(button: AnActionButton?) { val selectedRow = myRendererChooser.selectedElementRow if (selectedRow < 0) return var newRow = selectedRow + if (myMoveUp) -1 else 1 if (newRow < 0) { newRow = myRendererChooser.elementCount - 1 } else if (newRow >= myRendererChooser.elementCount) { newRow = 0 } myRendererChooser.moveElement(myRendererChooser.getElementAt(selectedRow), newRow) } } } override fun disposeUIResources() { super.disposeUIResources() myRendererSettings?.let { ApplicationManager.getApplication().executeOnPooledThread { Disposer.dispose(it) } } } private inner class RendererSettings : JPanel(BorderLayout()), Disposable { private val myPanel: JPanel private val myRendererNameTextField = JTextField() private val myAppendDefaultChildrenCheckBox = JCheckBox( PyBundle.message("form.debugger.variables.view.user.type.renderers.append.default.children")) private val myRbDefaultValueRenderer = JRadioButton( PyBundle.message("form.debugger.variables.view.user.type.renderers.use.default.renderer")) private val myRbExpressionValueRenderer = JRadioButton( PyBundle.message("form.debugger.variables.view.user.type.renderers.use.following.expression")) private val myRbDefaultChildrenRenderer = JRadioButton( PyBundle.message("form.debugger.variables.view.user.type.renderers.use.default.renderer")) private val myRbListChildrenRenderer = JRadioButton( PyBundle.message("form.debugger.variables.view.user.type.renderers.use.list.of.expressions")) private val myTypeNameTextField: TextFieldWithCompletion = TextFieldWithCompletion(myProject, TypeNameCompletionProvider(myProject), "", true, true, true) private val myNodeValueExpressionEditor: XDebuggerExpressionEditor private val myChildrenRenderersListEditor: JComponent private val myChildrenListEditorTableModel: ChildrenListEditorTableModel private val myChildrenListEditorTable: JBTable init { myNodeValueExpressionEditor = XDebuggerExpressionEditor(myProject, PyDebuggerEditorsProvider(), "NodeValueExpression", null, XExpressionImpl.EMPTY_EXPRESSION, false, false, true) myChildrenListEditorTableModel = ChildrenListEditorTableModel() myChildrenListEditorTable = JBTable(myChildrenListEditorTableModel) myChildrenRenderersListEditor = createChildrenListEditor() setupTypeNameEditor() setupPanelComponents() myPanel = createSettingsPanel() add(myPanel, BorderLayout.NORTH) } private fun createSettingsPanel(): JPanel { return panel { row(PyBundle.message("form.debugger.variables.view.user.type.renderers.name")) { myRendererNameTextField() } row { label(PyBundle.message("form.debugger.variables.view.user.type.renderers.apply.renderer.to.objects.of.type")) } row { myTypeNameTextField(CCFlags.growX) } row(PyBundle.message("form.debugger.variables.view.user.type.renderers.when.rendering.node")) { buttonGroup { row { myRbDefaultValueRenderer() } row { myRbExpressionValueRenderer() } } row { row { myNodeValueExpressionEditor.component(CCFlags.growX, comment = PyBundle.message("form.debugger.variables.view.user.type.renderers.variable.name")) } } } row(PyBundle.message("form.debugger.variables.view.user.type.renderers.when.expanding.node")) { buttonGroup { row { myRbDefaultChildrenRenderer() } row { myRbListChildrenRenderer() } } row { row { myChildrenRenderersListEditor(CCFlags.growX, comment = PyBundle.message("form.debugger.variables.view.user.type.renderers.variable.name")) } row { myAppendDefaultChildrenCheckBox() } } } } } private fun setupRendererNameField() { myRendererNameTextField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { val newName = myRendererNameTextField.text updateCurrentRendererName(newName) } }) } private fun setupTypeNameEditor() { val myTypeNameFieldValidator = ComponentValidator(this).withValidator( Supplier<ValidationInfo?> { val text: String = myTypeNameTextField.text return@Supplier if (!isValidTypeName(text)) { ValidationInfo(PyBundle.message("form.debugger.variables.view.user.type.renderers.class.not.found"), myTypeNameTextField) } else { null } }).installOn(myTypeNameTextField) myTypeNameTextField.addFocusListener(object : FocusAdapter() { override fun focusLost(e: FocusEvent) { myTypeNameFieldValidator.revalidate() } }) myTypeNameTextField.addDocumentListener(object : DocumentListener { override fun documentChanged(event: com.intellij.openapi.editor.event.DocumentEvent) { updateSelfType() } }) } private fun isValidTypeName(typeName: String): Boolean { return PyTypeNameResolver(myProject).resolve(typeName) != null } private fun updateSelfType() { val typeName = myTypeNameTextField.text val moduleName = typeName.substringBeforeLast(".") val className = typeName.substringAfterLast(".") val import = if (moduleName == className) "" else "from $moduleName import $className" val contextText = """ $import def foo(self: $className): pass """.trimIndent() val contextWithSelf = PyExpressionCodeFragmentImpl(myProject, "fragment.py", contextText, true) val offset = contextText.indexOf("def") val srcPosition = XSourcePositionImpl.createByOffset(contextWithSelf.virtualFile, offset) myNodeValueExpressionEditor.setSourcePosition(srcPosition) } private fun setupRadioButtons() { myRbDefaultValueRenderer.isSelected = true myRbDefaultChildrenRenderer.isSelected = true val listener = ActionListener { e -> when (e.source) { myRbDefaultChildrenRenderer -> { myAppendDefaultChildrenCheckBox.isEnabled = myRbListChildrenRenderer.isSelected myChildrenListEditorTable.isEnabled = myRbListChildrenRenderer.isSelected } myRbListChildrenRenderer -> { myAppendDefaultChildrenCheckBox.isEnabled = myRbListChildrenRenderer.isSelected myChildrenListEditorTable.isEnabled = myRbListChildrenRenderer.isSelected val renderer = myCurrentRenderer if (myChildrenListEditorTableModel.rowCount == 0 && renderer != null) { val pyClass = PyTypeNameResolver(myProject).resolve(renderer.toType) pyClass?.visitClassAttributes({ myChildrenListEditorTableModel.addRow("self.${it.name}") true }, false, null) } } } } myRbDefaultValueRenderer.addActionListener(listener) myRbExpressionValueRenderer.addActionListener(listener) myRbDefaultChildrenRenderer.addActionListener(listener) myRbListChildrenRenderer.addActionListener(listener) } private fun setupPanelComponents() { setupRendererNameField() setupRadioButtons() myAppendDefaultChildrenCheckBox.isEnabled = false myChildrenListEditorTable.isEnabled = false } private fun createChildrenListEditor(): JComponent { myChildrenListEditorTable.setShowGrid(true) return ChildrenListEditorToolbarDecorator(myChildrenListEditorTable, myChildrenListEditorTableModel).decorator.createPanel() } override fun setVisible(aFlag: Boolean) { myPanel.isVisible = aFlag } fun isModified(): Boolean { myCurrentRenderer?.let { return it.name != myRendererNameTextField.text || it.toType != myTypeNameTextField.text || it.valueRenderer.isDefault != myRbDefaultValueRenderer.isSelected || it.valueRenderer.expression != myNodeValueExpressionEditor.expression.expression || it.childrenRenderer.isDefault != myRbDefaultChildrenRenderer.isSelected || it.childrenRenderer.children != myChildrenListEditorTableModel.clonedChildren || it.childrenRenderer.appendDefaultChildren != myAppendDefaultChildrenCheckBox.isSelected } return false } fun apply() { myCurrentRenderer?.let { it.name = myRendererNameTextField.text it.toType = myTypeNameTextField.text it.valueRenderer.isDefault = myRbDefaultValueRenderer.isSelected it.valueRenderer.expression = myNodeValueExpressionEditor.expression.expression it.childrenRenderer.isDefault = myRbDefaultChildrenRenderer.isSelected it.childrenRenderer.children = myChildrenListEditorTableModel.clonedChildren it.childrenRenderer.appendDefaultChildren = myAppendDefaultChildrenCheckBox.isSelected resetTypeInfo(it) } } private fun resetTypeInfo(renderer: PyUserNodeRenderer) { renderer.typeSourceFile = "" renderer.moduleRootHasOneTypeWithSameName = false val type = renderer.toType val cls = PyTypeNameResolver(myProject).resolve(type) ?: return val clsName = cls.name ?: return val importPath = QualifiedNameFinder.findCanonicalImportPath(cls, null) renderer.typeCanonicalImportPath = if (importPath != null) "$importPath.${clsName}" else "" renderer.typeQualifiedName = cls.qualifiedName ?: "" renderer.typeSourceFile = cls.containingFile?.virtualFile?.path ?: "" renderer.moduleRootHasOneTypeWithSameName = getClassesNumberInModuleRootWithName(cls, importPath ?: QualifiedName.fromComponents(), myProject) == 1 } private fun resetChildrenListEditorTableModel(currentRenderer: PyUserNodeRenderer) { myChildrenListEditorTableModel.clear() for (child in currentRenderer.childrenRenderer.children) { myChildrenListEditorTableModel.addRow(child.expression) } } private fun resetRadioButtons(currentRenderer: PyUserNodeRenderer) { if (currentRenderer.valueRenderer.isDefault) { myRbDefaultValueRenderer.doClick() } else { myRbExpressionValueRenderer.doClick() } if (currentRenderer.childrenRenderer.isDefault) { myRbDefaultChildrenRenderer.doClick() } else { myRbListChildrenRenderer.doClick() } } fun reset() { myCurrentRenderer?.let { myRendererNameTextField.text = it.name myTypeNameTextField.text = it.toType myNodeValueExpressionEditor.expression = XExpressionImpl.fromText(it.valueRenderer.expression) myAppendDefaultChildrenCheckBox.isSelected = it.childrenRenderer.appendDefaultChildren resetRadioButtons(it) resetChildrenListEditorTableModel(it) myPanel.isVisible = true } ?: run { myPanel.isVisible = false } updateSelfType() } override fun dispose() { // do nothing } private inner class ChildrenListEditorToolbarDecorator(val table: JBTable, val tableModel: ChildrenListEditorTableModel) { val decorator = ToolbarDecorator.createDecorator(table) init { decorator.setToolbarPosition(ActionToolbarPosition.TOP) decorator.setAddAction(AddAction()) decorator.setRemoveAction(RemoveAction()) decorator.setMoveUpAction(MoveAction(true)) decorator.setMoveDownAction(MoveAction(false)) } private inner class AddAction : AnActionButtonRunnable { override fun run(button: AnActionButton?) { tableModel.addRow("") } } private inner class RemoveAction : AnActionButtonRunnable { override fun run(button: AnActionButton?) { tableModel.removeRows(table.selectedRows) } } private inner class MoveAction(val up: Boolean) : AnActionButtonRunnable { override fun run(button: AnActionButton?) { if (up) { TableUtil.moveSelectedItemsUp(table) } else { TableUtil.moveSelectedItemsDown(table) } } } } private inner class ChildrenListEditorTableModel : AbstractTableModel() { private val COLUMN_COUNT = 1 private val EXPRESSION_TABLE_COLUMN = 0 private val myData = mutableListOf<PyUserNodeRenderer.ChildInfo>() override fun getColumnCount(): Int { return COLUMN_COUNT } override fun getRowCount(): Int { return myData.size } override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean { return true } override fun getColumnClass(columnIndex: Int): Class<*> { return when (columnIndex) { EXPRESSION_TABLE_COLUMN -> String::class.java else -> super.getColumnClass(columnIndex) } } override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? { if (rowIndex >= rowCount) { return null } val row = myData[rowIndex] return when (columnIndex) { EXPRESSION_TABLE_COLUMN -> row.expression else -> null } } override fun setValueAt(aValue: Any, rowIndex: Int, columnIndex: Int) { if (rowIndex >= rowCount) { return } val row = myData[rowIndex] when (columnIndex) { EXPRESSION_TABLE_COLUMN -> row.expression = aValue as String } } override fun getColumnName(columnIndex: Int): String? { return when (columnIndex) { EXPRESSION_TABLE_COLUMN -> null else -> "" } } fun addRow(expression: String) { myData.add(PyUserNodeRenderer.ChildInfo(expression)) val lastRow = myData.size - 1 fireTableRowsInserted(lastRow, lastRow) } fun removeRows(rows: IntArray) { val nonSelected = myData.filterIndexed({ id, _ -> id !in rows }) myData.clear() myData.addAll(nonSelected) fireTableDataChanged() } fun clear() { myData.clear() fireTableDataChanged() } val clonedChildren: List<PyUserNodeRenderer.ChildInfo> get() = myData.toList() } } }
apache-2.0
91daf09bcbcade30f81362d4df22a81c
37.160572
166
0.700775
4.960116
false
false
false
false
cdietze/klay
klay-jvm/src/main/kotlin/klay/jvm/JavaCanvas.kt
1
8688
package klay.jvm import euklid.f.MathUtil import klay.core.* import java.awt.Color import java.awt.Graphics2D import java.awt.RenderingHints import java.awt.geom.* import java.awt.image.BufferedImage import java.util.* internal class JavaCanvas(gfx: Graphics, image: JavaImage) : Canvas(gfx, image) { val g2d: Graphics2D = image.bufferedImage()!!.createGraphics() private val stateStack = LinkedList<JavaCanvasState>() private val ellipse = Ellipse2D.Float() private val line = Line2D.Float() private val rect = Rectangle2D.Float() private val roundRect = RoundRectangle2D.Float() init { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) val scale = image.scale.factor g2d.scale(scale.toDouble(), scale.toDouble()) // push default state stateStack.push(JavaCanvasState()) // All clears go to rgba(0,0,0,0). g2d.background = Color(0, true) } fun alpha(): Float { return currentState().alpha } override fun snapshot(): Image { val bmp = (image as JavaImage).bufferedImage()!! val cm = bmp.colorModel val isAlphaPremultiplied = bmp.isAlphaPremultiplied val raster = bmp.copyData(null) val snap = BufferedImage(cm, raster, isAlphaPremultiplied, null) return JavaImage(gfx, image.scale, snap, "<canvas>") } override fun clear(): Canvas { currentState().prepareClear(g2d) g2d.clearRect(0, 0, MathUtil.iceil(width), MathUtil.iceil(height)) isDirty = true return this } override fun clearRect(x: Float, y: Float, width: Float, height: Float): Canvas { currentState().prepareClear(g2d) g2d.clearRect(MathUtil.ifloor(x), MathUtil.ifloor(y), MathUtil.iceil(width), MathUtil.iceil(height)) isDirty = true return this } override fun clip(path: Path): Canvas { currentState().clipper = path as JavaPath return this } override fun clipRect(x: Float, y: Float, width: Float, height: Float): Canvas { val cx = MathUtil.ifloor(x) val cy = MathUtil.ifloor(y) val cwidth = MathUtil.iceil(width) val cheight = MathUtil.iceil(height) currentState().clipper = object : JavaCanvasState.Clipper { override fun setClip(gfx: Graphics2D) { gfx.setClip(cx, cy, cwidth, cheight) } } return this } override fun createPath(): Path { return JavaPath() } override fun createGradient(cfg: Gradient.Config): Gradient { if (cfg is Gradient.Linear) return JavaGradient.create(cfg) else if (cfg is Gradient.Radial) return JavaGradient.create(cfg) else throw IllegalArgumentException("Unknown config: " + cfg) } override fun drawLine(x0: Float, y0: Float, x1: Float, y1: Float): Canvas { currentState().prepareStroke(g2d) line.setLine(x0, y0, x1, y1) g2d.draw(line) isDirty = true return this } override fun drawPoint(x: Float, y: Float): Canvas { currentState().prepareStroke(g2d) g2d.drawLine(x.toInt(), y.toInt(), x.toInt(), y.toInt()) isDirty = true return this } override fun drawText(text: String, x: Float, y: Float): Canvas { currentState().prepareFill(g2d) g2d.drawString(text, x, y) isDirty = true return this } override fun fillCircle(x: Float, y: Float, radius: Float): Canvas { currentState().prepareFill(g2d) ellipse.setFrame(x - radius, y - radius, 2 * radius, 2 * radius) g2d.fill(ellipse) isDirty = true return this } override fun fillPath(path: Path): Canvas { currentState().prepareFill(g2d) g2d.fill((path as JavaPath).path) isDirty = true return this } override fun fillRect(x: Float, y: Float, width: Float, height: Float): Canvas { currentState().prepareFill(g2d) rect.setRect(x, y, width, height) g2d.fill(rect) isDirty = true return this } override fun fillRoundRect(x: Float, y: Float, width: Float, height: Float, radius: Float): Canvas { currentState().prepareFill(g2d) roundRect.setRoundRect(x, y, width, height, radius * 2, radius * 2) g2d.fill(roundRect) isDirty = true return this } override fun fillText(layout: TextLayout, x: Float, y: Float): Canvas { currentState().prepareFill(g2d) (layout as JavaTextLayout).fill(g2d, x, y) isDirty = true return this } override fun restore(): Canvas { stateStack.pop() g2d.transform = currentState().transform return this } override fun rotate(angle: Float): Canvas { g2d.rotate(angle.toDouble()) return this } override fun save(): Canvas { // update saved transform currentState().transform = g2d.transform // clone to maintain current state stateStack.push(JavaCanvasState(currentState())) return this } override fun scale(x: Float, y: Float): Canvas { g2d.scale(x.toDouble(), y.toDouble()) return this } override fun setAlpha(alpha: Float): Canvas { currentState().alpha = alpha return this } override fun setCompositeOperation(composite: Composite): Canvas { currentState().composite = composite return this } override fun setFillColor(color: Int): Canvas { currentState().fillColor = color currentState().fillGradient = null currentState().fillPattern = null return this } override fun setFillGradient(gradient: Gradient): Canvas { currentState().fillGradient = gradient as JavaGradient currentState().fillPattern = null currentState().fillColor = 0 return this } override fun setFillPattern(pattern: Pattern): Canvas { currentState().fillPattern = pattern as JavaPattern currentState().fillGradient = null currentState().fillColor = 0 return this } override fun setLineCap(cap: LineCap): Canvas { currentState().lineCap = cap return this } override fun setLineJoin(join: LineJoin): Canvas { currentState().lineJoin = join return this } override fun setMiterLimit(miter: Float): Canvas { currentState().miterLimit = miter return this } override fun setStrokeColor(color: Int): Canvas { currentState().strokeColor = color return this } override fun setStrokeWidth(w: Float): Canvas { currentState().strokeWidth = w return this } override fun strokeCircle(x: Float, y: Float, radius: Float): Canvas { currentState().prepareStroke(g2d) ellipse.setFrame(x - radius, y - radius, 2 * radius, 2 * radius) g2d.draw(ellipse) isDirty = true return this } override fun strokePath(path: Path): Canvas { currentState().prepareStroke(g2d) g2d.color = Color(currentState().strokeColor, false) g2d.draw((path as JavaPath).path) isDirty = true return this } override fun strokeRect(x: Float, y: Float, width: Float, height: Float): Canvas { currentState().prepareStroke(g2d) rect.setRect(x, y, width, height) g2d.draw(rect) isDirty = true return this } override fun strokeRoundRect(x: Float, y: Float, width: Float, height: Float, radius: Float): Canvas { currentState().prepareStroke(g2d) roundRect.setRoundRect(x, y, width, height, radius * 2, radius * 2) g2d.draw(roundRect) isDirty = true return this } override fun strokeText(layout: TextLayout, x: Float, y: Float): Canvas { currentState().prepareStroke(g2d) (layout as JavaTextLayout).stroke(g2d, x, y) isDirty = true return this } override fun transform(m11: Float, m12: Float, m21: Float, m22: Float, dx: Float, dy: Float): Canvas { g2d.transform(AffineTransform(m11, m12, m21, m22, dx, dy)) return this } override fun translate(x: Float, y: Float): Canvas { g2d.translate(x.toDouble(), y.toDouble()) return this } override fun gc(): Graphics2D { currentState().prepareFill(g2d) return g2d } private fun currentState(): JavaCanvasState { return stateStack.first } }
apache-2.0
70787a29bc2de5b9139efc046bc57f78
28.753425
106
0.616252
4.090395
false
false
false
false
dahlstrom-g/intellij-community
plugins/git4idea/src/git4idea/GitNotificationIdsHolder.kt
3
10207
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea import com.intellij.notification.impl.NotificationIdsHolder class GitNotificationIdsHolder : NotificationIdsHolder { override fun getNotificationIds(): List<String> { return listOf( BRANCH_CHECKOUT_FAILED, BRANCH_CREATION_FAILED, BRANCH_DELETED, BRANCH_DELETION_ROLLBACK_ERROR, BRANCH_OPERATION_ERROR, BRANCH_OPERATION_SUCCESS, BRANCH_SET_UPSTREAM_ERROR, BRANCH_RENAME_ROLLBACK_FAILED, BRANCH_RENAME_ROLLBACK_SUCCESS, BRANCHES_UPDATE_SUCCESSFUL, CANNOT_RESOLVE_CONFLICT, CHECKOUT_NEW_BRANCH_OPERATION_ROLLBACK_ERROR, CHECKOUT_NEW_BRANCH_OPERATION_ROLLBACK_SUCCESSFUL, CHECKOUT_ROLLBACK_ERROR, CHECKOUT_SUCCESS, CHERRY_PICK_ABORT_FAILED, CHERRY_PICK_ABORT_SUCCESS, CLONE_FAILED, CLONE_ERROR_UNABLE_TO_CREATE_DESTINATION_DIR, COLLECT_UPDATED_CHANGES_ERROR, COMMIT_CANCELLED, COMMIT_EDIT_SUCCESS, CONFLICT_RESOLVING_ERROR, COULD_NOT_COMPARE_WITH_BRANCH, COULD_NOT_LOAD_CHANGES_OF_COMMIT, COULD_NOT_LOAD_CHANGES_OF_COMMIT_LOG, COULD_NOT_SAVE_UNCOMMITTED_CHANGES, BRANCH_CREATE_ROLLBACK_SUCCESS, BRANCH_CREATE_ROLLBACK_ERROR, DELETE_BRANCH_ON_MERGE, FETCH_ERROR, FETCH_SUCCESS, FETCH_CANCELLED, FETCH_DETAILS, FETCH_RESULT, FETCH_RESULT_ERROR, FILES_UPDATED_AFTER_MERGE, FILES_UP_TO_DATE, FIX_TRACKED_NOT_ON_BRANCH, INIT_ERROR, INIT_FAILED, INIT_STAGE_FAILED, LOCAL_CHANGES_NOT_RESTORED, MERGE_ABORT_FAILED, MERGE_ABORT_SUCCESS, MERGE_ERROR, MERGE_FAILED, LOCAL_CHANGES_DETECTED, MERGE_RESET_ERROR, MERGE_ROLLBACK_ERROR, PROJECT_UPDATED, PROJECT_PARTIALLY_UPDATED, PULL_FAILED, PUSH_RESULT, PUSH_NOT_SUPPORTED, REBASE_ABORT_FAILED, REBASE_ABORT, REBASE_ABORT_SUCCESS, REBASE_CANNOT_ABORT, REBASE_CANNOT_CONTINUE, REBASE_COMMIT_EDIT_UNDO_ERROR, REBASE_COMMIT_EDIT_UNDO_ERROR_PROTECTED_BRANCH, REBASE_COMMIT_EDIT_UNDO_ERROR_REPO_CHANGES, REBASE_NOT_ALLOWED, REBASE_NOT_STARTED, REBASE_ROLLBACK_FAILED, REBASE_SUCCESSFUL, REBASE_UPDATE_PROJECT_ERROR, REMOTE_BRANCH_DELETION_ERROR, REMOTE_BRANCH_DELETION_SUCCESS, REPOSITORY_CREATED, RESET_FAILED, RESET_PARTIALLY_FAILED, RESET_SUCCESSFUL, REVERT_ABORT_FAILED, REVERT_ABORT_SUCCESS, STAGE_COMMIT_ERROR, STAGE_COMMIT_SUCCESS, STASH_FAILED, STASH_LOCAL_CHANGES_DETECTED, TAG_CREATED, TAG_NOT_CREATED, TAG_DELETED, TAG_DELETION_ROLLBACK_ERROR, TAG_REMOTE_DELETION_ERROR, TAG_REMOTE_DELETION_SUCCESS, TAG_RESTORED, UNRESOLVED_CONFLICTS, UNSTASH_FAILED, UNSTASH_PATCH_APPLIED, UNSTASH_WITH_CONFLICTS, UNSTASH_UNRESOLVED_CONFLICTS, UPDATE_DETACHED_HEAD_ERROR, UPDATE_ERROR, UPDATE_NO_TRACKED_BRANCH, UPDATE_NOTHING_TO_UPDATE, BAD_EXECUTABLE, REBASE_STOPPED_ON_CONFLICTS, REBASE_STOPPED_ON_EDITING, REBASE_FAILED, UNTRACKED_FIES_OVERWITTEN ) } companion object { const val BRANCH_CHECKOUT_FAILED = "git.branch.checkout.failed" const val BRANCH_CREATION_FAILED = "git.branch.creation.failed" const val BRANCH_DELETED = "git.branch.deleted" const val BRANCH_DELETION_ROLLBACK_ERROR = "git.branch.deletion.rollback.error" const val BRANCH_OPERATION_ERROR = "git.branch.operation.error" const val BRANCH_OPERATION_SUCCESS = "git.branch.operation.success" const val BRANCH_SET_UPSTREAM_ERROR = "git.branch.set.upstream.failed" const val BRANCH_RENAME_ROLLBACK_FAILED = "git.branch.rename.rollback.failed" const val BRANCH_RENAME_ROLLBACK_SUCCESS = "git.branch.rename.rollback.success" const val BRANCHES_UPDATE_SUCCESSFUL = "git.branches.update.successful" const val CANNOT_RESOLVE_CONFLICT = "git.cannot.resolve.conflict" const val CHECKOUT_NEW_BRANCH_OPERATION_ROLLBACK_ERROR = "git.checkout.new.branch.operation.rollback.error" const val CHECKOUT_NEW_BRANCH_OPERATION_ROLLBACK_SUCCESSFUL = "git.checkout.new.branch.operation.rollback.successful" const val CHECKOUT_ROLLBACK_ERROR = "git.checkout.rollback.error" const val CHECKOUT_SUCCESS = "git.checkout.success" const val CHERRY_PICK_ABORT_FAILED = "git.cherry.pick.abort.failed" const val CHERRY_PICK_ABORT_SUCCESS = "git.cherry.pick.abort.success" const val CLONE_FAILED = "git.clone.failed" const val CLONE_ERROR_UNABLE_TO_CREATE_DESTINATION_DIR = "git.clone.unable.to.create.destination.dir" const val COLLECT_UPDATED_CHANGES_ERROR = "git.rebase.collect.updated.changes.error" const val COMMIT_CANCELLED = "git.commit.cancelled" const val COMMIT_EDIT_SUCCESS = "git.commit.edit.success" const val CONFLICT_RESOLVING_ERROR = "git.conflict.resolving.error" const val COULD_NOT_COMPARE_WITH_BRANCH = "git.could.not.compare.with.branch" const val COULD_NOT_LOAD_CHANGES_OF_COMMIT = "git.could.not.load.changes.of.commit" const val COULD_NOT_LOAD_CHANGES_OF_COMMIT_LOG = "git.log.could.not.load.changes.of.commit" const val COULD_NOT_SAVE_UNCOMMITTED_CHANGES = "git.could.not.save.uncommitted.changes" const val BRANCH_CREATE_ROLLBACK_SUCCESS = "git.create.branch.rollback.successful" const val BRANCH_CREATE_ROLLBACK_ERROR = "git.create.branch.rollback.error" const val DELETE_BRANCH_ON_MERGE = "git.delete.branch.on.merge" const val FETCH_ERROR = "git.fetch.error" const val FETCH_SUCCESS = "git.fetch.success" const val FETCH_CANCELLED = "git.fetch.cancelled" const val FETCH_DETAILS = "git.fetch.details" const val FETCH_RESULT = "git.fetch.result" const val FETCH_RESULT_ERROR = "git.fetch.result.error" const val FILES_UPDATED_AFTER_MERGE = "git.files.updated.after.merge" const val FILES_UP_TO_DATE = "git.all.files.are.up.to.date" const val FIX_TRACKED_NOT_ON_BRANCH = "git.fix.tracked.not.on.branch" const val INIT_ERROR = "git.init.error" const val INIT_FAILED = "git.init.failed" const val INIT_STAGE_FAILED = "git.init.stage.failed" const val LOCAL_CHANGES_NOT_RESTORED = "git.local.changes.not.restored" const val MERGE_ABORT_FAILED = "git.merge.abort.failed" const val MERGE_ABORT_SUCCESS = "git.merge.abort.success" const val MERGE_ERROR = "git.merge.error" const val MERGE_FAILED = "git.merge.failed" const val LOCAL_CHANGES_DETECTED = "git.merge.local.changes.detected" const val MERGE_RESET_ERROR = "git.merge.reset.error" const val MERGE_ROLLBACK_ERROR = "git.merge.rollback.error" const val PROJECT_UPDATED = "git.project.updated" const val PROJECT_PARTIALLY_UPDATED = "git.project.partially.updated" const val PULL_FAILED = "git.pull.failed" const val PUSH_RESULT = "git.push.result" const val PUSH_NOT_SUPPORTED = "git.push.not.supported" const val REBASE_ABORT_FAILED = "git.rebase.abort.failed" const val REBASE_ABORT = "git.rebase.abort" const val REBASE_ABORT_SUCCESS = "git.rebase.abort.succeeded" const val REBASE_CANNOT_ABORT = "git.rebase.cannot.abort" const val REBASE_CANNOT_CONTINUE = "git.rebase.cannot.continue" const val REBASE_COMMIT_EDIT_UNDO_ERROR = "git.rebase.commit.edit.undo.error" const val REBASE_COMMIT_EDIT_UNDO_ERROR_PROTECTED_BRANCH = "git.rebase.commit.edit.undo.error.protected.branch" const val REBASE_COMMIT_EDIT_UNDO_ERROR_REPO_CHANGES = "git.rebase.commit.edit.undo.error.repo.changed" const val REBASE_NOT_ALLOWED = "git.rebase.not.allowed" const val REBASE_NOT_STARTED = "git.rebase.not.started" const val REBASE_ROLLBACK_FAILED = "git.rebase.rollback.failed" const val REBASE_SUCCESSFUL = "git.rebase.successful" const val REBASE_UPDATE_PROJECT_ERROR = "git.rebase.update.project.error" const val REMOTE_BRANCH_DELETION_ERROR = "git.remote.branch.deletion.error" const val REMOTE_BRANCH_DELETION_SUCCESS = "git.remote.branch.deletion.success" const val REPOSITORY_CREATED = "git.repository.created" const val RESET_FAILED = "git.reset.failed" const val RESET_PARTIALLY_FAILED = "git.reset.partially.failed" const val RESET_SUCCESSFUL = "git.reset.successful" const val REVERT_ABORT_FAILED = "git.revert.abort.failed" const val REVERT_ABORT_SUCCESS = "git.revert.abort.success" const val STAGE_COMMIT_ERROR = "git.stage.commit.error" const val STAGE_COMMIT_SUCCESS = "git.stage.commit.successful" const val STASH_FAILED = "git.stash.failed" const val STASH_LOCAL_CHANGES_DETECTED = "git.stash.local.changes.detected" const val TAG_CREATED = "git.tag.created" const val TAG_NOT_CREATED = "git.tag.not.created" const val TAG_DELETED = "git.tag.deleted" const val TAG_DELETION_ROLLBACK_ERROR = "git.tag.deletion.rollback.error" const val TAG_REMOTE_DELETION_ERROR = "git.tag.remote.deletion.error" const val TAG_REMOTE_DELETION_SUCCESS = "git.tag.remote.deletion.success" const val TAG_RESTORED = "git.tag.restored" const val UNRESOLVED_CONFLICTS = "git.unresolved.conflicts" const val UNSTASH_FAILED = "git.unstash.failed" const val UNSTASH_PATCH_APPLIED = "git.unstash.patch.applied" const val UNSTASH_WITH_CONFLICTS = "git.unstash.with.conflicts" const val UNSTASH_UNRESOLVED_CONFLICTS = "git.unstash.with.unresolved.conflicts" const val UPDATE_DETACHED_HEAD_ERROR = "git.update.detached.head.error" const val UPDATE_ERROR = "git.update.error" const val UPDATE_NO_TRACKED_BRANCH = "git.update.no.tracked.branch.error" const val UPDATE_NOTHING_TO_UPDATE = "git.update.nothing.to.update" const val BAD_EXECUTABLE = "git.bad.executable" const val REBASE_STOPPED_ON_CONFLICTS = "git.rebase.stopped.due.to.conflicts" const val REBASE_STOPPED_ON_EDITING = "git.rebase.stopped.for.editing" const val REBASE_FAILED = "git.rebase.failed" const val UNTRACKED_FIES_OVERWITTEN = "untracked.files.overwritten" } }
apache-2.0
e67e9788ee781482e93204bd5535b593
46.259259
121
0.715685
3.580147
false
false
false
false
dahlstrom-g/intellij-community
java/java-impl/src/com/intellij/lang/java/actions/InsertMissingFieldTemplateListener.kt
18
1988
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.lang.java.actions import com.intellij.codeInsight.template.Template import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.codeInsight.template.impl.TemplateState import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiNameHelper import com.intellij.psi.util.createSmartPointer internal class InsertMissingFieldTemplateListener( private val project: Project, target: PsiClass, private val typeExpression: RangeExpression, private val isStatic: Boolean ) : TemplateEditingAdapter() { private val targetPointer = target.createSmartPointer(project) override fun beforeTemplateFinished(state: TemplateState, template: Template, brokenOff: Boolean) { if (brokenOff) return val target = targetPointer.element ?: return val name = state.getVariableValue(FIELD_VARIABLE)?.text ?: return val typeText = typeExpression.text CommandProcessor.getInstance().runUndoTransparentAction { runWriteAction { insertMissingField(target, name, typeText) PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(state.editor.document) } } } private fun insertMissingField(target: PsiClass, name: String, typeText: String) { if (!PsiNameHelper.getInstance(project).isIdentifier(name)) return if (target.findFieldByName(name, false) != null) return val factory = JavaPsiFacade.getElementFactory(project) val userType = factory.createTypeFromText(typeText, target) val userField = factory.createField(name, userType).setStatic(isStatic) target.add(userField) } }
apache-2.0
1a941e442033995781a098eacb66e65b
41.297872
140
0.792757
4.733333
false
false
false
false
PaulWoitaschek/MaterialAudiobookPlayer
data/src/main/java/de/ph1b/audiobook/data/Bookmark.kt
1
1267
package de.ph1b.audiobook.data import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import de.ph1b.audiobook.common.comparator.NaturalOrderComparator import java.io.File /** * Represents a bookmark in the book. */ @Entity(tableName = "bookmark") data class Bookmark( @ColumnInfo(name = "file") val mediaFile: File, @ColumnInfo(name = "title") val title: String, @ColumnInfo(name = "time") val time: Int, @ColumnInfo(name = "id") @PrimaryKey(autoGenerate = true) val id: Long = ID_UNKNOWN ) : Comparable<Bookmark> { init { require(title.isNotEmpty()) } override fun compareTo(other: Bookmark): Int { // compare files val fileCompare = NaturalOrderComparator.fileComparator.compare(mediaFile, other.mediaFile) if (fileCompare != 0) { return fileCompare } // if files are the same compare time val timeCompare = time.compareTo(other.time) if (timeCompare != 0) return timeCompare // if time is the same compare the titles val titleCompare = NaturalOrderComparator.stringComparator.compare(title, other.title) if (titleCompare != 0) return titleCompare return id.compareTo(other.id) } companion object { const val ID_UNKNOWN = 0L } }
lgpl-3.0
6f557d96af7b18450c35ac250854ebdd
24.34
95
0.70955
3.862805
false
false
false
false
indianpoptart/RadioControl
RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/utilities/Utilities.kt
1
27844
package com.nikhilparanjape.radiocontrol.utilities import android.Manifest import android.annotation.SuppressLint import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.job.JobInfo import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.media.AudioManager import android.net.ConnectivityManager import android.net.NetworkInfo import android.net.wifi.WifiManager import android.os.Build import android.provider.Settings import android.telephony.SubscriptionManager import android.telephony.TelephonyManager import android.text.format.DateFormat import android.util.Log import androidx.core.content.ContextCompat import com.nikhilparanjape.radiocontrol.R import com.nikhilparanjape.radiocontrol.services.BackgroundJobService import com.topjohnwu.superuser.Shell import java.io.File import java.io.IOException import java.lang.reflect.Field import java.lang.reflect.Method /** * Created by Nikhil on 2/3/2016. * * A custom Utilities class for RadioControl * * @author Nikhil Paranjape * * */ class Utilities { companion object { val airOffCmd2 = arrayOf("su", "settings put global airplane_mode_radios \"cell,bluetooth,nfc,wimax\"", "content update --uri content://settings/global --bind value:s:'cell,bluetooth,nfc,wimax' --where \"name='airplane_mode_radios'\"") /** * Check if there is any active call * * @param context allows access to application-specific resources and classes * @return true if the device is in an active call */ fun isCallActive(context: Context): Boolean { val manager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager return manager.mode == AudioManager.MODE_IN_CALL //Checks if android's audiomanager is in curently in an active call } /** * gets network ssid * @version 1.0 * @param context allows access to application-specific resources and classes * @return the current ssid the device is connected to as a string */ fun getCurrentSsid(context: Context): String? { var ssid: String? = null val connManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) if (networkInfo!!.isConnected) { val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager val connectionInfo = wifiManager.connectionInfo ssid = connectionInfo.ssid ssid = ssid!!.substring(1, ssid.length - 1) } else if (!networkInfo.isConnected) { ssid = "Not Connected" // TODO Check if this can use local isConnectedWifi method to reduce networkInfo/ConnectivityMananger usage } return ssid } /** * Gets the current network SSID * * After Android 8.0+ You now need the COARSE_LOCATION of the device to run these commands * * @version 2.0-alpha01 * @param context allows access to application-specific resources and classes * @return the current ssid the device is connected to as a string **/ fun getCurrentSSID(context: Context): String{ var ssid: String? = null val mWifiManager = (context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager) val info = mWifiManager.connectionInfo return info.ssid } /** * Return the status of the cellular radio * @param context allows access to application-specific resources and classes * @return int A value between 0-3. * 0 and 1 are good values, * returning a 2 or 3 means there is some kind of error */ fun getCellStatus(context: Context): Int { var z = 0 // Initially, we forcibly assume the cell radio is connected val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager /** * Old variables that are now deprecated //val connMgr = c.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager - This used to be the original connectivity manager, until that functionality was moved out of the utility - This removal allows the Utilities class to remain a relatively simple method //var isWifiConn: Boolean = false - Was used with connMgr //var isMobileConn: Boolean = false - Was used with connMgr **/ try{ if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ){ val cellInfoList = tm.allCellInfo Log.d("Radiocontrol-Util","Cell list: $cellInfoList") //This means cell is off if (cellInfoList.isEmpty()) { z = 1 } } } catch (e: SecurityException) { Log.e("RadioControl-util", "Unable to get Location Permission", e) return 2 } catch (e: NullPointerException) { Log.e("RadioControl-util", "NullPointer: ", e) return 3 } return z //Any value above 1 means some kind of error } //@Throws(java.lang.Exception::class) private fun getTransactionCode(context: Context): String { return try { val mTelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager val mTelephonyClass = Class.forName(mTelephonyManager.javaClass.name) val mTelephonyMethod: Method = mTelephonyClass.getDeclaredMethod("getITelephony") mTelephonyMethod.isAccessible = true val mTelephonyStub: Any = mTelephonyMethod.invoke(mTelephonyManager) val mTelephonyStubClass = Class.forName(mTelephonyStub.javaClass.name) val mClass = mTelephonyStubClass.declaringClass val field: Field = mClass!!.getDeclaredField("TRANSACTION_setDataEnabled") field.isAccessible = true java.lang.String.valueOf(field.getInt(null)) } catch (e: java.lang.Exception) { // The "TRANSACTION_setDataEnabled" field is not available, // or named differently in the current API level, so we throw // an exception and inform users that the method is not available. throw e } } internal fun enableNetworks(context: Context, prefs: SharedPreferences){ // Ensures that Airplane mode is on, or that the cell radio is off if (isAirplaneMode(context) || !isConnectedMobile(context)) { //Runs the alt cellular mode, otherwise, run the standard airplane mode if (prefs.getBoolean("altRootCommand", false)) { if (getCellStatus(context) == 1) { val output = Shell.cmd("service call phone 27").exec() writeLog("root accessed: $output", context) Log.d(BackgroundJobService.TAG, BackgroundJobService.CELL_RADIO_ON) writeLog(BackgroundJobService.CELL_RADIO_ON, context) } } else { val output = Shell.cmd("settings put global airplane_mode_on 0", "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false").exec() writeLog("root accessed: $output", context) //RootAccess.runCommands(airOffCmd3) *Here for legacy purposes Log.d(BackgroundJobService.TAG, BackgroundJobService.AIRPLANE_MODE_OFF) writeLog(BackgroundJobService.AIRPLANE_MODE_OFF, context) } } } internal fun disableNetworks(prefs: SharedPreferences, context: Context){ //Runs the cellular mode, otherwise, run default airplane mode if (prefs.getBoolean("altRootCommand", false)) { when { getCellStatus(context) == 0 -> { val output = Shell.cmd("service call phone 27").exec() writeLog("root accessed: $output", context) Log.d(BackgroundJobService.TAG, BackgroundJobService.CELL_RADIO_OFF) writeLog(BackgroundJobService.CELL_RADIO_OFF, context) } getCellStatus(context) == 1 -> { Log.d(BackgroundJobService.TAG, "Cell Radio is already off") } getCellStatus(context) == 2 -> { Log.e(BackgroundJobService.TAG, "Location can't be accessed, try alt method") setMobileNetworkFromLollipop(context) } } } else { val output = Shell.cmd("settings put global airplane_mode_radios \"cell\"", "content update --uri content://settings/global --bind value:s:'cell' --where \"name='airplane_mode_radios'\"", "settings put global airplane_mode_on 1", "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true").exec() writeLog("root accessed: $output", context) //RootAccess.runCommands(airCmd) Log.d(BackgroundJobService.TAG, BackgroundJobService.AIRPLANE_MODE_ON) writeLog(BackgroundJobService.AIRPLANE_MODE_ON, context) } } //An old function used for checking of we are on lollipop and whether mobile data can be turned on/off private fun isMobileDataEnabledFromLollipop(context: Context): Boolean { return Settings.Global.getInt(context.contentResolver, "mobile_data", 0) == 1 } /** * Runs a root level command to control the mobile network on device * * This method always requires transactionCodes that are device specific from getTransactionCode() * * @param context allows access to application-specific resources and classes */ @Throws(Exception::class) fun setMobileNetworkFromLollipop(context: Context) { var command: String? = null var state = 0 try { // Set the current state of the mobile network. state = Settings.Global.getInt(context.contentResolver, "mobile_data", 0) // Get the value of the "TRANSACTION_setDataEnabled" field. val transactionCode: String = getTransactionCode(context) // Android 5.1+ (API 22) and later. if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { val mSubscriptionManager: SubscriptionManager = context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager // Loop through the subscription list i.e. SIM list. for (i in 0 until mSubscriptionManager.activeSubscriptionInfoCountMax) { if (transactionCode.isNotEmpty()) { // Get the active subscription ID for a given SIM card. val subscriptionId: Int = mSubscriptionManager.activeSubscriptionInfoList[i].subscriptionId // Execute the command via `su` to turn off // mobile network for a subscription service. command = "service call phone $transactionCode i32 $subscriptionId i32 $state" val output = Shell.su(command).exec().out } } } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) { // Android 5.0 (API 21) only. if (transactionCode.isNotEmpty()) { // Execute the command via `su` to turn off mobile network. command = "service call phone $transactionCode i32 $state" val output = Shell.su(command).exec().out } } } catch (e: Exception) { // Oops! Something went wrong, so we throw the exception here. Log.e("RadioControl-util", "An unknown error occurred", e) } catch (e: SecurityException) { Log.e("RadioControl-util", "Unable to get Phone State Permission", e) } catch (e: NullPointerException) { Log.e("RadioControl-util", "NullPointer: ", e) } } /** * Checks link speed * @param c allows access to application-specific resources and classes * @return linkSpeed of the current wifi network in mbps */ fun linkSpeed(c: Context): Int { val wifiManager = c.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager val linkSpeed = wifiManager.connectionInfo.linkSpeed Log.d("RadioControl-util", "Link speed = " + linkSpeed + "Mbps") return linkSpeed } /** * Write a private log for the Statistics Activity * * Sets the date in yyyy-MM-dd HH:mm:ss format * * This method always requires appropriate context * * @param data The data to be written to the log file radiocontrol.log * @param c allows access to application-specific resources and classes */ fun writeLog(data: String, c: Context) { val preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(c) if (preferences.getBoolean("enableLogs", false)) { try { val h = DateFormat.format("yyyy-MM-dd HH:mm:ss", System.currentTimeMillis()).toString() val log = File(c.filesDir, "radiocontrol.log") if (!log.exists()) { log.createNewFile() } val logPath = "radiocontrol.log" val string = "\n$h: $data" val fos = c.openFileOutput(logPath, Context.MODE_APPEND) fos.write(string.toByteArray()) fos.close() } catch (e: IOException) { Log.e("RadioControl-util", "Error writing log") } } } /** * Function to write data to the log. It will also execute functions defined by Log.* (DEBUG,INFO,VERBOSE,etc) * * @param data This is the data that needs to be written to the log * @param c Allows access to application-specific resources and classes * @param t The type of Log level requested */ fun writeLog(tag: String, data: String, c: Context, t: Int) { println("$tag : $t : $data") val preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(c) if (preferences.getBoolean("enableLogs", false)) { try { val h = DateFormat.format("yyyy-MM-dd HH:mm:ss", System.currentTimeMillis()).toString() val log = File(c.filesDir, "radiocontrol.log") if (!log.exists()) { //If the log don't exist log.createNewFile() } val logPath = "radiocontrol.log" //TODO Change this to grab what the user desires val loggedData = "\n$h: TYPE: $t: DATA: $data" val fos = c.openFileOutput(logPath, Context.MODE_APPEND) // Appends the log data fos.write(loggedData.toByteArray()) // writes the log data to the log file above fos.close() // Closes the file buffer } catch (e: IOException) { Log.e("RadioControl-UTIL", "Error writing log") } } } /** * Schedule the start of the BackgroundJobService every 10 - 30 seconds * This ensures that the device is properly connected * * @param context allows access to application-specific resources and classes */ fun scheduleJob(context: Context) { val serviceComponent = ComponentName(context, BackgroundJobService::class.java) val builder = JobInfo.Builder(1, serviceComponent) val preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) val intervalTime = preferences.getString("interval_prefs", "10")?.toInt() //val intervalTime = Integer.parseInt(intervalTimeString) //val mJobScheduler = context as JobScheduler (intervalTime?.times(1000))?.toLong()?.let { builder.setMinimumLatency(it) } // wait at least (intervalTime?.times(1000))?.toLong()?.let { builder.setOverrideDeadline(it) } // maximum delay builder.setPersisted(true) // Persist at boot builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) // set required to any network builder.build() //mJobScheduler.schedule(builder.build()) //(getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler).schedule(builder.build()) } /** * Gets and returns the frequency of the connected WiFi network (eg. 2.4 or 5 GHz) * * @param c allows access to application-specific resources and classes * * @return signal frequency of WiFi network (2.4GHz or 5GHz) */ fun frequency(c: Context): Int { val wifiManager = c.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager val freq = wifiManager.connectionInfo.frequency return when (freq / 1000) { 2 -> { Log.d("RadioControl-util", "Frequency = " + freq + "MHz") 2 } 5 -> { Log.d("RadioControl-util", "Frequency = " + freq + "MHz") 5 } else -> 0 } } @SuppressLint("ByteOrderMark") /** * Makes a basic network alert notification * * @param context allows access to application-specific resources and classes * @param mes The main body of the notification * @param vibrate Sets if the notification will vibrate * @param sound Sets if the notification will make a sound * @param heads Should the notification appear in a floating window */ fun sendNote(context: Context, mes: String, vibrate: Boolean, sound: Boolean, heads: Boolean) { val notificationID = 102 createNotificationChannel(context) val pi = PendingIntent.getActivity(context, 1, Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0) //Resources r = getResources(); if (Build.VERSION.SDK_INT >= 26) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notification = Notification.Builder(context, "NetworkAlert") .setContentTitle("Network Alert") .setSmallIcon(R.drawable.ic_network_check_white_48dp) .setContentIntent(pi) .setContentText("Your WiFi connection is not functioning") .setAutoCancel(true) .build() notificationManager.notify(notificationID, notification) } else { val builder = androidx.core.app.NotificationCompat.Builder(context) .setContentTitle("Network Alert") .setSmallIcon(R.drawable.ic_network_check_white_48dp) .setContentIntent(pi) .setContentText("Your WiFi connection is not functioning") .setPriority(3) .setAutoCancel(true) .build() } } private fun createNotificationChannel(context: Context) { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = "Network Alert" val description = "Channel for network related alerts" val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel("networkalert", name, importance) channel.description = description // Register the channel with the system; you can't change the importance // or other notification behaviors after this val notificationManager = context.getSystemService(NotificationManager::class.java) notificationManager!!.createNotificationChannel(channel) } } /** * Get the currently active network info * @param context allows access to application-specific resources and classes * @return ActiveNetwork info */ private fun getNetworkInfo(context: Context): NetworkInfo? { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return cm.activeNetworkInfo } /** * Check if there is any connectivity via WiFi * * @param context allows access to application-specific resources and classes * @return true if connected to a WiFi network. False otherwise */ fun isConnectedWifi(context: Context): Boolean { val info = getNetworkInfo(context) return info != null && info.isConnectedOrConnecting && info.type == ConnectivityManager.TYPE_WIFI } /** * Check if the WiFi module is enabled. * * @param context allows access to application-specific resources and classes * @return True if WiFi is enabled, but not connected. False if otherwise */ fun isWifiOn(context: Context): Boolean { val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager return wifiManager.isWifiEnabled } /** * Check if there is any connectivity at all(local or internet) * * @param context allows access to application-specific resources and classes * @return true if connected to any network */ fun isConnected(context: Context): Boolean { val info = getNetworkInfo(context) return info != null && info.isConnectedOrConnecting } /** * Check if there is any connectivity to a mobile network * @param context * @return return true if the device is connected to a cellular network */ fun isConnectedMobile(context: Context): Boolean { val info = getNetworkInfo(context) return info != null && info.isConnectedOrConnecting && info.type == ConnectivityManager.TYPE_MOBILE } /** * Check if there is fast connectivity * @param context * @return true if the connection is fast wifi/mobile */ fun isConnectedFast(context: Context): Boolean { val info = getNetworkInfo(context) return info != null && info.isConnectedOrConnecting && isConnectionFast(info.type, info.subtype) } /** * Return whether airplane mode is on or off * @param context allows access to application-specific resources and classes * @return true if airplane mode is enabled, false if otherwise */ fun isAirplaneMode(context: Context): Boolean { return Settings.Global.getInt(context.contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0) != 0 } /** * Check if the connection is fast * @param type Type of the current network (WiFi/Mobile) * @param subType A subtype of mobile networks (eg. CDMA, HSPA, UMTS, LTE) * @return true if the connection is faster than 1 Mbps(Or Better than HSPA) * TODO Use transport types: https://developer.android.com/reference/kotlin/android/net/NetworkCapabilities */ private fun isConnectionFast(type: Int, subType: Int): Boolean { return when (type) { ConnectivityManager.TYPE_WIFI -> true //Assume WiFi is fast. TODO possible check for fast internet (but that may take too much CPU time to be efficient) ConnectivityManager.TYPE_MOBILE -> when (subType) { TelephonyManager.NETWORK_TYPE_1xRTT -> false // ~ 50-100 kbps TelephonyManager.NETWORK_TYPE_CDMA -> false // ~ 14-64 kbps TelephonyManager.NETWORK_TYPE_EDGE -> false // ~ 50-100 kbps TelephonyManager.NETWORK_TYPE_EVDO_0 -> false // ~ 400-1000 kbps TelephonyManager.NETWORK_TYPE_EVDO_A -> false // ~ 600-1400 kbps TelephonyManager.NETWORK_TYPE_GPRS -> false // ~ 100 kbps TelephonyManager.NETWORK_TYPE_HSDPA -> true // ~ 2-14 Mbps TelephonyManager.NETWORK_TYPE_HSPA -> false // ~ 700-1700 kbps TelephonyManager.NETWORK_TYPE_HSUPA -> true // ~ 1-23 Mbps TelephonyManager.NETWORK_TYPE_UMTS -> false // ~ 400-7000 kbps TelephonyManager.NETWORK_TYPE_EHRPD // API level 11 -> true // ~ 1-2 Mbps TelephonyManager.NETWORK_TYPE_EVDO_B // API level 9 -> true // ~ 5 Mbps TelephonyManager.NETWORK_TYPE_HSPAP // API level 13 -> true // ~ 10-20 Mbps TelephonyManager.NETWORK_TYPE_IDEN // API level 8 -> false // ~25 kbps TelephonyManager.NETWORK_TYPE_LTE // API level 11 -> true // ~ 10+ Mbps // Unknown TelephonyManager.NETWORK_TYPE_UNKNOWN -> false else -> false } else -> false } } } }
gpl-3.0
7203fa156b800f30fbb04f07da42eb2c
48.533575
324
0.574307
5.273485
false
false
false
false
google/iosched
shared/src/main/java/com/google/samples/apps/iosched/shared/data/ConferenceDataJsonParser.kt
4
5491
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.data import androidx.annotation.Keep import com.google.gson.GsonBuilder import com.google.gson.JsonIOException import com.google.gson.JsonSyntaxException import com.google.samples.apps.iosched.model.Codelab import com.google.samples.apps.iosched.model.ConferenceData import com.google.samples.apps.iosched.model.Room import com.google.samples.apps.iosched.model.Session import com.google.samples.apps.iosched.model.SessionType import com.google.samples.apps.iosched.model.SessionType.KEYNOTE import com.google.samples.apps.iosched.model.SessionType.SESSION import com.google.samples.apps.iosched.model.Speaker import com.google.samples.apps.iosched.model.Tag import com.google.samples.apps.iosched.shared.data.session.json.CodelabDeserializer import com.google.samples.apps.iosched.shared.data.session.json.CodelabTemp import com.google.samples.apps.iosched.shared.data.session.json.RoomDeserializer import com.google.samples.apps.iosched.shared.data.session.json.SessionDeserializer import com.google.samples.apps.iosched.shared.data.session.json.SessionTemp import com.google.samples.apps.iosched.shared.data.session.json.SpeakerDeserializer import com.google.samples.apps.iosched.shared.data.session.json.TagDeserializer import java.io.InputStream object ConferenceDataJsonParser { @Throws(JsonIOException::class, JsonSyntaxException::class) fun parseConferenceData(unprocessedSessionData: InputStream): ConferenceData { val jsonReader = com.google.gson.stream.JsonReader(unprocessedSessionData.reader()) val gson = GsonBuilder() .registerTypeAdapter(SessionTemp::class.java, SessionDeserializer()) .registerTypeAdapter(Tag::class.java, TagDeserializer()) .registerTypeAdapter(Speaker::class.java, SpeakerDeserializer()) .registerTypeAdapter(Room::class.java, RoomDeserializer()) .registerTypeAdapter(CodelabTemp::class.java, CodelabDeserializer()) .create() val tempData: TempConferenceData = gson.fromJson(jsonReader, TempConferenceData::class.java) return normalize(tempData) } /** * Adds nested objects like `session.tags` to `sessions` */ private fun normalize(data: TempConferenceData): ConferenceData { val sessions = mutableListOf<Session>() data.sessions.forEach { session: SessionTemp -> val tags = data.tags.filter { it.tagName in session.tagNames } val type = SessionType.fromTags(tags) val displayTags = if (type == SESSION || type == KEYNOTE) { tags.filter { it.category == Tag.CATEGORY_TOPIC } } else { emptyList() } val newSession = Session( id = session.id, startTime = session.startTime, endTime = session.endTime, title = session.title, description = session.description, sessionUrl = session.sessionUrl, isLivestream = session.isLivestream, youTubeUrl = session.youTubeUrl, doryLink = session.doryLink, tags = tags, displayTags = displayTags, speakers = session.speakers.mapNotNull { data.speakers[it] }.toSet(), photoUrl = session.photoUrl, relatedSessions = session.relatedSessions, room = data.rooms.firstOrNull { it.id == session.room } ) sessions.add(newSession) } val codelabs = mutableListOf<Codelab>() data.codelabs.forEach { codelab: CodelabTemp -> val tags = data.tags.filter { it.category == Tag.CATEGORY_TOPIC && it.tagName in codelab.tagNames } val newCodelab = Codelab( id = codelab.id, title = codelab.title, description = codelab.description, durationMinutes = codelab.durationMinutes, iconUrl = codelab.iconUrl, codelabUrl = codelab.codelabUrl, sortPriority = codelab.sortPriority, tags = tags ) codelabs.add(newCodelab) } return ConferenceData( sessions = sessions, speakers = data.speakers.values.toList(), rooms = data.rooms, codelabs = codelabs, tags = data.tags, version = data.version ) } } /** * Temporary data type for conference data where some collections are lists of IDs instead * of lists of domain objects. */ @Keep data class TempConferenceData( val sessions: List<SessionTemp>, val speakers: Map<String, Speaker>, val rooms: List<Room>, val codelabs: List<CodelabTemp>, val tags: List<Tag>, val version: Int )
apache-2.0
729ffb217d6c2937b547b50fd5868e20
40.285714
100
0.667456
4.538017
false
false
false
false
JetBrains/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/handlers/MarkdownTableReformatAfterActionHook.kt
1
2656
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.tables.handlers import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler import com.intellij.psi.PsiDocumentManager import org.intellij.plugins.markdown.editor.tables.TableFormattingUtils.reformatColumnOnChange import org.intellij.plugins.markdown.editor.tables.TableUtils import org.intellij.plugins.markdown.settings.MarkdownSettings internal class MarkdownTableReformatAfterActionHook(private val baseHandler: EditorActionHandler?): EditorWriteActionHandler() { override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean { return baseHandler?.isEnabled(editor, caret, dataContext) == true } override fun executeWriteAction(editor: Editor, caret: Caret?, dataContext: DataContext?) { baseHandler?.execute(editor, caret, dataContext) actuallyExecute(editor, caret, dataContext) } private fun actuallyExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) { val project = editor.project ?: return if (!TableUtils.isTableSupportEnabled() || !MarkdownSettings.getInstance(project).isEnhancedEditingEnabled) { return } val document = editor.document val caretOffset = caret?.offset ?: return if (!TableUtils.isProbablyInsideTableCell(document, caretOffset) || editor.caretModel.caretCount != 1) { return } val documentManager = PsiDocumentManager.getInstance(project) val file = documentManager.getPsiFile(document) ?: return if (!TableUtils.isFormattingEnabledForTables(file)) { return } PsiDocumentManager.getInstance(project).commitDocument(document) val cell = TableUtils.findCell(file, caretOffset) val table = cell?.parentTable val columnIndex = cell?.columnIndex if (cell == null || table == null || columnIndex == null) { return } val text = document.charsSequence if (cell.textRange.let { text.substring(it.startOffset, it.endOffset) }.isBlank()) { return } executeCommand(table.project) { table.reformatColumnOnChange( document, editor.caretModel.allCarets, columnIndex, trimToMaxContent = false, preventExpand = false ) } } }
apache-2.0
f19a5ed22be7610d812c8c652f287d64
42.540984
158
0.755271
4.69258
false
false
false
false
vhromada/Catalog
web/src/main/kotlin/com/github/vhromada/catalog/web/connector/common/RestRequest.kt
1
1315
package com.github.vhromada.catalog.web.connector.common import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpEntity import org.springframework.http.HttpMethod /** * A class represents request for REST. * * @param T type of receiving data * @author Vladimir Hromada */ class RestRequest<T>( /** * HTTP method */ val method: HttpMethod, /** * URL */ val url: String, /** * Entity */ private val entity: Any? = null, /** * Response type */ val responseType: Class<T>? = null, /** * Parameterized response type */ val parameterizedType: ParameterizedTypeReference<T>? = null, /** * Parameters */ val params: Map<String, Any> = emptyMap() ) { init { require((parameterizedType != null && responseType == null) || (parameterizedType == null && responseType != null)) { "Only one of attribute parameterizedType or responseType is required" } } /** * Returns HTTP entity. * * @return HTTP entity */ fun httpEntity(): HttpEntity<*> { return when (entity) { null -> HttpEntity<Any>(null, null) is HttpEntity<*> -> entity else -> HttpEntity<Any>(entity) } } }
mit
a84b889cb8e279fddc7c039920bc6ac3
20.209677
197
0.592395
4.472789
false
false
false
false
domdomegg/apps-android-commons
app/src/main/java/fr/free/nrw/commons/upload/worker/UploadWorker.kt
2
21125
package fr.free.nrw.commons.upload.worker import android.annotation.SuppressLint import android.app.PendingIntent import android.app.TaskStackBuilder import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.work.CoroutineWorker import androidx.work.Data import androidx.work.WorkerParameters import com.mapbox.mapboxsdk.plugins.localization.BuildConfig import dagger.android.ContributesAndroidInjector import fr.free.nrw.commons.CommonsApplication import fr.free.nrw.commons.Media import fr.free.nrw.commons.R import fr.free.nrw.commons.auth.SessionManager import fr.free.nrw.commons.contributions.ChunkInfo import fr.free.nrw.commons.contributions.Contribution import fr.free.nrw.commons.contributions.ContributionDao import fr.free.nrw.commons.contributions.MainActivity import fr.free.nrw.commons.customselector.database.UploadedStatus import fr.free.nrw.commons.customselector.database.UploadedStatusDao import fr.free.nrw.commons.di.ApplicationlessInjection import fr.free.nrw.commons.media.MediaClient import fr.free.nrw.commons.theme.BaseActivity import fr.free.nrw.commons.upload.StashUploadResult import fr.free.nrw.commons.upload.FileUtilsWrapper import fr.free.nrw.commons.upload.StashUploadState import fr.free.nrw.commons.upload.UploadClient import fr.free.nrw.commons.upload.UploadResult import fr.free.nrw.commons.wikidata.WikidataEditService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import timber.log.Timber import java.util.* import java.util.regex.Pattern import javax.inject.Inject import kotlin.collections.ArrayList class UploadWorker(var appContext: Context, workerParams: WorkerParameters) : CoroutineWorker(appContext, workerParams) { private var notificationManager: NotificationManagerCompat? = null @Inject lateinit var wikidataEditService: WikidataEditService @Inject lateinit var sessionManager: SessionManager @Inject lateinit var contributionDao: ContributionDao @Inject lateinit var uploadedStatusDao: UploadedStatusDao @Inject lateinit var uploadClient: UploadClient @Inject lateinit var mediaClient: MediaClient @Inject lateinit var fileUtilsWrapper: FileUtilsWrapper private val PROCESSING_UPLOADS_NOTIFICATION_TAG = BuildConfig.APPLICATION_ID + " : upload_tag" private val PROCESSING_UPLOADS_NOTIFICATION_ID = 101 //Attributes of the current-upload notification private var currentNotificationID: Int = -1// lateinit is not allowed with primitives private lateinit var currentNotificationTag: String private var curentNotification: NotificationCompat.Builder private val statesToProcess= ArrayList<Int>() private val STASH_ERROR_CODES = Arrays .asList( "uploadstash-file-not-found", "stashfailed", "verification-error", "chunk-too-small" ) init { ApplicationlessInjection .getInstance(appContext) .commonsApplicationComponent .inject(this) curentNotification = getNotificationBuilder(CommonsApplication.NOTIFICATION_CHANNEL_ID_ALL)!! statesToProcess.add(Contribution.STATE_QUEUED) statesToProcess.add(Contribution.STATE_QUEUED_LIMITED_CONNECTION_MODE) } @dagger.Module interface Module { @ContributesAndroidInjector fun worker(): UploadWorker } open inner class NotificationUpdateProgressListener( private var notificationFinishingTitle: String?, var contribution: Contribution? ) { fun onProgress(transferred: Long, total: Long) { if (transferred == total) { // Completed! curentNotification.setContentTitle(notificationFinishingTitle) .setProgress(0, 100, true) } else { curentNotification .setProgress( 100, (transferred.toDouble() / total.toDouble() * 100).toInt(), false ) } notificationManager?.cancel(PROCESSING_UPLOADS_NOTIFICATION_TAG, PROCESSING_UPLOADS_NOTIFICATION_ID) notificationManager?.notify( currentNotificationTag, currentNotificationID, curentNotification.build()!! ) contribution!!.transferred = transferred contributionDao.update(contribution).blockingAwait() } open fun onChunkUploaded(contribution: Contribution, chunkInfo: ChunkInfo?) { contribution.chunkInfo = chunkInfo contributionDao.update(contribution).blockingAwait() } } private fun getNotificationBuilder(channelId: String): NotificationCompat.Builder? { return NotificationCompat.Builder(appContext, channelId) .setAutoCancel(true) .setSmallIcon(R.drawable.ic_launcher) .setLargeIcon( BitmapFactory.decodeResource( appContext.resources, R.drawable.ic_launcher ) ) .setAutoCancel(true) .setOnlyAlertOnce(true) .setProgress(100, 0, true) .setOngoing(true) } override suspend fun doWork(): Result { var countUpload = 0 notificationManager = NotificationManagerCompat.from(appContext) val processingUploads = getNotificationBuilder( CommonsApplication.NOTIFICATION_CHANNEL_ID_ALL )!! withContext(Dispatchers.IO) { val queuedContributions = contributionDao.getContribution(statesToProcess) .blockingGet() //Showing initial notification for the number of uploads being processed Timber.e("Queued Contributions: "+ queuedContributions.size) processingUploads.setContentTitle(appContext.getString(R.string.starting_uploads)) processingUploads.setContentText( appContext.resources.getQuantityString( R.plurals.starting_multiple_uploads, queuedContributions.size, queuedContributions.size ) ) notificationManager?.notify( PROCESSING_UPLOADS_NOTIFICATION_TAG, PROCESSING_UPLOADS_NOTIFICATION_ID, processingUploads.build() ) /** * To avoid race condition when multiple of these workers are working, assign this state so that the next one does not process these contribution again */ queuedContributions.forEach { it.state=Contribution.STATE_IN_PROGRESS contributionDao.saveSynchronous(it) } queuedContributions.asFlow().map { contribution -> /** * If the limited connection mode is on, lets iterate through the queued * contributions * and set the state as STATE_QUEUED_LIMITED_CONNECTION_MODE , * otherwise proceed with the upload */ if (isLimitedConnectionModeEnabled()) { if (contribution.state == Contribution.STATE_QUEUED) { contribution.state = Contribution.STATE_QUEUED_LIMITED_CONNECTION_MODE contributionDao.saveSynchronous(contribution) } } else { contribution.transferred = 0 contribution.state = Contribution.STATE_IN_PROGRESS contributionDao.saveSynchronous(contribution) setProgressAsync(Data.Builder().putInt("progress", countUpload).build()) countUpload++ uploadContribution(contribution = contribution) } }.collect() //Dismiss the global notification notificationManager?.cancel( PROCESSING_UPLOADS_NOTIFICATION_TAG, PROCESSING_UPLOADS_NOTIFICATION_ID ) } //TODO make this smart, think of handling retries in the future return Result.success() } /** * Returns true is the limited connection mode is enabled */ private fun isLimitedConnectionModeEnabled(): Boolean { return sessionManager.getPreference(CommonsApplication.IS_LIMITED_CONNECTION_MODE_ENABLED) } /** * Upload the contribution * @param contribution */ @SuppressLint("StringFormatInvalid") private suspend fun uploadContribution(contribution: Contribution) { if (contribution.localUri == null || contribution.localUri.path == null) { Timber.e("""upload: ${contribution.media.filename} failed, file path is null""") } val media = contribution.media val displayTitle = contribution.media.displayTitle currentNotificationTag = contribution.localUri.toString() currentNotificationID = (contribution.localUri.toString() + contribution.media.filename).hashCode() curentNotification getNotificationBuilder(CommonsApplication.NOTIFICATION_CHANNEL_ID_ALL)!! curentNotification.setContentTitle( appContext.getString( R.string.upload_progress_notification_title_start, displayTitle ) ) notificationManager?.notify( currentNotificationTag, currentNotificationID, curentNotification.build()!! ) val filename = media.filename val notificationProgressUpdater = NotificationUpdateProgressListener( appContext.getString( R.string.upload_progress_notification_title_finishing, displayTitle ), contribution ) try { //Upload the file to stash val stashUploadResult = uploadClient.uploadFileToStash( appContext, filename, contribution, notificationProgressUpdater ).onErrorReturn{ return@onErrorReturn StashUploadResult(StashUploadState.FAILED,fileKey = null) }.blockingSingle() when (stashUploadResult.state) { StashUploadState.SUCCESS -> { //If the stash upload succeeds Timber.d("Upload to stash success for fileName: $filename") Timber.d("Ensure uniqueness of filename"); val uniqueFileName = findUniqueFileName(filename!!) try { //Upload the file from stash val uploadResult = uploadClient.uploadFileFromStash( contribution, uniqueFileName, stashUploadResult.fileKey ).onErrorReturn { return@onErrorReturn null }.blockingSingle() if (null != uploadResult && uploadResult.isSuccessful()) { Timber.d( "Stash Upload success..proceeding to make wikidata edit" ) wikidataEditService.addDepictionsAndCaptions(uploadResult, contribution) .blockingSubscribe(); if(contribution.wikidataPlace==null){ Timber.d( "WikiDataEdit not required, upload success" ) saveCompletedContribution(contribution,uploadResult) }else{ Timber.d( "WikiDataEdit not required, making wikidata edit" ) makeWikiDataEdit(uploadResult, contribution) } showSuccessNotification(contribution) } else { Timber.e("Stash Upload failed") showFailedNotification(contribution) contribution.state = Contribution.STATE_FAILED contribution.chunkInfo = null contributionDao.save(contribution).blockingAwait() } }catch (exception : Exception){ Timber.e(exception) Timber.e("Upload from stash failed for contribution : $filename") showFailedNotification(contribution) contribution.state=Contribution.STATE_FAILED contributionDao.saveSynchronous(contribution) if (STASH_ERROR_CODES.contains(exception.message)) { clearChunks(contribution) } } } StashUploadState.PAUSED -> { showPausedNotification(contribution) contribution.state = Contribution.STATE_PAUSED contributionDao.saveSynchronous(contribution) } else -> { Timber.e("""upload file to stash failed with status: ${stashUploadResult.state}""") showFailedNotification(contribution) contribution.state = Contribution.STATE_FAILED contribution.chunkInfo = null contributionDao.saveSynchronous(contribution) } } }catch (exception: Exception){ Timber.e(exception) Timber.e("Stash upload failed for contribution: $filename") showFailedNotification(contribution) contribution.state=Contribution.STATE_FAILED clearChunks(contribution) } } private fun clearChunks(contribution: Contribution) { contribution.chunkInfo=null contributionDao.saveSynchronous(contribution) } /** * Make the WikiData Edit, if applicable */ private suspend fun makeWikiDataEdit(uploadResult: UploadResult, contribution: Contribution) { val wikiDataPlace = contribution.wikidataPlace if (wikiDataPlace != null && wikiDataPlace.imageValue == null) { if (!contribution.hasInvalidLocation()) { var revisionID: Long?=null try { revisionID = wikidataEditService.createClaim( wikiDataPlace, uploadResult.filename, contribution.media.captions ) if (null != revisionID) { showSuccessNotification(contribution) } }catch (exception: Exception){ Timber.e(exception) } withContext(Dispatchers.Main) { wikidataEditService.handleImageClaimResult( contribution.wikidataPlace, revisionID ) } } else { withContext(Dispatchers.Main) { wikidataEditService.handleImageClaimResult( contribution.wikidataPlace, null ) } } } saveCompletedContribution(contribution, uploadResult) } private fun saveCompletedContribution(contribution: Contribution, uploadResult: UploadResult) { val contributionFromUpload = mediaClient.getMedia("File:" + uploadResult.filename) .map { media: Media? -> contribution.completeWith(media!!) } .blockingGet() contributionFromUpload.dateModified=Date() contributionDao.deleteAndSaveContribution(contribution, contributionFromUpload) // Upload success, save to uploaded status. saveIntoUploadedStatus(contribution) } /** * Save to uploadedStatusDao. */ private fun saveIntoUploadedStatus(contribution: Contribution) { contribution.contentUri?.let { val imageSha1 = fileUtilsWrapper.getSHA1(appContext.contentResolver.openInputStream(it)) val modifiedSha1 = fileUtilsWrapper.getSHA1(fileUtilsWrapper.getFileInputStream(contribution.localUri?.path)) MainScope().launch { uploadedStatusDao.insertUploaded( UploadedStatus( imageSha1, modifiedSha1, imageSha1 == modifiedSha1, true ) ); } } } private fun findUniqueFileName(fileName: String): String { var sequenceFileName: String? var sequenceNumber = 1 while (true) { sequenceFileName = if (sequenceNumber == 1) { fileName } else { if (fileName.indexOf('.') == -1) { "$fileName $sequenceNumber" } else { val regex = Pattern.compile("^(.*)(\\..+?)$") val regexMatcher = regex.matcher(fileName) regexMatcher.replaceAll("$1 $sequenceNumber$2") } } if (!mediaClient.checkPageExistsUsingTitle( String.format( "File:%s", sequenceFileName ) ) .blockingGet() ) { break } sequenceNumber++ } return sequenceFileName!! } /** * Notify that the current upload has succeeded * @param contribution */ @SuppressLint("StringFormatInvalid") private fun showSuccessNotification(contribution: Contribution) { val displayTitle = contribution.media.displayTitle contribution.state=Contribution.STATE_COMPLETED curentNotification.setContentTitle( appContext.getString( R.string.upload_completed_notification_title, displayTitle ) ) .setContentText(appContext.getString(R.string.upload_completed_notification_text)) .setProgress(0, 0, false) .setOngoing(false) notificationManager?.notify( currentNotificationTag, currentNotificationID, curentNotification.build() ) } /** * Notify that the current upload has failed * @param contribution */ @SuppressLint("StringFormatInvalid") private fun showFailedNotification(contribution: Contribution) { val displayTitle = contribution.media.displayTitle curentNotification.setContentIntent(getPendingIntent(MainActivity::class.java)) curentNotification.setContentTitle( appContext.getString( R.string.upload_failed_notification_title, displayTitle ) ) .setContentText(appContext.getString(R.string.upload_failed_notification_subtitle)) .setProgress(0, 0, false) .setOngoing(false) notificationManager?.notify( currentNotificationTag, currentNotificationID, curentNotification.build() ) } /** * Notify that the current upload is paused * @param contribution */ private fun showPausedNotification(contribution: Contribution) { val displayTitle = contribution.media.displayTitle curentNotification.setContentTitle( appContext.getString( R.string.upload_paused_notification_title, displayTitle ) ) .setContentText(appContext.getString(R.string.upload_paused_notification_subtitle)) .setProgress(0, 0, false) .setOngoing(false) notificationManager!!.notify( currentNotificationTag, currentNotificationID, curentNotification.build() ) } /** * Method used to get Pending intent for opening different screen after clicking on notification * @param toClass */ private fun getPendingIntent(toClass:Class<out BaseActivity>):PendingIntent { val intent = Intent(appContext,toClass) return TaskStackBuilder.create(appContext).run { addNextIntentWithParentStack(intent) getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT) }; } }
apache-2.0
1e019a2e9493d549c28e584f12b62d46
37.621572
121
0.596876
5.840476
false
false
false
false
domdomegg/apps-android-commons
app/src/test/kotlin/fr/free/nrw/commons/recentlanguages/RecentLanguagesDaoUnitTest.kt
2
6888
package fr.free.nrw.commons.recentlanguages import android.content.ContentProviderClient import android.content.ContentValues import android.database.Cursor import android.database.MatrixCursor import android.database.sqlite.SQLiteDatabase import android.os.RemoteException import com.nhaarman.mockitokotlin2.* import fr.free.nrw.commons.TestCommonsApplication import fr.free.nrw.commons.recentlanguages.RecentLanguagesDao.Table.* import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [21], application = TestCommonsApplication::class) class RecentLanguagesDaoUnitTest { private val columns = arrayOf( COLUMN_NAME, COLUMN_CODE ) private val client: ContentProviderClient = mock() private val database: SQLiteDatabase = mock() private val captor = argumentCaptor<ContentValues>() private lateinit var testObject: RecentLanguagesDao private lateinit var exampleLanguage: Language /** * Set up Test Language and RecentLanguagesDao */ @Before fun setUp() { exampleLanguage = Language("English", "en") testObject = RecentLanguagesDao { client } } @Test fun createTable() { onCreate(database) verify(database).execSQL(CREATE_TABLE_STATEMENT) } @Test fun deleteTable() { onDelete(database) inOrder(database) { verify(database).execSQL(DROP_TABLE_STATEMENT) } } @Test fun createFromCursor() { createCursor(1).let { cursor -> cursor.moveToFirst() testObject.fromCursor(cursor).let { Assert.assertEquals("languageName", it.languageName) Assert.assertEquals("languageCode", it.languageCode) } } } @Test fun testGetRecentLanguages() { whenever(client.query(any(), any(), anyOrNull(), any(), anyOrNull())) .thenReturn(createCursor(14)) val result = testObject.recentLanguages Assert.assertEquals(14, (result.size)) } @Test(expected = RuntimeException::class) fun getGetRecentLanguagesTranslatesExceptions() { whenever(client.query(any(), any(), anyOrNull(), any(), anyOrNull())).thenThrow( RemoteException("") ) testObject.recentLanguages } @Test fun getGetRecentLanguagesReturnsEmptyList_emptyCursor() { whenever(client.query(any(), any(), anyOrNull(), any(), anyOrNull())) .thenReturn(createCursor(0)) Assert.assertTrue(testObject.recentLanguages.isEmpty()) } @Test fun getGetRecentLanguagesReturnsEmptyList_nullCursor() { whenever(client.query(any(), any(), anyOrNull(), any(), anyOrNull())).thenReturn(null) Assert.assertTrue(testObject.recentLanguages.isEmpty()) } @Test fun cursorsAreClosedAfterGetRecentLanguages() { val mockCursor: Cursor = mock() whenever(client.query(any(), any(), anyOrNull(), any(), anyOrNull())).thenReturn(mockCursor) whenever(mockCursor.moveToFirst()).thenReturn(false) testObject.recentLanguages verify(mockCursor).close() } @Test fun findExistingLanguage() { whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenReturn(createCursor(1)) Assert.assertTrue(testObject.findRecentLanguage(exampleLanguage.languageCode)) } @Test(expected = RuntimeException::class) fun findLanguageTranslatesExceptions() { whenever(client.query(any(), any(), anyOrNull(), any(), anyOrNull())).thenThrow( RemoteException("") ) testObject.findRecentLanguage(exampleLanguage.languageCode) } @Test fun findNotExistingLanguageReturnsNull_emptyCursor() { whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenReturn(createCursor(0)) Assert.assertFalse(testObject.findRecentLanguage(exampleLanguage.languageCode)) } @Test fun findNotExistingLanguageReturnsNull_nullCursor() { whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenReturn(null) Assert.assertFalse(testObject.findRecentLanguage(exampleLanguage.languageCode)) } @Test fun cursorsAreClosedAfterFindLanguageQuery() { val mockCursor: Cursor = mock() whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenReturn(mockCursor) whenever(mockCursor.moveToFirst()).thenReturn(false) testObject.findRecentLanguage(exampleLanguage.languageCode) verify(mockCursor).close() } @Test fun migrateTableVersionFrom_v1_to_v2() { onUpdate(database, 1, 2) // Table didnt exist before v7 verifyZeroInteractions(database) } @Test fun migrateTableVersionFrom_v2_to_v3() { onUpdate(database, 2, 3) // Table didnt exist before v7 verifyZeroInteractions(database) } @Test fun migrateTableVersionFrom_v3_to_v4() { onUpdate(database, 3, 4) // Table didnt exist before v7 verifyZeroInteractions(database) } @Test fun migrateTableVersionFrom_v4_to_v5() { onUpdate(database, 4, 5) // Table didnt exist before v7 verifyZeroInteractions(database) } @Test fun migrateTableVersionFrom_v5_to_v6() { onUpdate(database, 5, 6) // Table didnt exist before v7 verifyZeroInteractions(database) } @Test fun migrateTableVersionFrom_v6_to_v7() { onUpdate(database, 6, 7) verify(database).execSQL(CREATE_TABLE_STATEMENT) } @Test fun migrateTableVersionFrom_v7_to_v8() { onUpdate(database, 7, 8) // Table didnt change in version 8 verifyZeroInteractions(database) } @Test fun testAddNewLanguage() { testObject.addRecentLanguage(exampleLanguage) verify(client).insert(eq(RecentLanguagesContentProvider.BASE_URI), captor.capture()) captor.firstValue.let { cv -> Assert.assertEquals(2, cv.size()) Assert.assertEquals( exampleLanguage.languageName, cv.getAsString(COLUMN_NAME) ) Assert.assertEquals( exampleLanguage.languageCode, cv.getAsString(COLUMN_CODE) ) } } @Test fun testDeleteLanguage() { testObject.addRecentLanguage(exampleLanguage) testObject.deleteRecentLanguage(exampleLanguage.languageCode) } private fun createCursor(rowCount: Int) = MatrixCursor(columns, rowCount).apply { for (i in 0 until rowCount) { addRow(listOf("languageName", "languageCode")) } } }
apache-2.0
c9ebd210d1d696a85adcf29fe8b07a79
29.348018
100
0.657375
4.650912
false
true
false
false
DmytroTroynikov/aemtools
lang/src/test/kotlin/com/aemtools/lang/clientlib/reference/CdReferenceTest.kt
1
1214
package com.aemtools.lang.clientlib.reference import com.aemtools.test.reference.BaseReferenceTest import com.intellij.psi.PsiFile /** * @author Dmytro_Troynikov */ class CdReferenceTest : BaseReferenceTest() { fun testReferenceToFileInSameDir() = testReference { addFile("component/js.txt", "${CARET}file.js") addFile("component/file.js", "included") shouldResolveTo(PsiFile::class.java) shouldContainText("included") } fun testReferenceInSubdirectory() = testReference { addFile("component/js.txt", "${CARET}js/file.js") addFile("component/js/file.js", "included") shouldResolveTo(PsiFile::class.java) shouldContainText("included") } fun testReferenceInSubdirectoryWithBasePath() = testReference { addFile("component/js.txt", """ #base=js ${CARET}file.js """.trimIndent()) addFile("component/js/file.js", "included") shouldResolveTo(PsiFile::class.java) shouldContainText("included") } fun testReferenceToParentDirectory() = testReference { addFile("component/js.txt", "$CARET../file.js") addFile("file.js", "included") shouldResolveTo(PsiFile::class.java) shouldContainText("included") } }
gpl-3.0
3f9ac3046698117a5852031d21e6b5d0
27.904762
65
0.696046
3.96732
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/classes/implementComparableInSubclass.kt
5
397
// See KT-12865 package foo abstract class Base { val x = 23 } class Derived : Base(), Comparable<Derived> { val y = 42 override fun compareTo(other: Derived): Int { throw UnsupportedOperationException("not implemented") } } fun box(): String { val b = Derived() if (b.x != 23) return "fail1: ${b.x}" if (b.y != 42) return "fail2: ${b.y}" return "OK" }
apache-2.0
2f4b50c4ff301bef0dc5adce3c537349
17.090909
62
0.589421
3.308333
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/math/Vec3.kt
1
16389
package de.fabmax.kool.math import kotlin.math.abs import kotlin.math.cos import kotlin.math.sin import kotlin.math.sqrt open class Vec3f(x: Float, y: Float, z: Float) { protected val fields = FloatArray(3) open val x get() = this[0] open val y get() = this[1] open val z get() = this[2] constructor(f: Float) : this(f, f, f) constructor(v: Vec3f) : this(v.x, v.y, v.z) init { fields[0] = x fields[1] = y fields[2] = z } fun add(other: Vec3f, result: MutableVec3f): MutableVec3f = result.set(this).add(other) fun cross(other: Vec3f, result: MutableVec3f): MutableVec3f { result.x = y * other.z - z * other.y result.y = z * other.x - x * other.z result.z = x * other.y - y * other.x return result } fun distance(other: Vec3f): Float = sqrt(sqrDistance(other)) fun dot(other: Vec3f): Float = x * other.x + y * other.y + z * other.z /** * Checks vector components for equality using [de.fabmax.kool.math.isFuzzyEqual], that is all components must * have a difference less or equal [eps]. */ fun isFuzzyEqual(other: Vec3f, eps: Float = FUZZY_EQ_F): Boolean = isFuzzyEqual(x, other.x, eps) && isFuzzyEqual(y, other.y, eps) && isFuzzyEqual(z, other.z, eps) fun length(): Float = sqrt(sqrLength()) fun mix(other: Vec3f, weight: Float, result: MutableVec3f): MutableVec3f { result.x = other.x * weight + x * (1f - weight) result.y = other.y * weight + y * (1f - weight) result.z = other.z * weight + z * (1f - weight) return result } fun mul(other: Vec3f, result: MutableVec3f): MutableVec3f = result.set(this).mul(other) fun norm(result: MutableVec3f): MutableVec3f = result.set(this).norm() fun planeSpace(p: MutableVec3f, q: MutableVec3f) { if (abs(z) > SQRT_1_2) { // choose p in y-z plane val a = y*y + z*z val k = 1f / sqrt(a) p.x = 0f p.y = -z * k p.z = y * k // q = this x p q.x = a * k q.y = -x * p.z q.z = x * p.y } else { // choose p in x-y plane val a = x*x + y*y val k = 1f / sqrt(a) p.x = -y * k p.y = x * k p.z = 0f // q = this x p q.x = -z * p.y q.y = z * p.x q.z = a * k } } fun rotate(angleDeg: Float, axisX: Float, axisY: Float, axisZ: Float, result: MutableVec3f): MutableVec3f = result.set(this).rotate(angleDeg, axisX, axisY, axisZ) fun rotate(angleDeg: Float, axis: Vec3f, result: MutableVec3f): MutableVec3f = result.set(this).rotate(angleDeg, axis.x, axis.y, axis.z) fun scale(factor: Float, result: MutableVec3f): MutableVec3f = result.set(this).scale(factor) fun sqrDistance(other: Vec3f): Float { val dx = x - other.x val dy = y - other.y val dz = z - other.z return dx*dx + dy*dy + dz*dz } fun sqrLength(): Float = x*x + y*y + z*z fun subtract(other: Vec3f, result: MutableVec3f): MutableVec3f = result.set(this).subtract(other) open operator fun get(i: Int) = fields[i] operator fun times(other: Vec3f): Float = dot(other) override fun toString(): String = "($x, $y, $z)" fun toVec3d(): Vec3d = Vec3d(x.toDouble(), y.toDouble(), z.toDouble()) fun toMutableVec3d(): MutableVec3d = toMutableVec3d(MutableVec3d()) fun toMutableVec3d(result: MutableVec3d): MutableVec3d = result.set(x.toDouble(), y.toDouble(), z.toDouble()) /** * Checks vector components for equality (using '==' operator). For better numeric stability consider using * [isFuzzyEqual]. */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Vec3f) return false if (x != other.x) return false if (y != other.y) return false if (z != other.z) return false return true } override fun hashCode(): Int { var result = x.hashCode() result = 31 * result + y.hashCode() result = 31 * result + z.hashCode() return result } companion object { val ZERO = Vec3f(0f) val ONES = Vec3f(1f) val X_AXIS = Vec3f(1f, 0f, 0f) val Y_AXIS = Vec3f(0f, 1f, 0f) val Z_AXIS = Vec3f(0f, 0f, 1f) val NEG_X_AXIS = Vec3f(-1f, 0f, 0f) val NEG_Y_AXIS = Vec3f(0f, -1f, 0f) val NEG_Z_AXIS = Vec3f(0f, 0f, -1f) } } open class MutableVec3f(x: Float, y: Float, z: Float) : Vec3f(x, y, z) { override var x get() = this[0] set(value) { this[0] = value } override var y get() = this[1] set(value) { this[1] = value } override var z get() = this[2] set(value) { this[2] = value } val array: FloatArray get() = fields constructor() : this(0f, 0f, 0f) constructor(f: Float) : this(f, f, f) constructor(v: Vec3f) : this(v.x, v.y, v.z) fun add(other: Vec3f): MutableVec3f { x += other.x y += other.y z += other.z return this } fun mul(other: Vec3f): MutableVec3f { x *= other.x y *= other.y z *= other.z return this } fun norm(): MutableVec3f { val l = length() return if (l != 0f) { scale(1f / l) } else { set(ZERO) } } fun rotate(angleDeg: Float, axisX: Float, axisY: Float, axisZ: Float): MutableVec3f { val rad = angleDeg.toRad() val c = cos(rad) val c1 = 1f - c val s = sin(rad) val rx = x * (axisX * axisX * c1 + c) + y * (axisX * axisY * c1 - axisZ * s) + z * (axisX * axisZ * c1 + axisY * s) val ry = x * (axisY * axisX * c1 + axisZ * s) + y * (axisY * axisY * c1 + c) + z * (axisY * axisZ * c1 - axisX * s) val rz = x * (axisX * axisZ * c1 - axisY * s) + y * (axisY * axisZ * c1 + axisX * s) + z * (axisZ * axisZ * c1 + c) x = rx y = ry z = rz return this } fun rotate(angleDeg: Float, axis: Vec3f): MutableVec3f = rotate(angleDeg, axis.x, axis.y, axis.z) fun scale(factor: Float): MutableVec3f { x *= factor y *= factor z *= factor return this } fun set(x: Float, y: Float, z: Float): MutableVec3f { this.x = x this.y = y this.z = z return this } fun set(other: Vec3f): MutableVec3f { x = other.x y = other.y z = other.z return this } fun subtract(other: Vec3f): MutableVec3f { x -= other.x y -= other.y z -= other.z return this } operator fun divAssign(div: Float) { scale(1f / div) } operator fun minusAssign(other: Vec3f) { subtract(other) } operator fun plusAssign(other: Vec3f) { add(other) } open operator fun set(i: Int, v: Float) { fields[i] = v } operator fun timesAssign(factor: Float) { scale(factor) } } open class Vec3d(x: Double, y: Double, z: Double) { protected val fields = DoubleArray(3) open val x get() = this[0] open val y get() = this[1] open val z get() = this[2] constructor(f: Double) : this(f, f, f) constructor(v: Vec3d) : this(v.x, v.y, v.z) init { fields[0] = x fields[1] = y fields[2] = z } fun add(other: Vec3d, result: MutableVec3d): MutableVec3d = result.set(this).add(other) fun cross(other: Vec3d, result: MutableVec3d): MutableVec3d { result.x = y * other.z - z * other.y result.y = z * other.x - x * other.z result.z = x * other.y - y * other.x return result } fun distance(other: Vec3d): Double = sqrt(sqrDistance(other)) fun dot(other: Vec3d): Double = x * other.x + y * other.y + z * other.z /** * Checks vector components for equality using [de.fabmax.kool.math.isFuzzyEqual], that is all components must * have a difference less or equal [eps]. */ fun isFuzzyEqual(other: Vec3d, eps: Double = FUZZY_EQ_D): Boolean = isFuzzyEqual(x, other.x, eps) && isFuzzyEqual(y, other.y, eps) && isFuzzyEqual(z, other.z, eps) fun length(): Double = sqrt(sqrLength()) fun mix(other: Vec3d, weight: Double, result: MutableVec3d): MutableVec3d { result.x = other.x * weight + x * (1.0 - weight) result.y = other.y * weight + y * (1.0 - weight) result.z = other.z * weight + z * (1.0 - weight) return result } fun mul(other: Vec3d, result: MutableVec3d): MutableVec3d = result.set(this).mul(other) fun norm(result: MutableVec3d): MutableVec3d = result.set(this).norm() fun planeSpace(p: MutableVec3d, q: MutableVec3d) { if (abs(z) > SQRT_1_2) { // choose p in y-z plane val a = y*y + z*z val k = 1.0 / sqrt(a) p.x = 0.0 p.y = -z * k p.z = y * k // q = this x p q.x = a * k q.y = -x * p.z q.z = x * p.y } else { // choose p in x-y plane val a = x*x + y*y val k = 1.0 / sqrt(a) p.x = -y * k p.y = x * k p.z = 0.0 // q = this x p q.x = -z * p.y q.y = z * p.x q.z = a * k } } fun rotate(angleDeg: Double, axisX: Double, axisY: Double, axisZ: Double, result: MutableVec3d): MutableVec3d = result.set(this).rotate(angleDeg, axisX, axisY, axisZ) fun rotate(angleDeg: Double, axis: Vec3d, result: MutableVec3d): MutableVec3d = result.set(this).rotate(angleDeg, axis.x, axis.y, axis.z) fun scale(factor: Double, result: MutableVec3d): MutableVec3d = result.set(this).scale(factor) fun sqrDistance(other: Vec3d): Double { val dx = x - other.x val dy = y - other.y val dz = z - other.z return dx*dx + dy*dy + dz*dz } fun sqrLength(): Double = x*x + y*y + z*z fun subtract(other: Vec3d, result: MutableVec3d): MutableVec3d = result.set(this).subtract(other) open operator fun get(i: Int) = fields[i] operator fun times(other: Vec3d): Double = dot(other) override fun toString(): String = "($x, $y, $z)" fun toVec3f(): Vec3f = Vec3f(x.toFloat(), y.toFloat(), z.toFloat()) fun toMutableVec3f(): MutableVec3f = toMutableVec3f(MutableVec3f()) fun toMutableVec3f(result: MutableVec3f): MutableVec3f = result.set(x.toFloat(), y.toFloat(), z.toFloat()) /** * Checks vector components for equality (using '==' operator). For better numeric stability consider using * [isFuzzyEqual]. */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Vec3d) return false if (x != other.x) return false if (y != other.y) return false if (z != other.z) return false return true } override fun hashCode(): Int { var result = x.hashCode() result = 31 * result + y.hashCode() result = 31 * result + z.hashCode() return result } companion object { val ZERO = Vec3d(0.0) val X_AXIS = Vec3d(1.0, 0.0, 0.0) val Y_AXIS = Vec3d(0.0, 1.0, 0.0) val Z_AXIS = Vec3d(0.0, 0.0, 1.0) val NEG_X_AXIS = Vec3d(-1.0, 0.0, 0.0) val NEG_Y_AXIS = Vec3d(0.0, -1.0, 0.0) val NEG_Z_AXIS = Vec3d(0.0, 0.0, -1.0) } } open class MutableVec3d(x: Double, y: Double, z: Double) : Vec3d(x, y, z) { override var x get() = this[0] set(value) { this[0] = value } override var y get() = this[1] set(value) { this[1] = value } override var z get() = this[2] set(value) { this[2] = value } constructor() : this(0.0, 0.0, 0.0) constructor(f: Double) : this(f, f, f) constructor(v: Vec3d) : this(v.x, v.y, v.z) fun add(other: Vec3d): MutableVec3d { x += other.x y += other.y z += other.z return this } fun mul(other: Vec3d): MutableVec3d { x *= other.x y *= other.y z *= other.z return this } fun norm(): MutableVec3d = scale(1.0f / length()) fun rotate(angleDeg: Double, axisX: Double, axisY: Double, axisZ: Double): MutableVec3d { val rad = angleDeg.toRad() val c = cos(rad) val c1 = 1f - c val s = sin(rad) val rx = x * (axisX * axisX * c1 + c) + y * (axisX * axisY * c1 - axisZ * s) + z * (axisX * axisZ * c1 + axisY * s) val ry = x * (axisY * axisX * c1 + axisZ * s) + y * (axisY * axisY * c1 + c) + z * (axisY * axisZ * c1 - axisX * s) val rz = x * (axisX * axisZ * c1 - axisY * s) + y * (axisY * axisZ * c1 + axisX * s) + z * (axisZ * axisZ * c1 + c) x = rx y = ry z = rz return this } fun rotate(angleDeg: Double, axis: Vec3d): MutableVec3d = rotate(angleDeg, axis.x, axis.y, axis.z) fun scale(factor: Double): MutableVec3d { x *= factor y *= factor z *= factor return this } fun set(x: Double, y: Double, z: Double): MutableVec3d { this.x = x this.y = y this.z = z return this } fun set(other: Vec3d): MutableVec3d { x = other.x y = other.y z = other.z return this } fun subtract(other: Vec3d): MutableVec3d { x -= other.x y -= other.y z -= other.z return this } operator fun divAssign(div: Double) { scale(1.0 / div) } operator fun minusAssign(other: Vec3d) { subtract(other) } operator fun plusAssign(other: Vec3d) { add(other) } open operator fun set(i: Int, v: Double) { fields[i] = v } operator fun timesAssign(factor: Double) { scale(factor) } } open class Vec3i(x: Int, y: Int, z: Int) { protected val fields = IntArray(3) open val x get() = this[0] open val y get() = this[1] open val z get() = this[2] constructor(f: Int) : this(f, f, f) constructor(v: Vec3i) : this(v.x, v.y, v.z) init { fields[0] = x fields[1] = y fields[2] = z } open operator fun get(i: Int): Int = fields[i] override fun toString(): String = "($x, $y, $z)" override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Vec3i) return false if (x != other.x) return false if (y != other.y) return false if (z != other.z) return false return true } override fun hashCode(): Int { var result = x.hashCode() result = 31 * result + y.hashCode() result = 31 * result + z.hashCode() return result } companion object { val ZERO = Vec3i(0) val X_AXIS = Vec3i(1, 0, 0) val Y_AXIS = Vec3i(0, 1, 0) val Z_AXIS = Vec3i(0, 0, 1) val NEG_X_AXIS = Vec3i(-1, 0, 0) val NEG_Y_AXIS = Vec3i(0, -1, 0) val NEG_Z_AXIS = Vec3i(0, 0, -1) } } open class MutableVec3i(x: Int, y: Int, z: Int) : Vec3i(x, y, z) { override var x get() = this[0] set(value) { this[0] = value } override var y get() = this[1] set(value) { this[1] = value } override var z get() = this[2] set(value) { this[2] = value } val array: IntArray get() = fields constructor() : this(0, 0, 0) constructor(f: Int) : this(f, f, f) constructor(other: Vec3i) : this(other.x, other.y, other.z) init { fields[0] = x fields[1] = y fields[2] = z } fun set(x: Int, y: Int, z: Int): MutableVec3i { this.x = x this.y = y this.z = z return this } fun set(other: Vec3i): MutableVec3i { x = other.x y = other.y z = other.z return this } open operator fun set(i: Int, v: Int) { fields[i] = v } fun add(other: Vec3i): MutableVec3i { x += other.x y += other.y z += other.z return this } fun subtract(other: Vec3i): MutableVec3i { x -= other.x y -= other.y z -= other.z return this } }
apache-2.0
a17411a3f683efbf11df399569146cd3
27.307427
123
0.530234
3.174317
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/gui/rcomponents/right/MaterialList.kt
1
7086
package com.cout970.modeler.gui.rcomponents.right import com.cout970.modeler.api.model.material.IMaterialRef import com.cout970.modeler.core.model.material.MaterialRefNone import com.cout970.modeler.core.model.objects import com.cout970.modeler.core.model.ref import com.cout970.modeler.core.project.IProgramState import com.cout970.modeler.gui.leguicomp.* import com.cout970.modeler.util.flatMapList import com.cout970.reactive.core.RBuilder import com.cout970.reactive.core.RProps import com.cout970.reactive.core.RStatelessComponent import com.cout970.reactive.dsl.* import com.cout970.reactive.nodes.comp import com.cout970.reactive.nodes.div import com.cout970.reactive.nodes.scrollablePanel import com.cout970.reactive.nodes.style import org.liquidengine.legui.component.optional.align.HorizontalAlign data class MaterialListProps(val programState: IProgramState, val selectedMaterial: () -> IMaterialRef) : RProps class MaterialList : RStatelessComponent<MaterialListProps>() { override fun RBuilder.render() = div("MaterialList") { style { height = 300f posY = 375f classes("left_panel_material_list") } postMount { marginX(5f) posY = parent.height / 2f height = parent.height / 2f } onCmd("updateModel") { rerender() } onCmd("updateSelection") { rerender() } onCmd("updateMaterial") { rerender() } comp(FixedLabel("Material List")) { style { classes("fixed_label", "material_list_label") } postMount { posX = 50f posY = 0f sizeX = parent.sizeX - 100f sizeY = 24f } } div("Buttons") { style { transparent() borderless() posY = 24f sizeY = 32f } postMount { marginX(5f) floatLeft(0f, 0f) } +IconButton("material.view.import", "add_material", 0f, 0f, 32f, 32f).also { it.setTooltip("Import material") } +IconButton("material.new.colored", "add_color_material", 0f, 0f, 32f, 32f).also { it.setTooltip("Create color material") } +IconButton("material.view.duplicate", "duplicate_material", 0f, 0f, 32f, 32f).also { it.setTooltip("Duplicate material") it.metadata += "ref" to props.selectedMaterial() } +IconButton("material.view.load", "load_material", 0f, 0f, 32f, 32f).also { it.setTooltip("Load different texture") it.metadata += "ref" to props.selectedMaterial() } +IconButton("material.view.remove", "remove_material", 0f, 0f, 32f, 32f).also { it.setTooltip("Delete material") it.metadata += "ref" to props.selectedMaterial() } +IconButton("material.view.inverse_select", "picker", 0f, 0f, 32f, 32f).also { it.setTooltip("Select objects with this material") it.metadata += "ref" to props.selectedMaterial() } } scrollablePanel("MaterialListScrollPanel") { style { transparent() borderless() } postMount { posX = 5f posY = 24f + 32f + 5f sizeX = parent.sizeX - 5f sizeY = parent.sizeY - posY - 5f } horizontalScroll { style { hide() } } verticalScroll { style { style.setMinWidth(16f) visibleAmount = 50f style.setTop(0f) style.setBottom(0f) classes("left_panel_material_list_scroll") } } viewport { style { style.setRight(18f) style.setBottom(0f) classes("left_panel_material_list_box") } } container { val model = props.programState.model val selection = props.programState.modelSelection val materialRefs = (model.materialRefs + listOf(MaterialRefNone)) val selectedMaterial = props.selectedMaterial() val materialOfSelectedObjects = selection .map { it to it.objects } .map { (sel, objs) -> objs.filter(sel::isSelected) } .map { it.map { model.getObject(it).material } } .flatMapList() style { transparent() borderless() sizeX = 256f sizeY = materialRefs.size * (24f + 2f) + 10f } materialRefs.forEachIndexed { index, ref -> val material = model.getMaterial(ref) div(material.name) { style { sizeY = 24f posY = 5f + index * (sizeY + 2f) classes("material_list_item") if (ref == selectedMaterial) { classes("material_list_item_selected") } } postMount { marginX(5f) } val icon = if (ref in materialOfSelectedObjects) "material_in_use" else "material" +IconButton("material.view.select", icon, 0f, 0f, 24f, 24f).apply { metadata += "ref" to material.ref } +TextButton("material.view.select", material.name, 24f, 0f, 196f - 24f, 24f).apply { horizontalAlign = HorizontalAlign.LEFT paddingLeft(2f) fontSize = 20f transparent() metadata += "ref" to material.ref } +IconButton("material.view.apply", "apply_material", 198f, 0f, 24f, 24f).apply { transparent() borderless() setTooltip("Apply material") metadata += "ref" to material.ref } +IconButton("material.view.config", "config_material", 222f, 0f, 24f, 24f).apply { transparent() borderless() setTooltip("Configure") metadata += "material" to material } } } } } } }
gpl-3.0
31729955956c3b6a76bcb04d7e153daa
33.91133
112
0.47742
4.927677
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/CastExpressionFix.kt
2
3519
// 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.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.asFlexibleType import org.jetbrains.kotlin.types.isDefinitelyNotNullType import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.types.typeUtil.makeNullable class CastExpressionFix(element: KtExpression, type: KotlinType) : KotlinQuickFixAction<KtExpression>(element) { private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type) private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type).let { if (type.isDefinitelyNotNullType) "($it)" else it } private val upOrDownCast: Boolean = run { val expressionType = element.analyze(BodyResolveMode.PARTIAL).getType(element) expressionType != null && (type.isSubtypeOf(expressionType) || expressionType.isSubtypeOf(type)) && expressionType != type.makeNullable() //covered by AddExclExclCallFix } override fun getFamilyName() = KotlinBundle.message("fix.cast.expression.family") override fun getText() = element?.let { KotlinBundle.message("fix.cast.expression.text", it.text, typePresentation) } ?: "" override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = upOrDownCast public override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val expressionToInsert = KtPsiFactory(file).createExpressionByPattern("$0 as $1", element, typeSourceCode) val newExpression = element.replaced(expressionToInsert) ShortenReferences.DEFAULT.process((KtPsiUtil.safeDeparenthesize(newExpression) as KtBinaryExpressionWithTypeRHS).right!!) editor?.caretModel?.moveToOffset(newExpression.endOffset) } abstract class Factory : KotlinSingleIntentionActionFactoryWithDelegate<KtExpression, KotlinType>() { override fun getElementOfInterest(diagnostic: Diagnostic) = diagnostic.psiElement as? KtExpression override fun createFix(originalElement: KtExpression, data: KotlinType) = CastExpressionFix(originalElement, data) } object SmartCastImpossibleFactory : Factory() { override fun extractFixData(element: KtExpression, diagnostic: Diagnostic) = Errors.SMARTCAST_IMPOSSIBLE.cast(diagnostic).a } object GenericVarianceConversion : Factory() { override fun extractFixData(element: KtExpression, diagnostic: Diagnostic): KotlinType { return ErrorsJvm.JAVA_TYPE_MISMATCH.cast(diagnostic).b.asFlexibleType().upperBound } } }
apache-2.0
8df7dec1d46796500f4e43c36ea35f86
53.984375
131
0.781188
4.794278
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/ui/navigation/playlists/PlaylistActivity.kt
1
3530
package com.kelsos.mbrc.ui.navigation.playlists import android.os.Bundle import android.view.View import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener import butterknife.BindView import butterknife.ButterKnife import com.google.android.material.snackbar.Snackbar import com.kelsos.mbrc.R import com.kelsos.mbrc.adapters.PlaylistAdapter import com.kelsos.mbrc.adapters.PlaylistAdapter.OnPlaylistPressedListener import com.kelsos.mbrc.data.Playlist import com.kelsos.mbrc.ui.activities.BaseActivity import com.kelsos.mbrc.ui.widgets.EmptyRecyclerView import com.kelsos.mbrc.ui.widgets.MultiSwipeRefreshLayout import com.raizlabs.android.dbflow.list.FlowCursorList import toothpick.Scope import toothpick.Toothpick import toothpick.smoothie.module.SmoothieActivityModule import java.net.ConnectException import javax.inject.Inject class PlaylistActivity : BaseActivity(), PlaylistView, OnPlaylistPressedListener, OnRefreshListener { private val PRESENTER_SCOPE: Class<*> = Presenter::class.java @BindView(R.id.swipe_layout) lateinit var swipeLayout: MultiSwipeRefreshLayout @BindView(R.id.playlist_list) lateinit var playlistList: EmptyRecyclerView @BindView(R.id.empty_view) lateinit var emptyView: View @BindView(R.id.list_empty_title) lateinit var emptyViewTitle: TextView @Inject lateinit var adapter: PlaylistAdapter @Inject lateinit var presenter: PlaylistPresenter private lateinit var scope: Scope public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_playlists) ButterKnife.bind(this) scope = Toothpick.openScopes(application, PRESENTER_SCOPE, this) scope.installTestModules(SmoothieActivityModule(this), PlaylistModule()) Toothpick.inject(this, scope) super.setup() swipeLayout.setSwipeableChildren(R.id.playlist_list, R.id.empty_view) adapter.setPlaylistPressedListener(this) playlistList.layoutManager = LinearLayoutManager(this) playlistList.emptyView = emptyView playlistList.adapter = adapter swipeLayout.setOnRefreshListener(this) emptyViewTitle.setText(R.string.playlists_list_empty) } public override fun onStart() { super.onStart() presenter.attach(this) presenter.load() } public override fun onStop() { super.onStop() presenter.detach() } override fun playlistPressed(path: String) { presenter.play(path) } override fun active(): Int { return R.id.nav_playlists } override fun onDestroy() { Toothpick.closeScope(this) if (isFinishing) { Toothpick.closeScope(PRESENTER_SCOPE) } super.onDestroy() } override fun onRefresh() { if (!swipeLayout.isRefreshing) { swipeLayout.isRefreshing = true } presenter.reload() } override fun update(cursor: FlowCursorList<Playlist>) { adapter.update(cursor) swipeLayout.isRefreshing = false } override fun failure(throwable: Throwable) { swipeLayout.isRefreshing = false if (throwable.cause is ConnectException) { Snackbar.make(swipeLayout, R.string.service_connection_error, Snackbar.LENGTH_SHORT).show() } else { Snackbar.make(swipeLayout, R.string.playlists_load_failed, Snackbar.LENGTH_SHORT).show() } } @javax.inject.Scope @Target(AnnotationTarget.TYPE) @Retention(AnnotationRetention.RUNTIME) annotation class Presenter }
gpl-3.0
3a307be45445886b8209bfea1ce205a7
27.934426
97
0.768555
4.294404
false
false
false
false
moko256/twicalico
app/src/main/java/com/github/moko256/twitlatte/UserLikeFragment.kt
1
1716
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.twitlatte import android.os.Bundle import com.github.moko256.latte.client.base.entity.Paging import com.github.moko256.twitlatte.entity.Client import com.github.moko256.twitlatte.viewmodel.ListViewModel /** * Created by moko256 on 2017/03/04. * * @author moko256 */ class UserLikeFragment : BaseTweetListFragment(), ToolbarTitleInterface { override val titleResourceId = R.string.like override val listRepository = object : ListViewModel.ListRepository() { var userId = 0L override fun onCreate(client: Client, bundle: Bundle) { super.onCreate(client, bundle) userId = bundle.getLong("userId") } override fun name() = "UserLike_$userId" override fun request(paging: Paging) = client.apiClient.getFavorites(userId, paging) } companion object { fun newInstance(userId: Long): UserLikeFragment { return UserLikeFragment().apply { arguments = Bundle().apply { putLong("userId", userId) } } } } }
apache-2.0
d6e44ff77c9e25431fe8e81c862d03b3
30.796296
92
0.681818
4.333333
false
false
false
false
googlecodelabs/android-performance
benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/home/Feed.kt
1
6110
/* * 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.macrobenchmark_codelab.ui.home import android.content.res.Configuration import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.add import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.windowInsetsTopHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.util.trace import com.example.macrobenchmark_codelab.model.Filter import com.example.macrobenchmark_codelab.model.SnackCollection import com.example.macrobenchmark_codelab.model.SnackRepo import com.example.macrobenchmark_codelab.ui.components.FilterBar import com.example.macrobenchmark_codelab.ui.components.JetsnackDivider import com.example.macrobenchmark_codelab.ui.components.JetsnackSurface import com.example.macrobenchmark_codelab.ui.components.SnackCollection import com.example.macrobenchmark_codelab.ui.theme.JetsnackTheme import kotlinx.coroutines.delay @Composable fun Feed( onSnackClick: (Long) -> Unit, modifier: Modifier = Modifier ) { // Simulate loading data asynchronously. // In real world application, you shouldn't have this kind of logic in your UI code, // but you should move it to appropriate layer. var snackCollections by remember { mutableStateOf(listOf<SnackCollection>()) } LaunchedEffect(Unit) { trace("Snacks loading") { delay(300) snackCollections = SnackRepo.getSnacks() } } val filters = remember { SnackRepo.getFilters() } Feed( snackCollections, filters, onSnackClick, modifier ) } @Composable private fun Feed( snackCollections: List<SnackCollection>, filters: List<Filter>, onSnackClick: (Long) -> Unit, modifier: Modifier = Modifier ) { JetsnackSurface(modifier = modifier.fillMaxSize()) { Box { SnackCollectionList(snackCollections, filters, onSnackClick) DestinationBar() } } } @Composable private fun SnackCollectionList( snackCollections: List<SnackCollection>, filters: List<Filter>, onSnackClick: (Long) -> Unit, modifier: Modifier = Modifier ) { var filtersVisible by rememberSaveable { mutableStateOf(false) } Box(modifier) { LazyColumn( modifier = Modifier.testTag("snack_list"), ) { item { Spacer( Modifier.windowInsetsTopHeight( WindowInsets.statusBars.add(WindowInsets(top = 56.dp)) ) ) FilterBar(filters, onShowFilters = { filtersVisible = true }) } if (snackCollections.isEmpty()) { item { Box( modifier = Modifier .fillParentMaxWidth() .fillParentMaxHeight(0.75f), contentAlignment = Alignment.Center ) { CircularProgressIndicator(color = JetsnackTheme.colors.brand) } } } else { itemsIndexed(snackCollections) { index, snackCollection -> if (index > 0) { JetsnackDivider(thickness = 2.dp) } SnackCollection( snackCollection = snackCollection, onSnackClick = onSnackClick, index = index, modifier = Modifier.testTag("snack_collection") ) } } } } AnimatedVisibility( visible = filtersVisible, enter = slideInVertically() + expandVertically( expandFrom = Alignment.Top ) + fadeIn(initialAlpha = 0.3f), exit = slideOutVertically() + shrinkVertically() + fadeOut() ) { FilterScreen( onDismiss = { filtersVisible = false } ) } } @Preview("default") @Preview("dark theme", uiMode = Configuration.UI_MODE_NIGHT_YES) @Preview("large font", fontScale = 2f) @Composable fun HomePreview() { JetsnackTheme { Feed( onSnackClick = { }, snackCollections = SnackRepo.getSnacks(), filters = SnackRepo.getFilters() ) } }
apache-2.0
458efc21896fcee9bda5a8464762fca4
34.317919
88
0.672013
4.915527
false
false
false
false