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
Fitbit/MvRx
sample/src/main/java/com/airbnb/mvrx/sample/features/dadjoke/RandomDadJokeFragment.kt
1
2929
package com.airbnb.mvrx.sample.features.dadjoke import android.os.Bundle import android.view.View import androidx.core.view.isVisible import androidx.navigation.fragment.findNavController import androidx.navigation.ui.setupWithNavController import com.airbnb.mvrx.Async import com.airbnb.mvrx.Loading import com.airbnb.mvrx.MavericksState import com.airbnb.mvrx.MavericksViewModelFactory import com.airbnb.mvrx.Success import com.airbnb.mvrx.Uninitialized import com.airbnb.mvrx.ViewModelContext import com.airbnb.mvrx.fragmentViewModel import com.airbnb.mvrx.mocking.mockSingleViewModel import com.airbnb.mvrx.sample.R import com.airbnb.mvrx.sample.core.BaseFragment import com.airbnb.mvrx.sample.core.MvRxViewModel import com.airbnb.mvrx.sample.databinding.RandomDadJokeFragmentBinding import com.airbnb.mvrx.sample.features.dadjoke.mocks.mockRandomDadJokeState import com.airbnb.mvrx.sample.models.Joke import com.airbnb.mvrx.sample.network.DadJokeService import com.airbnb.mvrx.sample.utils.viewBinding import com.airbnb.mvrx.withState import kotlinx.coroutines.Dispatchers import org.koin.android.ext.android.inject data class RandomDadJokeState(val joke: Async<Joke> = Uninitialized) : MavericksState class RandomDadJokeViewModel( initialState: RandomDadJokeState, private val dadJokeService: DadJokeService ) : MvRxViewModel<RandomDadJokeState>(initialState) { init { fetchRandomJoke() } fun fetchRandomJoke() { suspend { dadJokeService.random() }.execute(Dispatchers.IO) { copy(joke = it) } } companion object : MavericksViewModelFactory<RandomDadJokeViewModel, RandomDadJokeState> { override fun create( viewModelContext: ViewModelContext, state: RandomDadJokeState ): RandomDadJokeViewModel { val service: DadJokeService by viewModelContext.activity.inject() return RandomDadJokeViewModel(state, service) } } } class RandomDadJokeFragment : BaseFragment(R.layout.random_dad_joke_fragment) { private val binding: RandomDadJokeFragmentBinding by viewBinding() private val viewModel: RandomDadJokeViewModel by fragmentViewModel() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.toolbar.setupWithNavController(findNavController()) binding.randomizeButton.setOnClickListener { viewModel.fetchRandomJoke() } } override fun invalidate() = withState(viewModel) { state -> binding.loader.isVisible = state.joke is Loading binding.row.isVisible = state.joke is Success binding.row.setTitle(state.joke()?.joke) } override fun provideMocks() = mockSingleViewModel( viewModelReference = RandomDadJokeFragment::viewModel, defaultState = mockRandomDadJokeState, defaultArgs = null ) { stateForLoadingAndFailure { ::joke } } }
apache-2.0
33957b1d3cae6aa88a7eb9edfb162a39
35.160494
94
0.758279
4.202296
false
false
false
false
alashow/music-android
modules/core-ui-media/src/main/java/tm/alashow/datmusic/ui/audios/AudioActionHandler.kt
1
2561
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.ui.audios import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.AnnotatedString import com.google.firebase.analytics.FirebaseAnalytics import kotlinx.coroutines.launch import timber.log.Timber import tm.alashow.base.util.event import tm.alashow.base.util.extensions.simpleName import tm.alashow.base.util.toast import tm.alashow.common.compose.LocalAnalytics import tm.alashow.common.compose.LocalPlaybackConnection import tm.alashow.datmusic.downloader.Downloader import tm.alashow.datmusic.playback.PlaybackConnection import tm.alashow.datmusic.ui.downloader.LocalDownloader import tm.alashow.datmusic.ui.media.R val LocalAudioActionHandler = staticCompositionLocalOf<AudioActionHandler> { error("No LocalAudioActionHandler provided") } typealias AudioActionHandler = (AudioItemAction) -> Unit @Composable fun audioActionHandler( downloader: Downloader = LocalDownloader.current, playbackConnection: PlaybackConnection = LocalPlaybackConnection.current, clipboardManager: ClipboardManager = LocalClipboardManager.current, analytics: FirebaseAnalytics = LocalAnalytics.current, ): AudioActionHandler { val context = LocalContext.current val coroutine = rememberCoroutineScope() return { action -> analytics.event("audio.${action.simpleName}", mapOf("id" to action.audio.id)) when (action) { is AudioItemAction.Play -> playbackConnection.playAudio(action.audio) is AudioItemAction.PlayNext -> playbackConnection.playNextAudio(action.audio) is AudioItemAction.Download -> coroutine.launch { Timber.d("Coroutine launched to download audio: $action") downloader.enqueueAudio(action.audio) } is AudioItemAction.DownloadById -> coroutine.launch { Timber.d("Coroutine launched to download audio by Id: $action") downloader.enqueueAudio(action.audio.id) } is AudioItemAction.CopyLink -> { clipboardManager.setText(AnnotatedString(action.audio.downloadUrl ?: "")) context.toast(R.string.generic_clipboard_copied) } } } }
apache-2.0
0e2dbd7e6bc5f39cc71b730949a359b7
40.306452
89
0.750098
4.786916
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/wildplot/android/parsing/AtomTypes/MathFunctionAtom.kt
1
5199
/**************************************************************************************** * Copyright (c) 2014 Michael Goldbach <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ @file:Suppress("PackageName") // AtomTypes: copied from wildplot library package com.wildplot.android.parsing.AtomTypes import com.ichi2.utils.KotlinCleanup import com.wildplot.android.parsing.AtomTypes.MathFunctionAtom.MathType import com.wildplot.android.parsing.Expression import com.wildplot.android.parsing.ExpressionFormatException import com.wildplot.android.parsing.TopLevelParser import com.wildplot.android.parsing.TreeElement import kotlin.Throws @KotlinCleanup("IDE Lint") class MathFunctionAtom(funcString: String, private val parser: TopLevelParser) : TreeElement { enum class MathType { SIN, COS, TAN, SQRT, ACOS, ASIN, ATAN, SINH, COSH, LOG, LN, INVALID } var mathType = MathType.INVALID private set private var expression: Expression? = null private var hasSavedValue = false private var savedValue = 0.0 private fun init(funcString: String): Boolean { val leftBracket = funcString.indexOf("(") val rightBracket = funcString.lastIndexOf(")") if (leftBracket > 1 && rightBracket > leftBracket + 1) { val funcName = funcString.substring(0, leftBracket) val expressionString = funcString.substring(leftBracket + 1, rightBracket) val expressionInBrackets = Expression(expressionString, parser) val isValidExpression = expressionInBrackets.expressionType != Expression.ExpressionType.INVALID if (isValidExpression) { when (funcName) { "sin" -> mathType = MathType.SIN "cos" -> mathType = MathType.COS "tan" -> mathType = MathType.TAN "sqrt" -> mathType = MathType.SQRT "acos" -> mathType = MathType.ACOS "asin" -> mathType = MathType.ASIN "atan" -> mathType = MathType.ATAN "sinh" -> mathType = MathType.SINH "cosh" -> mathType = MathType.COSH "log", "lg" -> mathType = MathType.LOG "ln" -> mathType = MathType.LN else -> { mathType = MathType.INVALID return false } } expression = expressionInBrackets return true } } return false } @get:Throws(ExpressionFormatException::class) override val value: Double get() = if (hasSavedValue) { savedValue } else when (mathType) { MathType.SIN -> Math.sin(expression!!.value) MathType.COS -> Math.cos(expression!!.value) MathType.TAN -> Math.tan(expression!!.value) MathType.SQRT -> Math.sqrt(expression!!.value) MathType.ACOS -> Math.acos(expression!!.value) MathType.ASIN -> Math.asin(expression!!.value) MathType.ATAN -> Math.atan(expression!!.value) MathType.SINH -> Math.sinh(expression!!.value) MathType.COSH -> Math.cosh(expression!!.value) MathType.LOG -> Math.log10(expression!!.value) MathType.LN -> Math.log(expression!!.value) MathType.INVALID -> throw ExpressionFormatException("Number is Invalid, cannot parse") } @get:Throws(ExpressionFormatException::class) override val isVariable: Boolean get() = if (mathType != MathType.INVALID) { expression!!.isVariable } else { throw ExpressionFormatException("Number is Invalid, cannot parse") } init { val isValid = init(funcString) if (!isValid) { mathType = MathType.INVALID } if (isValid && !isVariable) { savedValue = value hasSavedValue = true } } }
gpl-3.0
4bba8fc50f6915d59ef845020de46a50
46.697248
98
0.539912
4.904717
false
false
false
false
sybila/CTL-Parser
src/main/java/com/github/sybila/huctl/dsl/package.kt
1
12236
package com.github.sybila.huctl.dsl import com.github.sybila.huctl.* /* ========== Expression ========== */ /** * Convert string to variable expression. */ fun String.toVar(): Expression.Variable = Expression.Variable(this) /** * Convert double to constant expression. */ fun Double.toConst(): Expression.Constant = Expression.Constant(this) /** * Create addition from two expressions. */ infix operator fun Expression.plus(other: Expression): Expression.Add = Expression.Add(this, other) /** * Create subtraction from two expressions. */ infix operator fun Expression.minus(other: Expression): Expression.Sub = Expression.Sub(this, other) /** * Create multiplication from two expressions. */ infix operator fun Expression.times(other: Expression): Expression.Mul = Expression.Mul(this, other) /** * Create division from two expressions. */ infix operator fun Expression.div(other: Expression): Expression.Div = Expression.Div(this, other) /** * Create [Formula.Numeric] proposition by comparing two expressions using the [CompareOp.GT]. */ infix fun Expression.gt(other: Expression): Formula.Numeric = Formula.Numeric(this, CompareOp.GT, other) /** * Create [Formula.Numeric] proposition by comparing two expressions using the [CompareOp.GE]. */ infix fun Expression.ge(other: Expression): Formula.Numeric = Formula.Numeric(this, CompareOp.GE, other) /** * Create [Formula.Numeric] proposition by comparing two expressions using the [CompareOp.EQ]. */ infix fun Expression.eq(other: Expression): Formula.Numeric = Formula.Numeric(this, CompareOp.EQ, other) /** * Create [Formula.Numeric] proposition by comparing two expressions using the [CompareOp.NEQ]. */ infix fun Expression.neq(other: Expression): Formula.Numeric = Formula.Numeric(this, CompareOp.NEQ, other) /** * Create [Formula.Numeric] proposition by comparing two expressions using the [CompareOp.LE]. */ infix fun Expression.le(other: Expression): Formula.Numeric = Formula.Numeric(this, CompareOp.LE, other) /** * Create [Formula.Numeric] proposition by comparing two expressions using the [CompareOp.LT]. */ infix fun Expression.lt(other: Expression): Formula.Numeric = Formula.Numeric(this, CompareOp.LT, other) /* ========== Direction Formula ========== */ /** * Convert variable name to increasing direction proposition. */ fun String.toIncreasing(): DirFormula.Proposition = DirFormula.Proposition(this, Direction.POSITIVE) /** * Convert variable name to decreasing direction proposition. */ fun String.toDecreasing(): DirFormula.Proposition = DirFormula.Proposition(this, Direction.NEGATIVE) /** * Create a negation of target direction formula. */ fun Not(inner: DirFormula): DirFormula.Not = DirFormula.Not(inner) /** * Create a conjunction of two direction formulas. */ infix fun DirFormula.and(right: DirFormula): DirFormula.And = DirFormula.And(this, right) /** * Create a disjunction of two direction formulas. */ infix fun DirFormula.or(right: DirFormula): DirFormula = DirFormula.Or(this, right) /** * Create an implication of two direction formulas. */ infix fun DirFormula.implies(right: DirFormula): DirFormula = DirFormula.Implies(this, right) /** * Create an equality of two direction formulas. */ infix fun DirFormula.equal(right: DirFormula): DirFormula = DirFormula.Equals(this, right) /* ========== HUCTLp formula ========== */ /** * Create a [Formula.Transition] proposition with positive direction and incoming flow. */ fun String.toPositiveIn(): Formula.Transition = Formula.Transition(this, Direction.POSITIVE, Flow.IN) /** * Create a [Formula.Transition] proposition with positive direction and incoming flow. */ fun String.toPositiveOut(): Formula.Transition = Formula.Transition(this, Direction.POSITIVE, Flow.OUT) /** * Create a [Formula.Transition] proposition with positive direction and incoming flow. */ fun String.toNegativeIn(): Formula.Transition = Formula.Transition(this, Direction.NEGATIVE, Flow.IN) /** * Create a [Formula.Transition] proposition with positive direction and incoming flow. */ fun String.toNegativeOut(): Formula.Transition = Formula.Transition(this, Direction.NEGATIVE, Flow.OUT) /** * Create a [Formula.Reference] from this string. */ fun String.toReference() = Formula.Reference(this) /** * Create a negation of [inner] formula. */ // Not an extension function to match other temporal unary ops fun Not(inner: Formula): Formula.Not = Formula.Not(inner) /** * Create a conjunction of two formulas. */ infix fun Formula.and(other: Formula): Formula.And = Formula.And(this, other) /** * Create a disjunction of two formulas. */ infix fun Formula.or(other: Formula): Formula.Or = Formula.Or(this, other) /** * Create an implication of two formulas. */ infix fun Formula.implies(other: Formula): Formula.Implies = Formula.Implies(this, other) /** * Create an equality of two formulas. */ infix fun Formula.equal(other: Formula): Formula.Equals = Formula.Equals(this, other) /** * Create an exists future formula over future paths with optional [dir] direction restriction. */ fun EF(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Future = Formula.Future(PathQuantifier.E, inner, dir) /** * Create an exists future formula over past paths with optional [dir] direction restriction. */ fun pEF(inner: Formula, dir: DirFormula = DirFormula.True): Formula = Formula.Future(PathQuantifier.pE, inner, dir) /** * Create an all future formula over future paths with optional [dir] direction restriction. */ fun AF(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Future = Formula.Future(PathQuantifier.A, inner, dir) /** * Create an all future formula over past paths with optional [dir] direction restriction. */ fun pAF(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Future = Formula.Future(PathQuantifier.pA, inner, dir) /** * Create an exists weak future formula over future paths with optional [dir] direction restriction. */ fun EwF(inner: Formula, dir: DirFormula = DirFormula.True): Formula.WeakFuture = Formula.WeakFuture(PathQuantifier.E, inner, dir) /** * Create an all weak future formula over future paths with optional [dir] direction restriction. */ fun AwF(inner: Formula, dir: DirFormula = DirFormula.True): Formula.WeakFuture = Formula.WeakFuture(PathQuantifier.A, inner, dir) /** * Create an exists weak future formula over past paths with optional [dir] direction restriction. */ fun pEwF(inner: Formula, dir: DirFormula = DirFormula.True): Formula.WeakFuture = Formula.WeakFuture(PathQuantifier.pE, inner, dir) /** * Create an all weak future formula over past paths with optional [dir] direction restriction. */ fun pAwF(inner: Formula, dir: DirFormula = DirFormula.True): Formula.WeakFuture = Formula.WeakFuture(PathQuantifier.pA, inner, dir) /** * Create an exists next formula over future paths with optional [dir] direction restriction. */ fun EX(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Next = Formula.Next(PathQuantifier.E, inner, dir) /** * Create an exists next formula over past paths with optional [dir] direction restriction. */ fun pEX(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Next = Formula.Next(PathQuantifier.pE, inner, dir) /** * Create an all next formula over future paths with optional [dir] direction restriction. */ fun AX(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Next = Formula.Next(PathQuantifier.A, inner, dir) /** * Create an all next formula over past paths with optional [dir] direction restriction. */ fun pAX(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Next = Formula.Next(PathQuantifier.pA, inner, dir) /** * Create an exists weak next formula over future paths with optional [dir] direction restriction. */ fun EwX(inner: Formula, dir: DirFormula = DirFormula.True): Formula.WeakNext = Formula.WeakNext(PathQuantifier.E, inner, dir) /** * Create an exists weak next formula over past paths with optional [dir] direction restriction. */ fun pEwX(inner: Formula, dir: DirFormula = DirFormula.True): Formula.WeakNext = Formula.WeakNext(PathQuantifier.pE, inner, dir) /** * Create an all weak next formula over future paths with optional [dir] direction restriction. */ fun AwX(inner: Formula, dir: DirFormula = DirFormula.True): Formula.WeakNext = Formula.WeakNext(PathQuantifier.A, inner, dir) /** * Create an all weak next formula over past paths with optional [dir] direction restriction. */ fun pAwX(inner: Formula, dir: DirFormula = DirFormula.True): Formula.WeakNext = Formula.WeakNext(PathQuantifier.pA, inner, dir) /** * Create an exists globally formula over future paths with optional [dir] direction restriction. */ fun EG(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Globally = Formula.Globally(PathQuantifier.E, inner, dir) /** * Create an exists weak next formula over past paths with optional [dir] direction restriction. */ fun pEG(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Globally = Formula.Globally(PathQuantifier.pE, inner, dir) /** * Create an all weak next formula over future paths with optional [dir] direction restriction. */ fun AG(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Globally = Formula.Globally(PathQuantifier.A, inner, dir) /** * Create an all weak next formula over past paths with optional [dir] direction restriction. */ fun pAG(inner: Formula, dir: DirFormula = DirFormula.True): Formula.Globally = Formula.Globally(PathQuantifier.pA, inner, dir) /** * Create an exists until formula over future paths without direction restriction. */ infix fun Formula.EU(reach: Formula): Formula.Until = Formula.Until(PathQuantifier.E, this, reach, DirFormula.True) /** * Create an all until formula over future paths without direction restriction. */ infix fun Formula.AU(reach: Formula): Formula.Until = Formula.Until(PathQuantifier.A, this, reach, DirFormula.True) /** * Create an exists until formula over past paths without direction restriction. */ infix fun Formula.pEU(reach: Formula): Formula.Until = Formula.Until(PathQuantifier.pE, this, reach, DirFormula.True) /** * Create an all until formula over past paths without direction restriction. */ infix fun Formula.pAU(reach: Formula): Formula.Until = Formula.Until(PathQuantifier.pA, this, reach, DirFormula.True) /** * Create an exists until formula over future paths with optional direction restriction. */ fun Formula.EU(reach: Formula, dir: DirFormula = DirFormula.True): Formula.Until = Formula.Until(PathQuantifier.E, this, reach, dir) /** * Create an all until formula over future paths with optional direction restriction. */ fun Formula.AU(reach: Formula, dir: DirFormula = DirFormula.True): Formula.Until = Formula.Until(PathQuantifier.A, this, reach, dir) /** * Create an exists until formula over past paths with optional direction restriction. */ fun Formula.pEU(reach: Formula, dir: DirFormula = DirFormula.True): Formula.Until = Formula.Until(PathQuantifier.pE, this, reach, dir) /** * Create an all until formula over past paths with optional direction restriction. */ fun Formula.pAU(reach: Formula, dir: DirFormula = DirFormula.True): Formula.Until = Formula.Until(PathQuantifier.pA, this, reach, dir) /** * Create a hybrid At formula valid at the given [name]. */ fun At(name: String, inner: Formula) : Formula.At = Formula.At(name, inner) /** * Create a hybrid Bind formula, binding the given [name]. */ fun Bind(name: String, inner: Formula) : Formula.Bind = Formula.Bind(name, inner) /** * Create a first order ForAll formula, binding the given [name]. */ fun ForAll(name: String, bound: Formula = Formula.True, inner: Formula) : Formula.ForAll = Formula.ForAll(name, bound, inner) /** * Create a first order Exists formula, binding the given [name]. */ fun Exists(name: String, bound: Formula = Formula.True, inner: Formula) : Formula.Exists = Formula.Exists(name, bound, inner)
gpl-3.0
9a50323f39311d32304245d3493af27c
34.469565
106
0.729732
3.822555
false
false
false
false
FrogCraft-Rebirth/LaboratoriumChemiae
src/main/kotlin/info/tritusk/laboratoriumchemiae/library/Processable.kt
1
2090
package info.tritusk.laboratoriumchemiae.library import info.tritusk.laboratoriumchemiae.api.agent.Agent import info.tritusk.laboratoriumchemiae.api.devices.AgentInput import info.tritusk.laboratoriumchemiae.api.devices.AgentOutput import info.tritusk.laboratoriumchemiae.api.devices.ResearchDataInput import info.tritusk.laboratoriumchemiae.api.reaction.ReactionType import info.tritusk.laboratoriumchemiae.api.research.Research import info.tritusk.laboratoriumchemiae.api.research.ResearchManager import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.launch import net.minecraft.tileentity.TileEntity import net.minecraft.util.ITickable abstract class Processable : TileEntity(), ITickable { protected val inputs : MutableSet<AgentInput<*>> = mutableSetOf() protected val outputs : MutableSet<AgentOutput<*>> = mutableSetOf() protected var data : ResearchDataInput<*>? = null protected var status = WorkStatus.IDLE private var tickCounter = 0 protected var isReadyToStartReaction = false override fun update() = if (tickCounter++ == 20 && !world.isRemote) updateServer() else updateClient() private fun updateServer() { val currData = data //Thread-safe, if I read it right. if (currData != null && currData.currentResearch() != ResearchManager.EMPTY_RESEARCH) { //TODO ONLY DO REACTION WHEN WE HAVE RECIPE DATA if (isReadyToStartReaction) { val reactionProcess = launch(CommonPool) { reactionStart( data?.currentResearch() ?: ResearchManager.EMPTY_RESEARCH, inputs.map { it.containedAgent }.toTypedArray() ) }.invokeOnCompletion { status = WorkStatus.IDLE } } } } private fun updateClient() { // TODO do some client -> server synchronization stuff } suspend fun reactionStart(data : Research, inputs : Array<Agent>) { status = WorkStatus.WORKING } }
mit
61b10216f3e90dd471083c857419f87a
38.433962
106
0.690431
4.291581
false
false
false
false
morayl/Footprint
footprint-ktx/src/main/java/com/morayl/footprintktx/Footprint.kt
1
12906
package com.morayl.footprintktx import android.util.Log import com.google.gson.Gson import org.json.JSONArray import org.json.JSONException import org.json.JSONObject /** * Leave footprint. * Footprint-ktx is a library for debugging Android-Kotlin. * * You just use [footprint], logcat shows "[ClassName#MethodName:LineNumber]". * You can log multiple params, object as json, pair values, stacktrace. * → [jsonFootprint], [withJsonFootprint], [pairFootprint], [stacktraceFootprint]. * You can configure enable, log level, etc. Use [configFootprint]. * * [footprint] use [StackTraceElement] to log "[ClassName#MethodName:LineNumber]", * it is a bit heavy and may slow down the UI thread * if you call a lot at short intervals like a long "for" statement. * You can use [simpleFootprint], which is faster than [footprint] * because it doesn't use [StackTraceElement]. (It doesn't log "[ClassName#MethodName:LineNumber]".) * * (In Java, You "can" use to write FootprintKt.~ but it's not useful.) */ private var enableInternal = true private var defaultLogTag = "Footprint" private var defaultLogPriority = LogPriority.DEBUG private var showJsonExceptionInternal = false private var forceSimpleInternal = false private var defaultStackTraceLogLevel = LogPriority.ERROR private var defaultJsonIndentCount = 4 /** * Configure default of Footprint. * Params not specify, the current settings will be inherited. * This settings available in memory. * * @param enable If it false, all Footprint log are not shown. (Default true) * @param logTag Set default LogTag. (Default "Footprint") * @param logPriority Set default [LogPriority] (like Verbose/Debug/Error). (Default [LogPriority.DEBUG]) * @param showInternalJsonException If it true, Footprint show "internal [JSONException]" * when exception occurred while you use [withJsonFootprint]. (Default false) * @param forceSimple If it true, all Footprint log are not use [getMetaInfo] and are not showed [Class#Method:Linenumber]. * It is used for improve performance. (Default false) * @param stacktraceLogLogPriority Set default LogPriority when Footprint printing stacktrace. (Default [LogPriority.ERROR]) * @param jsonIndentCount Set default count of Json Indention space. * * @see [LogPriority] */ fun configFootprint( enable: Boolean = enableInternal, logTag: String = defaultLogTag, logPriority: LogPriority = defaultLogPriority, showInternalJsonException: Boolean = showJsonExceptionInternal, forceSimple: Boolean = forceSimpleInternal, stacktraceLogLogPriority: LogPriority = defaultStackTraceLogLevel, jsonIndentCount: Int = defaultJsonIndentCount ) { enableInternal = enable defaultLogTag = logTag defaultLogPriority = logPriority showJsonExceptionInternal = showInternalJsonException forceSimpleInternal = forceSimple defaultStackTraceLogLevel = stacktraceLogLogPriority defaultJsonIndentCount = jsonIndentCount } /** * Log [ClassName#MethodName:LineNumber]. * * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. * * @see [LogPriority] */ fun footprint(priority: LogPriority = defaultLogPriority, logTag: String = defaultLogTag) { if (enableInternal) { simpleFootprint(getMetaInfo(), priority = priority, logTag = logTag) } } /** * Log [ClassName#MethodName:LineNumber] and messages. * * @param messages Messages you want to log. * This param is vararg, you can put multiple messages with using comma. * Messages are concat at space. * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. * * @see [LogPriority] */ fun footprint(vararg messages: Any?, priority: LogPriority = defaultLogPriority, logTag: String = defaultLogTag) { if (enableInternal) { simpleFootprint(getMetaInfo(), messages.joinToString(separator = " "), priority = priority, logTag = logTag) } } /** * Log [ClassName#MethodName:LineNumber] and messages. * Log priority of this log is force [LogPriority.ERROR]. * The log could become red, so you can find log easier in many debug logs. * * @param messages (Optional) Messages you want to log. * This param is vararg, you can put multiple messages with using comma. * Messages are concat at space. * @param logTag (Optional) Logcat-log's tag of this log. */ fun accentFootprint(vararg messages: Any? = emptyArray(), logTag: String = defaultLogTag) { footprint(*messages, priority = LogPriority.ERROR, logTag = logTag) } /** * Just log messages without stacktrace information. * It is faster than [footprint]. * Recommended when using many times at short intervals. * * @param message Messages you want to log. * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. */ fun simpleFootprint(message: Any?, priority: LogPriority = defaultLogPriority, logTag: String = defaultLogTag) { if (enableInternal) { Log.println(priority.value, logTag, message.toString()) } } /** * Just log messages without stacktrace information. * It is faster than [footprint]. * Recommended when outputting many times at short intervals. * * @param messages (Optional) Messages you want to log. * This param is vararg, you can put multiple messages with using comma. * Messages are concat at space. * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. */ fun simpleFootprint(vararg messages: Any?, priority: LogPriority = defaultLogPriority, logTag: String = defaultLogTag) { if (enableInternal) { simpleFootprint(messages.joinToString(separator = " "), priority = priority, logTag = logTag) } } /** * Log [ClassName#MethodName:LineNumber] and target as Json. * * @param target "Any object" you want to log as Json. * If target Json conversion failed, it show toString(). * Want to know failure reason, use [#configFootprint(showJsonExceptionInternal = true)] * @param indent (Optional) Count of Json Indention space. * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. */ fun jsonFootprint(target: Any?, indent: Int = defaultJsonIndentCount, priority: LogPriority = defaultLogPriority, logTag: String = defaultLogTag) { target.withJsonFootprint(indent, priority, logTag) } /** * Log [ClassName#MethodName:LineNumber] and receiver as Json. And return receiver. * Want to log primitive value, use [withFootprint]. * If receiver Json conversion failed, it show toString(). * Want to know failure reason, use [configFootprint] and "showJsonExceptionInternal = true". * * @receiver Object you want to log as json. * @param indent (Optional) Count of Json Indention space. * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. * @param block (Optional) Variable which you want to log. Default is "this". * @return Receiver (this). */ fun <T> T.withJsonFootprint(indent: Int = defaultJsonIndentCount, priority: LogPriority = defaultLogPriority, logTag: String = defaultLogTag, block: (T) -> Any? = { this }): T { if (enableInternal) { footprint("\n", block(this).toFormattedJSON(indent), priority = priority, logTag = logTag) } return this } /** * Log [ClassName#MethodName:LineNumber] and receiver as toString(). And return receiver. * Want to log object json, use [withJsonFootprint]. * * @receiver Object you want to log as toString(). * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. * @param block (Optional) Variable which you want to log as toString(). Default is "this". * @return Receiver (this). */ fun <T> T.withFootprint(priority: LogPriority = defaultLogPriority, logTag: String = defaultLogTag, block: (T) -> Any? = { this }): T { if (enableInternal) { footprint(block(this), priority = priority, logTag = logTag) } return this } /** * Just log receiver as toString() without stacktrace information. And return receiver. * It is faster than [withFootprint]. * Recommended when outputting many times at short intervals. * * @receiver Object you want to log as toString(). * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. * @param block (Optional) Variable which you want to log as toString(). Default is "this". * @return Receiver (this). */ fun <T> T.withSimpleFootprint(priority: LogPriority = defaultLogPriority, logTag: String = defaultLogTag, block: (T) -> Any? = { this }): T { if (enableInternal) { simpleFootprint(block(this), priority = priority, logTag = logTag) } return this } /** * Log [ClassName#MethodName:LineNumber] and pair values. * Usage: pairFootprint("first" to 1, "second" to "secondValue", "third" to 3.toString()) * Output: [ClassName#MethodName:LineNumber] * first : 1 * second : secondValue * third : 3 * * @param pairs Value pairs you want to log. * This param is vararg, you can put multiple messages with using comma. * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. */ fun pairFootprint(vararg pairs: Pair<String, Any?>, priority: LogPriority = defaultLogPriority, logTag: String = defaultLogTag) { val message = pairs.joinToString(separator = "\n", prefix = "\n") { "${it.first} : ${it.second}" } footprint(message, priority = priority, logTag = logTag) } /** * Log [ClassName#MethodName:LineNumber] and stacktrace of exception. * * @receiver [Throwable] you want to log as stacktrace string. * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. */ fun Throwable.stacktraceFootprint(priority: LogPriority = defaultStackTraceLogLevel, logTag: String = defaultLogTag) { if (enableInternal) { footprint(Log.getStackTraceString(this), priority = priority, logTag = logTag) } } /** * Log [ClassName#MethodName:LineNumber] and current stacktrace. * Useful for confirming calling hierarchy. * * @param priority (Optional) Log priority of this log. Select from [LogPriority]. * @param logTag (Optional) Logcat-log's tag of this log. */ fun stacktraceFootprint(priority: LogPriority = defaultStackTraceLogLevel, logTag: String = defaultLogTag) { if (enableInternal) { footprint(Log.getStackTraceString(Throwable()), priority = priority, logTag = logTag) } } /** * Convert receiver to formatted Json. * * @param indent Count of Json Indention space. * @return formatted json. * If Json conversion failed, return toString(). */ private fun Any?.toFormattedJSON(indent: Int): String? { return runCatching { val json = Gson().toJson(this) try { val jsonObject = JSONObject(json) jsonObject.toString(indent) } catch (e: JSONException) { val jsonArray = JSONArray(json) jsonArray.toString(indent) } }.onFailure { if (showJsonExceptionInternal) { it.stacktraceFootprint() } }.getOrElse { toString() } } /** * Get stacktrace information string from current [StackTraceElement]. * * @return [className#methodName:line] */ private fun getMetaInfo(): String? { if (forceSimpleInternal) { return "" } // Get stackTraceElement array. // 0: VM, 1: Thread, 2: This method, 3: Caller of this method... val elements = Thread.currentThread().stackTrace for (i in 2 until elements.size) { if (elements[i].fileName?.startsWith("Footprint") == false) { return getMetaInfo(elements[i]) } } return "No meta info" } /** * Get stacktrace information string from [StackTraceElement]. * * @param element a [StackTraceElement] * @return [className#methodName:line] */ private fun getMetaInfo(element: StackTraceElement): String? { val fullClassName = element.className val simpleClassName = fullClassName?.substring(fullClassName.lastIndexOf(".") + 1) val methodName = element.methodName val lineNumber = element.lineNumber return "[$simpleClassName#$methodName:$lineNumber]" }
apache-2.0
571350f78f0f00257fe2052c38971de8
39.199377
147
0.702185
4.215616
false
false
false
false
debop/debop4k
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/DayRange.kt
1
1768
/* * Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.timeperiod.timeranges import debop4k.core.kodatimes.asDate import debop4k.core.kodatimes.today import debop4k.timeperiod.DefaultTimeCalendar import debop4k.timeperiod.ITimeCalendar import debop4k.timeperiod.models.DayOfWeek import org.joda.time.DateTime /** * Created by debop */ open class DayRange @JvmOverloads constructor(startTime: DateTime = today(), calendar: ITimeCalendar = DefaultTimeCalendar) : DayTimeRange(startTime, 1, calendar) { @JvmOverloads constructor(year: Int, monthOfYear: Int = 1, dayOfMonth: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar) : this(asDate(year, monthOfYear, dayOfMonth), calendar) val year: Int get() = startYear val monthOfYear: Int get() = startMonthOfYear val dayOfMonth: Int get() = startDayOfMonth val dayOfWeek: DayOfWeek get() = startDayOfWeek fun addDays(days: Int): DayRange { return DayRange(start.plusDays(days), calendar) } fun nextDay(): DayRange = addDays(1) fun prevDay(): DayRange = addDays(-1) }
apache-2.0
dd4182cc7377211fdf301159ed075e23
34.38
92
0.697964
4.312195
false
false
false
false
ykrank/S1-Next
library/src/main/java/com/github/ykrank/androidtools/widget/hostcheck/MultiHostInterceptor.kt
1
2124
package com.github.ykrank.androidtools.widget.hostcheck import okhttp3.HttpUrl import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response import java.io.IOException import java.net.ProtocolException import java.util.concurrent.TimeUnit /** * Self-adaption multi host * Created by ykrank on 2017/3/29. */ open class MultiHostInterceptor<T : BaseHostUrl>(private val baseHostUrl: T, private val mergeHttpUrl: (originHttpUrl: HttpUrl, baseHostUrl: T) -> HttpUrl) : Interceptor { @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val originRequest = chain.request() val originHttpUrl = originRequest.url val newHttpUrl = mergeHttpUrl.invoke(originHttpUrl, baseHostUrl) var newRequest = originRequest if (originHttpUrl !== newHttpUrl) { val builder = originRequest.newBuilder() builder.url(newHttpUrl) builder.header("host", newHttpUrl.host) newRequest = builder.build() } val response: Response = proceedRequest(chain, newRequest) { if (newRequest != originRequest) { return proceedRequest(chain.withReadTimeout(chain.readTimeoutMillis(), TimeUnit.MILLISECONDS), originRequest) { throw it } } else { throw it } } return response } private inline fun proceedRequest(chain: Interceptor.Chain, request: Request, except: (IOException) -> Response): Response { return try { chain.proceed(request) } catch (e: Exception) { if (e is IOException) { except.invoke(e) } else { except.invoke(OkHttpException(request.url.host, e)) } } } } /** * Must not extends IOException but ProtocolException because okhttp3 catch RouteException and IOException to retry. * But only some exception * * @see [okhttp3.internal.http.RetryAndFollowUpInterceptor.recover] */ class OkHttpException(val host: String?, override val cause: Throwable?) : ProtocolException(host)
apache-2.0
51a22c68939f0dac07dcf979c5508054
32.730159
171
0.664783
4.587473
false
false
false
false
ntlv/BasicLauncher2
app/src/main/java/se/ntlv/basiclauncher/database/GlobalConfig.kt
1
1038
package se.ntlv.basiclauncher.database import android.content.SharedPreferences import se.ntlv.basiclauncher.GridDimensions class GlobalConfig(private val prefs: SharedPreferences) { private val GRID_DIMENS_ROW_COUNT = "GRID_DIMENS_ROW_COUNT" private val GRID_DIMENS_COL_COUNT = "GRID_DIMENS_COL_COUNT" private val ONE_TIME_INIT = "ONE_TIME_INIT" var pageDimens: GridDimensions set(newDimens: GridDimensions) { val editor = prefs.edit() editor.putInt(GRID_DIMENS_ROW_COUNT, newDimens.rowCount) editor.putInt(GRID_DIMENS_COL_COUNT, newDimens.columnCount) editor.apply() } get() { val rows = prefs.getInt(GRID_DIMENS_ROW_COUNT, 5) val cols = prefs.getInt(GRID_DIMENS_COL_COUNT, 4) return GridDimensions(rows, cols) } var shouldDoOneTimeInit : Boolean set(shouldDo: Boolean) = prefs.edit().putBoolean(ONE_TIME_INIT, shouldDo).apply() get() = prefs.getBoolean(ONE_TIME_INIT, true) }
mit
c7b0a86986d98cb175f8c5bb044bbbf6
32.516129
89
0.66474
3.830258
false
false
false
false
GDG-Nantes/devfest-android
app/src/main/kotlin/com/gdgnantes/devfest/android/SyncService.kt
1
5890
package com.gdgnantes.devfest.android import android.app.IntentService import android.content.ContentProviderOperation import android.content.ContentValues import android.content.Context import android.content.Intent import android.util.Log import com.gdgnantes.devfest.android.app.PreferencesManager import com.gdgnantes.devfest.android.http.JsonConverters import com.gdgnantes.devfest.android.model.Schedule import com.gdgnantes.devfest.android.model.toContentValues import com.gdgnantes.devfest.android.provider.ScheduleContract import com.google.firebase.crash.FirebaseCrash import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Header import java.io.IOException import java.lang.RuntimeException import java.util.concurrent.TimeUnit class SyncService : IntentService(TAG) { // NOTE Cyril // The current implementation of the sync mechanism is fairly simple … // not to say stupid^^. // The sync consists on heavily relying on the server response code: // - a 304 response indicates the local schedule is already up-to-date // and, as a consequence, nothing needs to be done locally. In that // case, the sync stops immediately; // - a 200 response code indicates the local schedule is outdated. The // code consists on removing everything that was persisted locally // and insert the newly retrieved content from the server. // - other response codes are treated as errors // // Obviously, this algorithm could be improved greatly by doing diffs // which would avoid unnecessary insert/delete operations. The main // advantage of the current implementation is it keeps the code as // simple as possible. companion object { private const val TAG = "SyncService" private val AMOUNT = TimeUnit.MINUTES.toMillis(10) private var lastSync = -1L fun sync(context: Context) { if (lastSync > 0 && (System.currentTimeMillis() - lastSync) <= AMOUNT) { // No need to sync now as it's been done recently // Let's skip the request return } context.startService(Intent(context, SyncService::class.java)) } } private interface ScheduleApi { interface Headers { companion object { const val ETAG = "etag" const val IF_NONE_MATCH = "If-None-Match" } } interface ResponseCodes { companion object { const val OK = 200 const val NO_CONTENT = 304 } } @GET("schedule") fun getSchedule(@Header(Headers.IF_NONE_MATCH) etag: String): Call<Schedule> } override fun onHandleIntent(intent: Intent) { val api: ScheduleApi = Retrofit.Builder() .baseUrl(AppConfig.ENDPOINT) .addConverterFactory(GsonConverterFactory.create(JsonConverters.main)) .build() .create(ScheduleApi::class.java) try { val prefs = PreferencesManager.from(this) val etag = prefs.scheduleETag ?: AppConfig.SEED_ETAG val response = api.getSchedule(etag).execute() val code = response.code() when (code) { ScheduleApi.ResponseCodes.OK -> { contentResolver.applyBatch(ScheduleContract.AUTHORITY, buildOperations(response.body()!!)) lastSync = System.currentTimeMillis() prefs.scheduleETag = response.headers()[ScheduleApi.Headers.ETAG] } ScheduleApi.ResponseCodes.NO_CONTENT -> return else -> { FirebaseCrash.log("Unknown response code $code received while syncing") } } } catch (ioe: IOException) { Log.e(TAG, "A network error occurred while syncing schedule", ioe) } catch (re: RuntimeException) { Log.e(TAG, "An error occurred while syncing schedule", re) FirebaseCrash.report(re) } } private fun buildOperations(schedule: Schedule) = ArrayList<ContentProviderOperation>().apply { add(ContentProviderOperation.newDelete(ScheduleContract.Rooms.CONTENT_URI).build()) add(ContentProviderOperation.newDelete(ScheduleContract.Sessions.CONTENT_URI).build()) add(ContentProviderOperation.newDelete(ScheduleContract.SessionsSpeakers.CONTENT_URI).build()) add(ContentProviderOperation.newDelete(ScheduleContract.Speakers.CONTENT_URI).build()) schedule.rooms.forEach { add(ContentProviderOperation.newInsert(ScheduleContract.Rooms.CONTENT_URI) .withValues(it.toContentValues()) .build()) } schedule.speakers.forEach { add(ContentProviderOperation.newInsert(ScheduleContract.Speakers.CONTENT_URI) .withValues(it.toContentValues()) .build()) } schedule.sessions.forEach { session -> add(ContentProviderOperation.newInsert(ScheduleContract.Sessions.CONTENT_URI) .withValues(session.toContentValues()) .build()) session.speakersIds?.forEach { speakerId -> val values = ContentValues().apply { put(ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SESSION_ID, session.id) put(ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SPEAKER_ID, speakerId) } add(ContentProviderOperation.newInsert(ScheduleContract.SessionsSpeakers.CONTENT_URI) .withValues(values) .build()) } } } }
apache-2.0
b9808a717b9c0da2a9a89f11ee32331b
39.335616
110
0.639266
5.133391
false
false
false
false
bendaniel10/weather-lite-kotlin
app/src/main/java/com/bendaniel10/weatherlite/di/WeatherLiteModule.kt
1
3195
package com.bendaniel10.weatherlite.di import com.bendaniel10.weatherlite.app.WeatherLiteApplication import com.bendaniel10.weatherlite.service.WeatherLiteService import com.bendaniel10.weatherlite.service.impl.WeatherLiteServiceImpl import com.bendaniel10.weatherlite.viewmodel.WeatherLiteViewModel import com.bendaniel10.weatherlite.webservice.RestAPI import dagger.Module import dagger.Provides import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Converter import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Named /** * Created by bendaniel on 22/06/2017. */ @Module class WeatherLiteModule { @Provides fun provideApplicationContext(): WeatherLiteApplication { return WeatherLiteApplication.instance } @Provides fun provideConverterFactory(): Converter.Factory { return GsonConverterFactory.create() } @Provides @Named("baseUrl") fun provideBaseUrl(): String { return WeatherLiteApplication.OPEN_WEATHER_API_URL } @Provides @Named("weatherApiKey") fun provideWeatherApiKey(): String { return WeatherLiteApplication.OPEN_WEATHER_API_KEY } @Provides fun provideOkHttpClient(@Named("connectionTimeOutSecs") connectionTimeOutSecs: Long, @Named("readTimeOutSecs") readTimeOutSecs: Long, @Named("interceptor") interceptor: Interceptor?): OkHttpClient { val okHttpClient = OkHttpClient().newBuilder() .connectTimeout(connectionTimeOutSecs, TimeUnit.SECONDS) .readTimeout(readTimeOutSecs, TimeUnit.SECONDS) .build() if (interceptor != null) { val interceptorBuilder = okHttpClient.newBuilder() interceptorBuilder.addInterceptor(interceptor) return interceptorBuilder.build() } return okHttpClient } @Provides @Named("interceptor") fun providesInterceptor(): Interceptor { val logInterceptor = HttpLoggingInterceptor() logInterceptor.level = HttpLoggingInterceptor.Level.BODY return logInterceptor } @Provides @Named("readTimeOutSecs") fun provideReadTimeOutSecs() = 15L @Provides @Named("connectionTimeOutSecs") fun provideConnectionTimeOutSecs() = 15L @Provides fun provideRestAPI(converterFactory: Converter.Factory, @Named("baseUrl") baseUrl: String, okHttpClient: OkHttpClient, @Named("weatherApiKey") weatherApiKey: String): RestAPI { return RestAPI(converterFactory = converterFactory, baseUrl = baseUrl, okHttpClient = okHttpClient, weatherApiKey = weatherApiKey) } @Provides fun provideWeatherLiteService(restAPI: RestAPI): WeatherLiteService { return WeatherLiteServiceImpl(restAPI = restAPI) } @Provides fun provideWeatherLiteViewModel(weatherLiteService: WeatherLiteService): WeatherLiteViewModel { return WeatherLiteViewModel(weatherLiteService = weatherLiteService) } }
apache-2.0
2e4f47d23176c894328b0d0bb4f64a23
28.869159
138
0.707668
5.023585
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/GivenAPlayingFile/ThatIsThenPaused/AndThePlayerIdles/WhenThePlayerWillNotPlayWhenReady.kt
1
2121
package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.GivenAPlayingFile.ThatIsThenPaused.AndThePlayerIdles import com.google.android.exoplayer2.Player import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.ExoPlayerPlaybackHandler import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.BeforeClass import org.junit.Test import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException class WhenThePlayerWillNotPlayWhenReady { companion object { private val eventListeners: MutableCollection<Player.Listener> = ArrayList() private val mockExoPlayer = mockk<PromisingExoPlayer>() @JvmStatic @BeforeClass fun before() { every { mockExoPlayer.setPlayWhenReady(any()) } returns mockExoPlayer.toPromise() every { mockExoPlayer.getPlayWhenReady() } returns true.toPromise() every { mockExoPlayer.getCurrentPosition() } returns 50L.toPromise() every { mockExoPlayer.getDuration() } returns 100L.toPromise() every { mockExoPlayer.addListener(any()) } answers { eventListeners.add(firstArg()) mockExoPlayer.toPromise() } val exoPlayerPlaybackHandler = ExoPlayerPlaybackHandler(mockExoPlayer) val playbackPromise = exoPlayerPlaybackHandler.promisePlayback() playbackPromise .eventually { p -> val playableFilePromise = p.promisePause() every { mockExoPlayer.getPlayWhenReady() } returns false.toPromise() eventListeners.forEach { e -> e.onPlaybackStateChanged(Player.STATE_IDLE) } playableFilePromise } val playedPromise = playbackPromise .eventually { obj -> obj.promisePlayedFile() } try { FuturePromise(playedPromise)[1, TimeUnit.SECONDS] } catch (ignored: TimeoutException) { } } } @Test fun thenPlaybackIsNotRestarted() { verify(exactly = 1) { mockExoPlayer.setPlayWhenReady(true) } } }
lgpl-3.0
b48d59689feb776cd377d40aa8974cae
36.875
122
0.78595
4.175197
false
false
false
false
alphafoobar/intellij-community
platform/configuration-store-impl/src/XmlElementStorage.kt
2
10832
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.TrackingPathMacroSubstitutor import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.components.impl.stores.StateStorageBase import com.intellij.openapi.util.JDOMUtil import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.SmartHashSet import gnu.trove.THashMap import org.jdom.Attribute import org.jdom.Element import java.io.IOException abstract class XmlElementStorage protected constructor(protected val fileSpec: String, protected val rootElementName: String, protected val pathMacroSubstitutor: TrackingPathMacroSubstitutor?, roamingType: RoamingType? = RoamingType.DEFAULT, provider: StreamProvider? = null) : StateStorageBase<StateMap>() { protected val roamingType: RoamingType = roamingType ?: RoamingType.DEFAULT private val provider: StreamProvider? = if (provider == null || roamingType == RoamingType.DISABLED || !provider.isApplicable(fileSpec, this.roamingType)) null else provider protected abstract fun loadLocalData(): Element? override fun getStateAndArchive(storageData: StateMap, component: Any, componentName: String) = storageData.getStateAndArchive(componentName) override fun hasState(storageData: StateMap, componentName: String) = storageData.hasState(componentName) override fun loadData(): StateMap { val element: Element? // we don't use local data if has stream provider if (provider != null && provider.enabled) { try { element = loadDataFromProvider() dataLoadedFromProvider(element) } catch (e: Exception) { LOG.error(e) element = null } } else { element = loadLocalData() } return if (element == null) StateMap.EMPTY else loadState(element) } protected open fun dataLoadedFromProvider(element: Element?) { } private fun loadDataFromProvider() = JDOMUtil.load(provider!!.read(fileSpec, roamingType)) private fun loadState(element: Element): StateMap { beforeElementLoaded(element) return StateMap.fromMap(FileStorageCoreUtil.load(element, pathMacroSubstitutor, true)) } fun setDefaultState(element: Element) { element.setName(rootElementName) storageDataRef.set(loadState(element)) } override fun startExternalization() = if (checkIsSavingDisabled()) null else createSaveSession(getStorageData()) protected abstract fun createSaveSession(states: StateMap): StateStorage.ExternalizationSession override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<String>) { val oldData = storageDataRef.get() val newData = getStorageData(true) if (oldData == null) { if (LOG.isDebugEnabled()) { LOG.debug("analyzeExternalChangesAndUpdateIfNeed: old data null, load new for ${toString()}") } componentNames.addAll(newData.keys()) } else { val changedComponentNames = oldData.getChangedComponentNames(newData) if (LOG.isDebugEnabled()) { LOG.debug("analyzeExternalChangesAndUpdateIfNeed: changedComponentNames $changedComponentNames for ${toString()}") } if (!ContainerUtil.isEmpty(changedComponentNames)) { componentNames.addAll(changedComponentNames) } } } private fun setStates(oldStorageData: StateMap, newStorageData: StateMap?) { if (oldStorageData !== newStorageData && storageDataRef.getAndSet(newStorageData) !== oldStorageData) { LOG.warn("Old storage data is not equal to current, new storage data was set anyway") } } abstract class XmlElementStorageSaveSession<T : XmlElementStorage>(private val originalStates: StateMap, protected val storage: T) : SaveSessionBase() { private var copiedStates: MutableMap<String, Any>? = null private val newLiveStates = THashMap<String, Element>() override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStates == null) null else this override fun setSerializedState(component: Any, componentName: String, element: Element?) { if (copiedStates == null) { copiedStates = setStateAndCloneIfNeed(componentName, element, originalStates, newLiveStates) } else { updateState(copiedStates!!, componentName, element, newLiveStates) } } override fun save() { val stateMap = StateMap.fromMap(copiedStates!!) var element = save(stateMap, newLiveStates, storage.rootElementName) if (element == null || JDOMUtil.isEmpty(element)) { element = null } else { storage.beforeElementSaved(element) } val provider = storage.provider if (provider != null && provider.enabled) { if (element == null) { provider.delete(storage.fileSpec, storage.roamingType) } else { // we should use standard line-separator (\n) - stream provider can share file content on any OS provider.write(storage.fileSpec, element.toBufferExposingByteArray(), storage.roamingType) } } else { saveLocally(element) } storage.setStates(originalStates, stateMap) } throws(IOException::class) protected abstract fun saveLocally(element: Element?) } protected open fun beforeElementLoaded(element: Element) { } protected open fun beforeElementSaved(element: Element) { if (pathMacroSubstitutor != null) { try { pathMacroSubstitutor.collapsePaths(element) } finally { pathMacroSubstitutor.reset() } } } public fun updatedFromStreamProvider(changedComponentNames: MutableSet<String>, deleted: Boolean) { if (roamingType == RoamingType.DISABLED) { // storage roaming was changed to DISABLED, but settings repository has old state return } try { val newElement = if (deleted) null else loadDataFromProvider() val states = storageDataRef.get() if (newElement == null) { // if data was loaded, mark as changed all loaded components if (states != null) { changedComponentNames.addAll(states.keys()) setStates(states, null) } } else if (states != null) { val newStates = loadState(newElement) changedComponentNames.addAll(states.getChangedComponentNames(newStates)) setStates(states, newStates) } } catch (e: Throwable) { LOG.error(e) } } } private fun save(states: StateMap, newLiveStates: Map<String, Element>, rootElementName: String): Element? { if (states.isEmpty()) { return null } val rootElement = Element(rootElementName) for (componentName in states.keys()) { val element = states.getElement(componentName, newLiveStates) // name attribute should be first val elementAttributes = element.getAttributes() if (elementAttributes.isEmpty()) { element.setAttribute(FileStorageCoreUtil.NAME, componentName) } else { var nameAttribute: Attribute? = element.getAttribute(FileStorageCoreUtil.NAME) if (nameAttribute == null) { nameAttribute = Attribute(FileStorageCoreUtil.NAME, componentName) elementAttributes.add(0, nameAttribute) } else { nameAttribute.setValue(componentName) if (elementAttributes.get(0) != nameAttribute) { elementAttributes.remove(nameAttribute) elementAttributes.add(0, nameAttribute) } } } rootElement.addContent(element) } return rootElement } fun setStateAndCloneIfNeed(componentName: String, newState: Element?, oldStates: StateMap, newLiveStates: MutableMap<String, Element>): MutableMap<String, Any>? { val oldState = oldStates.get(componentName) if (newState == null || JDOMUtil.isEmpty(newState)) { if (oldState == null) { return null } val newStates = oldStates.toMutableMap() newStates.remove(componentName) return newStates } prepareElement(newState) newLiveStates.put(componentName, newState) var newBytes: ByteArray? = null if (oldState is Element) { if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) { return null } } else if (oldState != null) { newBytes = StateMap.getNewByteIfDiffers(componentName, newState, oldState as ByteArray) if (newBytes == null) { return null } } val newStates = oldStates.toMutableMap() newStates.put(componentName, newBytes ?: newState) return newStates } fun prepareElement(state: Element) { if (state.getParent() != null) { LOG.warn("State element must not have parent ${JDOMUtil.writeElement(state)}") state.detach() } state.setName(FileStorageCoreUtil.COMPONENT) } private fun updateState(states: MutableMap<String, Any>, componentName: String, newState: Element?, newLiveStates: MutableMap<String, Element>) { if (newState == null || JDOMUtil.isEmpty(newState)) { states.remove(componentName) return } prepareElement(newState) newLiveStates.put(componentName, newState) val oldState = states.get(componentName) var newBytes: ByteArray? = null if (oldState is Element) { if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) { return } } else if (oldState != null) { newBytes = StateMap.getNewByteIfDiffers(componentName, newState, oldState as ByteArray) ?: return } states.put(componentName, newBytes ?: newState) } // newStorageData - myStates contains only live (unarchived) states private fun StateMap.getChangedComponentNames(newStates: StateMap): Set<String> { val bothStates = keys().toMutableSet() bothStates.retainAll(newStates.keys()) val diffs = SmartHashSet<String>() diffs.addAll(newStates.keys()) diffs.addAll(keys()) diffs.removeAll(bothStates) for (componentName in bothStates) { compare(componentName, newStates, diffs) } return diffs }
apache-2.0
c819f32991c9228143c269797471b609
33.832797
175
0.697655
4.888087
false
false
false
false
schaal/ocreader
app/src/main/java/email/schaal/ocreader/SettingsActivity.kt
1
4385
/* * Copyright © 2017. Daniel Schaal <[email protected]> * * This file is part of OCReader. * * OCReader 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. * * OCReader 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ package email.schaal.ocreader import android.content.Intent import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.databinding.DataBindingUtil import androidx.preference.PreferenceManager import email.schaal.ocreader.Preferences.ChangeAction import email.schaal.ocreader.databinding.ActivitySettingsBinding import email.schaal.ocreader.util.FaviconLoader class SettingsActivity : AppCompatActivity(), OnSharedPreferenceChangeListener { private var recreateActivity: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) recreateActivity = intent.getBooleanExtra(EXTRA_RECREATE_ACTIVITY, false) val binding = DataBindingUtil.setContentView<ActivitySettingsBinding>(this, R.layout.activity_settings) setSupportActionBar(binding.toolbarLayout.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setTitle(R.string.settings) PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this) supportFragmentManager.beginTransaction() .add(R.id.fragment_settings, SettingsFragment()) .commit() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(EXTRA_RECREATE_ACTIVITY, recreateActivity) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) recreateActivity = savedInstanceState.getBoolean(EXTRA_RECREATE_ACTIVITY) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { Preferences.getPreference(key)?.let { preference -> when (preference.changeAction) { ChangeAction.NOTHING -> { } ChangeAction.RECREATE -> { recreateActivity = true FaviconLoader.clearCache() AppCompatDelegate.setDefaultNightMode(Preferences.getNightMode(sharedPreferences)) val intent = intent intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK intent.putExtra(EXTRA_RECREATE_ACTIVITY, recreateActivity) startActivity(intent) finish() overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) } ChangeAction.UPDATE -> PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(Preferences.SYS_NEEDS_UPDATE_AFTER_SYNC.key, true).apply() } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { checkRecreateActivity() } return super.onOptionsItemSelected(item) } private fun checkRecreateActivity() { setResult(REQUEST_CODE, Intent().apply { putExtra(EXTRA_RECREATE_ACTIVITY, recreateActivity) }) } override fun onBackPressed() { // Recreate the parent activity if necessary to apply theme change, go back normally otherwise checkRecreateActivity() super.onBackPressed() } companion object { const val EXTRA_RECREATE_ACTIVITY = "recreateActivity" const val REQUEST_CODE = 267 } }
gpl-3.0
d494b883dc5f4c08421a47057d2413f0
41.163462
167
0.708485
5.301088
false
false
false
false
TeamAmaze/AmazeFileManager
app/src/main/java/com/amaze/filemanager/ui/views/drawer/GestureExclusionView.kt
3
2174
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.ui.views.drawer import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.os.Build import android.util.AttributeSet import android.view.View class GestureExclusionView( context: Context, attrs: AttributeSet? = null ) : View(context, attrs) { private val gestureExclusionRects = mutableListOf<Rect>() override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) if (changed) { updateGestureExclusion() } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) updateGestureExclusion() } private fun updateGestureExclusion() { // Skip this call if we're not running on Android 10+ if (Build.VERSION.SDK_INT < 29) { visibility = GONE return } visibility = VISIBLE setBackgroundColor(resources.getColor(android.R.color.transparent)) gestureExclusionRects.clear() val rect = Rect() this.getGlobalVisibleRect(rect) gestureExclusionRects += rect systemGestureExclusionRects = gestureExclusionRects } }
gpl-3.0
8c6341797b58465e2448076e93666a80
33.507937
107
0.702392
4.330677
false
false
false
false
tasks/tasks
app/src/debug/java/org/tasks/preferences/fragments/Debug.kt
1
3391
package org.tasks.preferences.fragments import android.os.Bundle import androidx.annotation.StringRes import androidx.lifecycle.lifecycleScope import androidx.preference.Preference import at.bitfire.cert4android.CustomCertManager.Companion.resetCertificates import com.todoroo.andlib.utility.DateUtilities.now import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.tasks.R import org.tasks.billing.BillingClient import org.tasks.billing.Inventory import org.tasks.extensions.Context.toast import org.tasks.injection.InjectingPreferenceFragment import org.tasks.preferences.Preferences import java.util.concurrent.TimeUnit import javax.inject.Inject import kotlin.math.min @AndroidEntryPoint class Debug : InjectingPreferenceFragment() { @Inject lateinit var inventory: Inventory @Inject lateinit var billingClient: BillingClient @Inject lateinit var preferences: Preferences override fun getPreferenceXml() = R.xml.preferences_debug override suspend fun setupPreferences(savedInstanceState: Bundle?) { for (pref in listOf( R.string.p_leakcanary, R.string.p_flipper, R.string.p_strict_mode_vm, R.string.p_strict_mode_thread, R.string.p_crash_main_queries )) { findPreference(pref) .setOnPreferenceChangeListener { _: Preference?, _: Any? -> showRestartDialog() true } } findPreference(R.string.debug_reset_ssl).setOnPreferenceClickListener { resetCertificates(requireContext()) context?.toast("SSL certificates reset") false } findPreference(R.string.debug_force_restart).setOnPreferenceClickListener { restart() false } setupIap(R.string.debug_themes, Inventory.SKU_THEMES) setupIap(R.string.debug_tasker, Inventory.SKU_TASKER) findPreference(R.string.debug_crash_app).setOnPreferenceClickListener { throw RuntimeException("Crashed app from debug preferences") } findPreference(R.string.debug_clear_hints).setOnPreferenceClickListener { preferences.installDate = min(preferences.installDate, now() - TimeUnit.DAYS.toMillis(14)) preferences.lastSubscribeRequest = 0L preferences.lastReviewRequest = 0L preferences.shownBeastModeHint = false true } } private fun setupIap(@StringRes prefId: Int, sku: String) { val preference: Preference = findPreference(prefId) if (inventory.getPurchase(sku) == null) { preference.title = getString(R.string.debug_purchase, sku) preference.onPreferenceClickListener = Preference.OnPreferenceClickListener { lifecycleScope.launch { billingClient.initiatePurchaseFlow(requireActivity().parent, "inapp" /*SkuType.INAPP*/, sku) } false } } else { preference.title = getString(R.string.debug_consume, sku) preference.onPreferenceClickListener = Preference.OnPreferenceClickListener { lifecycleScope.launch { billingClient.consume(sku) } false } } } }
gpl-3.0
67b2c68bdc15728c31804858ebf1df95
35.473118
112
0.660277
5.091592
false
false
false
false
cbeust/kobalt
src/test/kotlin/com/beust/kobalt/internal/ExcludeTest.kt
2
3344
package com.beust.kobalt.internal import com.beust.kobalt.BaseTest import com.beust.kobalt.api.Kobalt import com.beust.kobalt.app.BuildFileCompiler import com.beust.kobalt.maven.DependencyManager import com.beust.kobalt.maven.aether.Scope import com.google.inject.Inject import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.DataProvider import org.testng.annotations.Test class ExcludeTest @Inject constructor(compilerFactory: BuildFileCompiler.IFactory, val dependencyManager: DependencyManager) : BaseTest(compilerFactory) { val EXCLUDED_DEPENDENCY = "org.codehaus.plexus:plexus-utils:jar:3.0.22" @DataProvider fun dp() = arrayOf<Array<String?>>( arrayOf(null), arrayOf(EXCLUDED_DEPENDENCY) ) @Test(dataProvider = "dp", description = "Text exclusions that apply to the whole project") fun globalExcludeShouldWork(excludedDependency: String?) { val projectText = """ dependencies { compile("org.apache.maven:maven-model:jar:3.3.9") """ + (if (excludedDependency != null) """exclude("$excludedDependency")""" else "") + """ } """ val project = compileSingleProject(projectText) val allIds = dependencyManager.calculateDependencies(project, Kobalt.context!!, scopes = listOf(Scope.COMPILE)) .map { it.id } if (excludedDependency != null) { assertThat(allIds).doesNotContain(excludedDependency) } else { assertThat(allIds).contains(EXCLUDED_DEPENDENCY) } } @DataProvider fun dp2() = arrayOf<Array<Any?>>( arrayOf(null, 8, ""), arrayOf("{ exclude(\".*org.apache.*\") }", 4, "org.apache"), arrayOf("{ exclude(groupId = \"org.apache.*\") }", 4, "org.apache"), arrayOf("{ exclude(artifactId = \".*core.*\") }", 7, "core"), arrayOf("{ exclude(artifactId = \"httpcore\", version = \"4.3.3\") }", 7, "httpcore"), arrayOf("{ exclude(version = \"4.3.3\") }", 7, "httpcore"), arrayOf("{ exclude(artifactId = \"commons.codec\") }", 7, "commons-codec") ) @Test(dataProvider = "dp2", description = "Text exclusions tied to a specific dependency") fun localExcludeShouldWork(excludedDependency: String?, expectedCount: Int, excludedString: String) { val projectText = """ dependencies { compile("org.eclipse.jgit:org.eclipse.jgit:4.5.0.201609210915-r") """ + (if (excludedDependency != null) """$excludedDependency""" else "") + """ } """ val project = compileSingleProject(projectText) val allIds = dependencyManager.calculateDependencies(project, Kobalt.context!!, scopes = listOf(Scope.COMPILE)) .map { it.id } assertThat(allIds.size).isEqualTo(expectedCount) if (excludedDependency != null) { if (allIds.any { it.contains(excludedString) }) { throw AssertionError("id's should not contain any string \"$excludedString\": $allIds") } } else { assertThat(allIds.filter { it.contains("org.apache") }.size).isEqualTo(2) } } }
apache-2.0
9e338b28c315fcfacbbf685b9247503f
38.809524
105
0.604366
4.3827
false
true
false
false
olonho/carkot
translator/src/test/kotlin/tests/array_extensions_1/array_extensions_1.kt
1
1458
fun array_extensions_1_copyOf(): Int { val array = IntArray(3) array[0] = 1 array[1] = 20 array[2] = 333 val minimize = array.copyOf(2) return minimize[1] + minimize.size } fun array_extensions_1_copyOf_extend(): Int { val array = IntArray(3) array[0] = 1 array[1] = 20 array[2] = 333 val minimize = array.copyOf(7) return minimize[2] + minimize[3] + minimize[4] + minimize[5] + minimize[6] + minimize.size } fun array_extensions_1_copyOfRange(): Int { val array = IntArray(7) array[0] = 1 array[1] = 20 array[2] = 333 array[3] = 444 array[4] = 555 array[5] = 666 array[6] = 777 val minimize = array.copyOfRange(2, 4) val ans = minimize[0] + minimize[1] + minimize.size return ans } fun array_extensions_1_plus_element(): Int { val array = IntArray(7) array[0] = 1 array[1] = 20 array[2] = 333 array[3] = 444 array[4] = 555 array[5] = 666 array[6] = 777 val minimize = array.plus(2148) return minimize[6] + minimize[7] + minimize.size } fun array_extensions_1_plus_array(): Int { val array = IntArray(3) array[0] = 1 array[1] = 20 array[2] = 333 val secondArray = IntArray(4) secondArray[0] = 9999 secondArray[1] = 2789 secondArray[2] = 11792 secondArray[3] = 67820 val maximize = array.plus(secondArray) val ans = maximize[2] + maximize[5] + maximize.size return ans }
mit
4a0da5189e9e60c4fca2dd445f0fc158
22.142857
94
0.597394
3.075949
false
false
false
false
olonho/carkot
translator/src/test/kotlin/tests/class_reassignment_2/class_reassignment_2.kt
1
467
class class_reassignment_2_Node { var left: class_reassignment_2_Node? = null var right: class_reassignment_2_Node? = null var value: Int = 0 } fun class_reassignment_2(): Int { val root: class_reassignment_2_Node = class_reassignment_2_Node() root.value = 12 root.left = class_reassignment_2_Node() var current: class_reassignment_2_Node? = root current = root.left current!!.value = 10593 return current.value + root.value }
mit
23af3019e62f3fca1f70d5159b096fa7
30.2
69
0.678801
3.288732
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/Container.kt
1
10351
package com.soywiz.korge.view import com.soywiz.kds.* import com.soywiz.kds.iterators.* import com.soywiz.kmem.* import com.soywiz.korge.internal.* import com.soywiz.korge.render.* import com.soywiz.korma.geom.* /** Creates a new [Container], allowing to configure with [callback], and attaches the newly created container to the receiver this [Container] */ inline fun Container.container(callback: @ViewDslMarker Container.() -> Unit = {}) = Container().addTo(this, callback) // For Flash compatibility //open class Sprite : Container() /** * A simple container of [View]s. * * All the [children] in this container have an associated index that determines their rendering order. * The first child is rendered first, and the last one is rendered last. So when children are overlapping with each other, * the last child will overlap the previous ones. * * You can access the children by [numChildren], [getChildAt] or [size] and [get]. * * You can add new children to this container by calling [addChild] or [addChildAt]. */ @UseExperimental(KorgeInternal::class) open class Container : View(true) { @PublishedApi internal val __children: FastArrayList<View> = FastArrayList() override val _children: FastArrayList<View>? get() = __children inline fun fastForEachChild(block: (child: View) -> Unit) { __children.fastForEach { child ->block(child) } } @KorgeInternal @PublishedApi internal val childrenInternal: FastArrayList<View> get() { return __children!! } /** * Retrieves all the child [View]s. * Shouldn't be used if possible. You can use [numChildren] and [getChildAt] to get the children. * You can also use [forEachChild], [forEachChildWithIndex] and [forEachChildReversed] to iterate children */ @KorgeInternal val children: FastArrayList<View> get() = __children override fun invalidate() { super.invalidate() fastForEachChild { child -> if (child._requireInvalidate) { child.invalidate() } } } override fun invalidateColorTransform() { super.invalidateColorTransform() fastForEachChild { child -> if (child._requireInvalidateColor) { child.invalidateColorTransform() } } } /** Returns the first child of this container or null when the container doesn't have children */ val firstChild: View? get() = __children.firstOrNull() /** Returns the last child of this container or null when the container doesn't have children */ val lastChild: View? get() = __children.lastOrNull() /** Sorts all the children by using the specified [comparator]. */ fun sortChildrenBy(comparator: Comparator<View>) { __children.sortWith(comparator) forEachChildWithIndex { index: Int, child: View -> child.index = index } } /** Returns the number of children this container has */ @Suppress("FoldInitializerAndIfToElvis") val numChildren: Int get() { val children = _children if (children == null) return 0 return children.size } /** Returns the number of children this container has */ val size: Int get() = numChildren /** * Recursively retrieves the top ancestor in the container hierarchy. * * Retrieves the top ancestor of the hierarchy. In case the container is orphan this very instance is returned. */ val containerRoot: Container get() = parent?.containerRoot ?: this /** * Recursively retrieves the ancestor in the container hierarchy that is a [View.Reference] like the stage or null when can't be found. */ val referenceParent: Container? get() { if (parent is Reference) return parent return parent?.referenceParent } /** * Swaps the order of two child [View]s [view1] and [view2]. * If [view1] or [view2] are not part of this container, this method doesn't do anything. */ @KorgeUntested fun swapChildren(view1: View, view2: View) { if (view1.parent == view2.parent && view1.parent == this) { val index1 = view1.index val index2 = view2.index __children[index1] = view2 view2.index = index1 __children[index2] = view1 view1.index = index2 } } fun moveChildTo(view: View, index: Int) { if (view.parent != this) return val targetIndex = index.clamp(0, numChildren - 1) while (view.index < targetIndex) swapChildren(view, __children[view.index + 1]) while (view.index > targetIndex) swapChildren(view, __children[view.index - 1]) } fun sendChildToFront(view: View) { if (view.parent === this) { while (view != lastChild!!) { swapChildren(view, children[view.index + 1]) } } } fun sendChildToBack(view: View) { if (view.parent === this) { while (view != firstChild!!) { swapChildren(view, children[view.index - 1]) } } } /** * Adds the [view] [View] as a child at a specific [index]. * * Remarks: if [index] is outside bounds 0..[numChildren], it will be clamped to the nearest valid value. */ @KorgeUntested fun addChildAt(view: View, index: Int) { view.removeFromParent() val aindex = index.clamp(0, this.numChildren) view.index = aindex val children = childrenInternal children.add(aindex, view) for (n in aindex + 1 until children.size) children[n].index = n // Update other indices view.parent = this view.invalidate() onChildAdded(view) } protected open fun onChildAdded(view: View) { } /** * Retrieves the index of a given child [View]. */ @KorgeUntested fun getChildIndex(view: View): Int = view.index /** * Finds the [View] at a given index. * Remarks: if [index] is outside bounds 0..[numChildren] - 1, an [IndexOutOfBoundsException] will be thrown. */ fun getChildAt(index: Int): View = childrenInternal[index] /** * Finds the [View] at a given index. If the index is not valid, it returns null. */ fun getChildAtOrNull(index: Int): View? = __children.getOrNull(index) /** * Finds the first child [View] matching a given [name]. */ @KorgeUntested fun getChildByName(name: String): View? = __children.firstOrNull { it.name == name } /** * Removes the specified [view] from this container. * * Remarks: If the parent of [view] is not this container, this function doesn't do anything. */ fun removeChild(view: View?) { if (view?.parent == this) { view?.removeFromParent() } } /** * Removes all [View]s children from this container. */ fun removeChildren() { fastForEachChild { child -> child.parent = null child.index = -1 } __children.clear() } inline fun removeChildrenIf(cond: (index: Int, child: View) -> Boolean) { var removedCount = 0 forEachChildWithIndex { index, child -> if (cond(index, child)) { child._parent = null child._index = -1 removedCount++ } else { child._index -= removedCount } } for (n in 0 until removedCount) __children.removeAt(__children.size - 1) } /** * Adds a child [View] to the container. * * If the [View] already belongs to a parent, it is removed from it and then added to the container. */ fun addChild(view: View) = addChildAt(view, numChildren) fun addChildren(views: List<View?>?) = views?.toList()?.fastForEach { it?.let { addChild(it) } } /** * Alias for [addChild]. */ operator fun plusAssign(view: View) { addChildAt(view, numChildren) } /** Alias for [getChildAt] */ operator fun get(index: Int): View = getChildAt(index) /** * Alias for [removeChild]. */ operator fun minusAssign(view: View) = removeChild(view) private val tempMatrix = Matrix() override fun renderInternal(ctx: RenderContext) { if (!visible) return renderChildrenInternal(ctx) } open fun renderChildrenInternal(ctx: RenderContext) { fastForEachChild { child: View -> child.render(ctx) } } override fun renderDebug(ctx: RenderContext) { fastForEachChild { child: View -> child.renderDebug(ctx) } super.renderDebug(ctx) } private val bb = BoundsBuilder() private val tempRect = Rectangle() override fun getLocalBoundsInternal(out: Rectangle) { bb.reset() fastForEachChild { child: View -> child.getBounds(this, tempRect) bb.add(tempRect) } bb.getBounds(out) } /** * Creates a new container. * @return an empty container. */ override fun createInstance(): View = Container() /** * Performs a deep copy of the container, by copying all the child [View]s. */ override fun clone(): View { val out = super.clone() fastForEachChild { out += it.clone() } return out } override fun findViewByName(name: String): View? { val result = super.findViewByName(name) if (result != null) return result fastForEachChild { child: View -> val named = child.findViewByName(name) if (named != null) return named } return null } } /** * Alias for `parent += this`. Refer to [Container.plusAssign]. */ fun <T : View> T.addTo(parent: Container): T { parent += this return this } /** Adds the specified [view] to this view only if this view is a [Container]. */ operator fun View?.plusAssign(view: View?) { val container = this as? Container? if (view != null) container?.addChild(view) } inline fun <T : View> T.addTo(instance: Container, callback: @ViewDslMarker T.() -> Unit = {}) = this.addTo(instance).apply(callback) inline fun <T : View> Container.append(view: T): T { addChild(view) return view } inline fun <T : View> Container.append(view: T, block: T.() -> Unit): T = append(view).also(block) fun View.bringToTop() { val parent = this.parent ?: return parent.moveChildTo(this, parent.numChildren - 1) } fun View.bringToBottom() { val parent = this.parent ?: return parent.moveChildTo(this, 0) }
apache-2.0
43c5e9306555f56389a49a7751866b46
29.444118
146
0.632596
4.004255
false
false
false
false
HedvigInsurance/bot-service
src/main/java/com/hedvig/botService/chat/OnboardingConversationDevi.kt
1
86930
package com.hedvig.botService.chat import com.google.common.collect.Lists import com.google.i18n.phonenumbers.PhoneNumberUtil import com.hedvig.botService.chat.MainConversation.Companion.MESSAGE_HEDVIG_COM_POST_LOGIN import com.hedvig.botService.chat.house.HouseConversationConstants import com.hedvig.botService.chat.house.HouseOnboardingConversation import com.hedvig.botService.config.SwitchableInsurers import com.hedvig.botService.dataTypes.EmailAdress import com.hedvig.botService.dataTypes.HouseholdMemberNumber import com.hedvig.botService.dataTypes.LivingSpaceSquareMeters import com.hedvig.botService.dataTypes.SSNSweden import com.hedvig.botService.dataTypes.TextInput import com.hedvig.botService.dataTypes.ZipCodeSweden import com.hedvig.botService.enteties.UserContext import com.hedvig.botService.enteties.message.KeyboardType import com.hedvig.botService.enteties.message.Message import com.hedvig.botService.enteties.message.MessageBody import com.hedvig.botService.enteties.message.MessageBodyBankIdCollect import com.hedvig.botService.enteties.message.MessageBodyMultipleSelect import com.hedvig.botService.enteties.message.MessageBodyNumber import com.hedvig.botService.enteties.message.MessageBodyParagraph import com.hedvig.botService.enteties.message.MessageBodySingleSelect import com.hedvig.botService.enteties.message.MessageBodyText import com.hedvig.botService.enteties.message.MessageHeader import com.hedvig.botService.enteties.message.SelectItem import com.hedvig.botService.enteties.message.SelectLink import com.hedvig.botService.enteties.message.SelectOption import com.hedvig.botService.enteties.message.TextContentType import com.hedvig.botService.enteties.userContextHelpers.UserData import com.hedvig.botService.enteties.userContextHelpers.UserData.IS_STUDENT import com.hedvig.botService.enteties.userContextHelpers.UserData.LOGIN import com.hedvig.botService.serviceIntegration.memberService.MemberService import com.hedvig.botService.serviceIntegration.memberService.dto.Flag import com.hedvig.botService.serviceIntegration.memberService.dto.Nationality import com.hedvig.botService.serviceIntegration.memberService.exceptions.ErrorType import com.hedvig.botService.serviceIntegration.underwriter.Underwriter import com.hedvig.botService.services.events.MemberSignedEvent import com.hedvig.botService.services.events.OnboardingCallForQuoteEvent import com.hedvig.botService.services.events.OnboardingQuestionAskedEvent import com.hedvig.botService.services.events.RequestObjectInsuranceEvent import com.hedvig.botService.services.events.RequestStudentObjectInsuranceEvent import com.hedvig.botService.services.events.UnderwritingLimitExcededEvent import com.hedvig.botService.utils.ConversationUtils import com.hedvig.botService.utils.ssnLookupAndStore import com.hedvig.botService.utils.storeAndTrimAndAddSSNToChat import com.hedvig.libs.translations.Translations import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.context.ApplicationEventPublisher import java.nio.charset.Charset import java.time.LocalDateTime import java.util.ArrayList class OnboardingConversationDevi( private val memberService: MemberService, private val underwriter: Underwriter, eventPublisher: ApplicationEventPublisher, private val conversationFactory: ConversationFactory, translations: Translations, @Value("\${hedvig.appleUser.email}") private val appleUserEmail: String, @Value("\${hedvig.appleUser.password}") private val appleUserPassword: String, private val phoneNumberUtil: PhoneNumberUtil, userContext: UserContext ) : Conversation(eventPublisher, translations, userContext), BankIdChat { var queuePos: Int? = null enum class ProductTypes { BRF, RENT, RENT_BRF, SUBLET_RENTAL, SUBLET_BRF, STUDENT_BRF, STUDENT_RENT, LODGER, HOUSE } init { //Not in use this.createChatMessage( MESSAGE_ONBOARDINGSTART, MessageBodySingleSelect( "Hej! Jag heter Hedvig 👋" + "\u000CJag behöver ställa några frågor till dig, för att kunna ge dig ett prisförslag på en hemförsäkring" + "\u000CDu signar inte upp dig på något genom att fortsätta!", Lists.newArrayList<SelectItem>( SelectOption("Låter bra!", MESSAGE_FORSLAGSTART), SelectOption("Jag är redan medlem", "message.bankid.start") ) ) ) this.createChatMessage( MESSAGE_ONBOARDINGSTART_SHORT, MessageBodyParagraph( "Hej! Jag heter Hedvig 👋" ) ) this.addRelayToChatMessage(MESSAGE_ONBOARDINGSTART_SHORT, MESSAGE_FORSLAGSTART) this.createChatMessage( MESSAGE_ONBOARDINGSTART_ASK_NAME, WrappedMessage( MessageBodyText( "Hej! Jag heter Hedvig 👋\u000CVad heter du?", TextContentType.GIVEN_NAME, KeyboardType.DEFAULT, "Förnamn" ) ) { body, u, message -> val name = body.text.trim().replace(Regex("[!.,]"), "") .replace(Regex("Hej jag heter", RegexOption.IGNORE_CASE), "").trim().capitalizeAll() u.onBoardingData.firstName = name addToChat(message) MESSAGE_ONBOARDINGSTART_REPLY_NAME }) this.createChatMessage( MESSAGE_ONBOARDINGSTART_REPLY_NAME, MessageBodySingleSelect( "Trevligt att träffas {NAME}!\u000CFör att kunna ge dig ett prisförslag" + " behöver jag ställa några snabba frågor" // + "\u000C" , SelectOption("Okej!", MESSAGE_ONBOARDINGSTART_ASK_EMAIL), SelectOption("Jag är redan medlem", "message.bankid.start") ) ) this.createChatMessage( MESSAGE_ONBOARDINGSTART_ASK_EMAIL, WrappedMessage( MessageBodyText( "Först, vad är din mailadress?", TextContentType.EMAIL_ADDRESS, KeyboardType.EMAIL_ADDRESS ) ) { body, userContext, message -> val trimmedEmail = body.text.trim() userContext.onBoardingData.email = trimmedEmail memberService.updateEmail(userContext.memberId, trimmedEmail) body.text = "Min email är {EMAIL}" addToChat(message) MESSAGE_FORSLAGSTART } ) this.setExpectedReturnType(MESSAGE_ONBOARDINGSTART_ASK_EMAIL, EmailAdress()) this.createChatMessage( "message.membernotfound", MessageBodySingleSelect( "Hmm, det verkar som att du inte är medlem här hos mig ännu" + "\u000CMen jag tar gärna fram ett försäkringsförslag till dig, det är precis som allt annat med mig superenkelt", Lists.newArrayList<SelectItem>(SelectOption("Låter bra!", MESSAGE_ONBOARDINGSTART_ASK_EMAIL_ALT)) ) ) this.createChatMessage( MESSAGE_ONBOARDINGSTART_ASK_EMAIL_ALT, WrappedMessage( MessageBodyText( "Först, vad är din mailadress?", TextContentType.EMAIL_ADDRESS, KeyboardType.EMAIL_ADDRESS ) ) { body, userContext, message -> val trimmedEmail = body.text.trim() userContext.onBoardingData.email = trimmedEmail memberService.updateEmail(userContext.memberId, trimmedEmail) body.text = "Min email är {EMAIL}" addToChat(message) MESSAGE_FORSLAGSTART } ) this.setExpectedReturnType(MESSAGE_ONBOARDINGSTART_ASK_EMAIL_ALT, EmailAdress()) this.createMessage( MESSAGE_NOTMEMBER, MessageBodyParagraph( "Okej! Då tar jag fram ett försäkringsförslag till dig på nolltid" ) ) this.addRelay(MESSAGE_NOTMEMBER, "message.notmember.start") this.createMessage( "message.notmember.start", MessageBodyParagraph( "Jag ställer några snabba frågor så att jag kan räkna ut ditt pris" ) ) this.addRelay("message.notmember.start", MESSAGE_ONBOARDINGSTART_ASK_EMAIL) this.createMessage( "message.uwlimit.tack", MessageBodySingleSelect( "Tack! Jag hör av mig så fort jag kan", listOf(SelectOption("Jag vill starta om chatten", "message.activate.ok.a")) ) ) this.createChatMessage( "message.medlem", WrappedMessage( MessageBodySingleSelect( "Välkommen tillbaka " + emoji_hug + "\n\n Logga in med BankID så är du inne i appen igen", listOf( SelectLink( "Logga in", "message.bankid.autostart.respond", null, "bankid:///?autostarttoken={AUTOSTART_TOKEN}&redirect={LINK_URI}", null, false ) ) ) ) { m: MessageBodySingleSelect, uc: UserContext, _ -> val obd = uc.onBoardingData if (m.selectedItem.value == "message.bankid.autostart.respond") { uc.putUserData(LOGIN, "true") obd.bankIdMessage = "message.medlem" } m.selectedItem.value }) setupBankidErrorHandlers("message.medlem") // Deprecated this.createMessage( MESSAGE_PRE_FORSLAGSTART, MessageBodyParagraph( "Toppen! Då ställer jag några frågor så att jag kan räkna ut ditt pris" ), 1500 ) this.addRelay(MESSAGE_PRE_FORSLAGSTART, MESSAGE_FORSLAGSTART) this.createMessage( MESSAGE_FORSLAGSTART, body = MessageBodySingleSelect( "Tack! Bor du i lägenhet eller eget hus?", SelectOption("Lägenhet", MESSAGE_LAGENHET_PRE), SelectOption("Hus", MESSAGE_HUS) ) ) this.createMessage(MESSAGE_LAGENHET_PRE, MessageBodyParagraph("👍")) this.addRelay(MESSAGE_LAGENHET_PRE, MESSAGE_LAGENHET_NO_PERSONNUMMER) this.createChatMessage( MESSAGE_LAGENHET_NO_PERSONNUMMER, WrappedMessage( MessageBodyNumber( "Vad är ditt personnummer? Jag behöver det så att jag kan hämta din adress", "ååmmddxxxx" ) ) { body, uc, m -> val (trimmedSSN, memberBirthDate) = uc.storeAndTrimAndAddSSNToChat(body) { m.body.text = it addToChat(m) } if (ConversationUtils.isYoungerThan18(memberBirthDate)) { return@WrappedMessage(MESSAGE_MEMBER_UNDER_EIGHTEEN) } val hasAddress = memberService.ssnLookupAndStore(uc, trimmedSSN, Nationality.SWEDEN) if (hasAddress) { MESSAGE_BANKIDJA } else { MESSAGE_LAGENHET_ADDRESSNOTFOUND } } ) this.setExpectedReturnType(MESSAGE_LAGENHET_NO_PERSONNUMMER, SSNSweden()) this.createChatMessage( MESSAGE_LAGENHET_ADDRESSNOTFOUND, WrappedMessage( MessageBodyText( "Konstigt, just nu kan jag inte hitta din adress. Så jag behöver ställa några extra frågor 😊\u000C" + "Vad heter du i efternamn?" , TextContentType.FAMILY_NAME, KeyboardType.DEFAULT ) ) { b, uc, m -> val familyName = b.text.trim().capitalizeAll() val firstName = uc.onBoardingData.firstName if (firstName != null) { if (firstName.split(" ").size > 1 && firstName.endsWith(familyName, true) == true) { val lastNameIndex = firstName.length - (familyName.length + 1) if (lastNameIndex > 0) { uc.onBoardingData.firstName = firstName.substring(0, lastNameIndex) } } } uc.onBoardingData.familyName = familyName addToChat(m) "message.varborduadress" }) this.createChatMessage( "fel.telefonnummer.format", WrappedMessage( MessageBodyText( "Det ser inte ut som ett korrekt svenskt telefonnummer... Prova igen tack!", TextContentType.TELEPHONE_NUMBER, KeyboardType.PHONE_PAD ) ) { b, uc, m -> if (phoneNumberIsCorrectSwedishFormat(b, m)) { "message.hedvig.ska.ringa.dig" } else { "fel.telefonnummer.format" } } ) this.createChatMessage( "message.vad.ar.ditt.telefonnummer", WrappedMessage( MessageBodyText( "Tack! Jag behöver ställa några frågor på telefon till dig, innan jag kan ge dig ditt förslag 🙂\u000C" + "Vilket telefonnummer kan jag nå dig på?", TextContentType.TELEPHONE_NUMBER, KeyboardType.PHONE_PAD ) ) { b, uc, m -> if (phoneNumberIsCorrectSwedishFormat(b, m)) { "message.hedvig.ska.ringa.dig" } else { "fel.telefonnummer.format" } } ) this.createChatMessage( "message.hedvig.ska.ringa.dig", MessageBodyText( "Tack så mycket. Jag hör av mig inom kort med ett förslag!" ) ) this.createChatMessage( "message.member.under.eighteen", WrappedMessage( MessageBodyParagraph( "Hoppsan! \uD83D\uDE4A För att skaffa en försäkring hos mig behöver du tyvärr ha fyllt 18 år" + "Om du råkade skriva fel personnummer så kan du testa att skriva igen \uD83D\uDE42" ) ) { b, uc, m -> MESSAGE_LAGENHET_NO_PERSONNUMMER } ) this.createChatMessage( MESSAGE_LAGENHET, WrappedMessage( MessageBodySingleSelect( "Har du BankID? I så fall kan vi hoppa över några frågor så du får se ditt prisförslag snabbare!", listOf( SelectLink( "Fortsätt med BankID", "message.bankid.autostart.respond.one", null, "bankid:///?autostarttoken={AUTOSTART_TOKEN}&redirect={LINK_URI}", null, false ), SelectOption("Fortsätt utan", "message.manuellnamn") ) ) ) { m, uc, _ -> val obd = uc.onBoardingData if (m.selectedItem.value == "message.bankid.autostart.respond.one") { obd.bankIdMessage = MESSAGE_LAGENHET } m.selectedItem.value } ) setupBankidErrorHandlers(MESSAGE_LAGENHET) this.createMessage( "message.missing.bisnode.data", MessageBodyParagraph( "Konstigt, just nu kan jag inte hitta din adress. Så jag behöver ställa några extra frågor 😊" ) ) this.addRelay("message.missing.bisnode.data", "message.manuellnamn") this.createMessage( MESSAGE_START_LOGIN, MessageBodyParagraph("Hej! $emoji_hug"), 1500 ) this.addRelay(MESSAGE_START_LOGIN, MESSAGE_LOGIN_WITH_EMAIL) this.createChatMessage( "message.bankid.start", WrappedMessage( MessageBodySingleSelect( "Bara att logga in så ser du din försäkring", SelectLink( "Logga in med BankID", "message.bankid.autostart.respond.two", null, "bankid:///?autostarttoken={AUTOSTART_TOKEN}&redirect={LINK_URI}", null, false ), SelectOption("Jag är inte medlem", MESSAGE_ONBOARDINGSTART_ASK_EMAIL_NOT_MEMBER) ) ) { body, uc, message -> body.text = body.selectedItem.text addToChat(message) val obd = uc.onBoardingData if (body.selectedItem.value == "message.bankid.autostart.respond.two") { obd.bankIdMessage = "message.bankid.start" uc.putUserData(LOGIN, "true") body.selectedItem.value } else if (body.selectedItem.value == MESSAGE_ONBOARDINGSTART_ASK_EMAIL_NOT_MEMBER) { uc.putUserData(LOGIN, "false") MESSAGE_ONBOARDINGSTART_ASK_EMAIL } else { body.selectedItem.value } }) setupBankidErrorHandlers("message.bankid.start") this.createMessage( "message.bankid.start.manual", MessageBodyNumber( "Om du anger ditt personnummer så får du använda bankId på din andra enhet$emoji_smile" ) ) this.createMessage( "message.bankid.error", MessageBodyParagraph("Hmm, det verkar inte som att ditt BankID svarar. Testa igen!"), 1500 ) this.createMessage( "message.bankid.start.manual.error", MessageBodyParagraph("Hmm, det verkar inte som att ditt BankID svarar. Testa igen!") ) this.addRelay("message.bankid.start.manual.error", "message.bankid.start.manual") this.createMessage( "message.bankid.autostart.respond", MessageBodyBankIdCollect("{REFERENCE_TOKEN}") ) this.createMessage( "message.bankid.autostart.respond.one", MessageBodyBankIdCollect("{REFERENCE_TOKEN}") ) this.createMessage( "message.bankid.autostart.respond.two", MessageBodyBankIdCollect("{REFERENCE_TOKEN}") ) this.createChatMessage( MESSAGE_LOGIN_FAILED_WITH_EMAIL, WrappedMessage( MessageBodySingleSelect( "Ojdå, det ser ut som att du måste logga in med BankID!", SelectLink( "Logga in med BankID", "message.bankid.autostart.respond.two", null, "bankid:///?autostarttoken={AUTOSTART_TOKEN}&redirect={LINK_URI}", null, false ), SelectOption("Jag är inte medlem", MESSAGE_ONBOARDINGSTART_ASK_EMAIL_NOT_MEMBER) ) ) { body, uc, message -> body.text = body.selectedItem.text addToChat(message) when (body.selectedItem.value) { "message.bankid.autostart.respond.two" -> { uc.onBoardingData.bankIdMessage = "message.bankid.start" uc.putUserData(LOGIN, "true") body.selectedItem.value } MESSAGE_ONBOARDINGSTART_ASK_EMAIL_NOT_MEMBER -> { uc.putUserData(LOGIN, "false") MESSAGE_ONBOARDINGSTART_ASK_EMAIL } else -> { body.selectedItem.value } } }) setupBankidErrorHandlers(MESSAGE_LOGIN_FAILED_WITH_EMAIL) this.createChatMessage(MESSAGE_LOGIN_WITH_EMAIL, WrappedMessage( MessageBodySingleSelect( "Bara att logga in så ser du din försäkring", SelectLink( "Logga in med BankID", "message.bankid.autostart.respond.two", null, "bankid:///?autostarttoken={AUTOSTART_TOKEN}&redirect={LINK_URI}", null, false ), SelectOption("Logga in med email och lösenord", MESSAGE_LOGIN_ASK_EMAIL), SelectOption("Jag är inte medlem", MESSAGE_ONBOARDINGSTART_ASK_EMAIL_NOT_MEMBER) ) ) { body, uc, message -> body.text = body.selectedItem.text addToChat(message) when (body.selectedItem.value) { "message.bankid.autostart.respond.two" -> { uc.onBoardingData.bankIdMessage = MESSAGE_LOGIN_WITH_EMAIL uc.putUserData(LOGIN, "true") body.selectedItem.value } MESSAGE_ONBOARDINGSTART_ASK_EMAIL_NOT_MEMBER -> { uc.putUserData(LOGIN, "false") MESSAGE_ONBOARDINGSTART_ASK_EMAIL } MESSAGE_LOGIN_ASK_EMAIL -> { uc.putUserData(LOGIN, "true") body.selectedItem.value } else -> { body.selectedItem.value } } }) setupBankidErrorHandlers(MESSAGE_LOGIN_WITH_EMAIL) this.createMessage( MESSAGE_LOGIN_WITH_EMAIL_ASK_PASSWORD, MessageBodyText( "Tack! Och vad är ditt lösenord?", TextContentType.PASSWORD, KeyboardType.DEFAULT ) ) this.createMessage(MESSAGE_LOGIN_WITH_EMAIL_PASSWORD_SUCCESS, MessageBodyText("Välkommen, Apple!")) this.createMessage( MESSAGE_LOGIN_ASK_EMAIL, MessageBodyText( "Vad är din email address?", TextContentType.EMAIL_ADDRESS, KeyboardType.EMAIL_ADDRESS ) ) this.setExpectedReturnType(MESSAGE_LOGIN_ASK_EMAIL, EmailAdress()) this.createChatMessage(MESSAGE_LOGIN_WITH_EMAIL_TRY_AGAIN, WrappedMessage( MessageBodySingleSelect( "Om du är medlem hos Hedvig med denna email måste du logga in med BankID!", SelectLink( "Logga in med BankID", "message.bankid.autostart.respond.two", null, "bankid:///?autostarttoken={AUTOSTART_TOKEN}&redirect={LINK_URI}", null, false ), SelectOption("Logga in med email och lösenord", MESSAGE_LOGIN_ASK_EMAIL), SelectOption("Jag är inte medlem", MESSAGE_ONBOARDINGSTART_ASK_EMAIL_NOT_MEMBER) ) ) { body, uc, message -> body.text = body.selectedItem.text addToChat(message) val obd = uc.onBoardingData when (body.selectedItem.value) { "message.bankid.autostart.respond.two" -> { obd.bankIdMessage = MESSAGE_LOGIN_WITH_EMAIL_TRY_AGAIN uc.putUserData(LOGIN, "true") body.selectedItem.value } MESSAGE_ONBOARDINGSTART_ASK_EMAIL_NOT_MEMBER -> { uc.putUserData(LOGIN, "false") MESSAGE_ONBOARDINGSTART_ASK_EMAIL } MESSAGE_LOGIN_ASK_EMAIL -> { uc.putUserData(LOGIN, "true") body.selectedItem.value } else -> { body.selectedItem.value } } }) setupBankidErrorHandlers(MESSAGE_LOGIN_WITH_EMAIL_TRY_AGAIN) this.createMessage( MESSAGE_TIPSA, MessageBodyText( "Kanon! Fyll i mailadressen till den du vill att jag ska skicka ett tipsmail till", TextContentType.EMAIL_ADDRESS, KeyboardType.EMAIL_ADDRESS ) ) this.setExpectedReturnType(MESSAGE_TIPSA, EmailAdress()) this.createMessage( MESSAGE_FRIFRAGA, MessageHeader(MessageHeader.HEDVIG_USER_ID, -1, true), MessageBodyText("Fråga på!") ) this.createMessage( MESSAGE_FRIONBOARDINGFRAGA, MessageHeader(MessageHeader.HEDVIG_USER_ID, -1, true), MessageBodyText("Fråga på! ") ) this.createMessage( MESSAGE_NAGOTMER, MessageBodySingleSelect( "Tack! Vill du hitta på något mer nu när vi har varandra på tråden?", SelectOption("Jag har en fråga", MESSAGE_FRIONBOARDINGFRAGA), SelectOption("Nej tack!", MESSAGE_AVSLUTOK) ) ) this.createChatMessage( MESSAGE_BANKIDJA, WrappedMessage( MessageBodySingleSelect( "Tack {NAME}! Är det lägenheten på {ADDRESS} jag ska ta fram ett förslag för?", SelectOption("Yes, stämmer bra!", MESSAGE_KVADRAT), SelectOption("Nix", MESSAGE_VARBORDUFELADRESS) ) ) { body, uc, m -> val item = body.selectedItem body.text = if (item.value == MESSAGE_KVADRAT) "Yes, stämmer bra!" else "Nix" addToChat(m) when { item.value == MESSAGE_KVADRAT -> handleStudentEntrypoint(MESSAGE_KVADRAT, uc) item.value == MESSAGE_VARBORDUFELADRESS -> { val obd = uc.onBoardingData obd.clearAddress() item.value } else -> item.value } } ) this.createMessage( "message.bankidja.noaddress", MessageBodyText( "Tack {NAME}! Nu skulle jag behöva veta vilken gatuadress bor du på?", TextContentType.STREET_ADDRESS_LINE1, KeyboardType.DEFAULT ) ) this.createMessage( MESSAGE_VARBORDUFELADRESS, MessageBodyText( "Inga problem! Vad är gatuadressen till lägenheten du vill försäkra?", TextContentType.STREET_ADDRESS_LINE1, KeyboardType.DEFAULT, "Kungsgatan 1" ) ) this.createMessage( "message.varbordufelpostnr", MessageBodyNumber("Och vad har du för postnummer?", TextContentType.POSTAL_CODE, "123 45") ) this.setExpectedReturnType("message.varbordufelpostnr", ZipCodeSweden()) this.createMessage(MESSAGE_KVADRAT, MessageBodyNumber("Hur många kvadratmeter är lägenheten?")) this.createMessage(MESSAGE_KVADRAT_ALT, MessageBodyNumber("Hur många kvadratmeter är lägenheten?")) this.setExpectedReturnType(MESSAGE_KVADRAT, LivingSpaceSquareMeters()) this.setExpectedReturnType(MESSAGE_KVADRAT_ALT, LivingSpaceSquareMeters()) this.createChatMessage( "message.manuellnamn", MessageBodyText( "Inga problem! Då ställer jag bara några extra frågor nu\u000CMen om du vill bli medlem sen så måste du signera med BankID, bara så du vet!\u000CVad heter du i förnamn?" , TextContentType.GIVEN_NAME, KeyboardType.DEFAULT ) ) this.createMessage( "message.manuellfamilyname", MessageBodyText( "Kul att ha dig här {NAME}! Vad heter du i efternamn?", TextContentType.FAMILY_NAME, KeyboardType.DEFAULT ) ) this.createMessage( "message.manuellpersonnr", MessageBodyNumber("Tack! Vad är ditt personnummer? (12 siffror)") ) this.setExpectedReturnType("message.manuellpersonnr", SSNSweden()) this.createMessage( "message.varborduadress", MessageBodyText( "Vilken gatuadress bor du på?", TextContentType.STREET_ADDRESS_LINE1, KeyboardType.DEFAULT, "Kungsgatan 1" ) ) this.createMessage( "message.varbordupostnr", MessageBodyNumber("Vad är ditt postnummer?", TextContentType.POSTAL_CODE, "123 45") ) this.setExpectedReturnType("message.varbordupostnr", ZipCodeSweden()) this.createMessage( "message.lghtyp", MessageBodySingleSelect( "Perfekt! Hyr du eller äger du den?", SelectOption("Jag hyr den", ProductTypes.RENT.toString()), SelectOption("Jag äger den", ProductTypes.BRF.toString()) ) ) this.createMessage( "message.lghtyp.sublet", MessageBodySingleSelect( "Okej! Är lägenheten du hyr i andra hand en hyresrätt eller bostadsrätt?", SelectOption("Hyresrätt", ProductTypes.SUBLET_RENTAL.toString()), SelectOption("Bostadsrätt", ProductTypes.SUBLET_BRF.toString()) ) ) this.createMessage(MESSAGE_ASK_NR_RESIDENTS, MessageBodyNumber("Okej! Hur många bor där?")) this.setExpectedReturnType(MESSAGE_ASK_NR_RESIDENTS, HouseholdMemberNumber()) this.createMessage( MESSAGE_SAKERHET, MessageBodyMultipleSelect( "Finns någon av de här säkerhetsgrejerna i lägenheten?", Lists.newArrayList( SelectOption("Brandvarnare", "safety.alarm"), SelectOption("Brandsläckare", "safety.extinguisher"), SelectOption("Säkerhetsdörr", "safety.door"), SelectOption("Gallergrind", "safety.gate"), SelectOption("Inbrottslarm", "safety.burglaralarm"), SelectOption("Inget av dessa", "safety.none", false, true) ) ) ) this.createMessage( MESSAGE_PHONENUMBER, MessageBodyNumber("Nu är vi snart klara! Vad är ditt telefonnummer?") ) this.setExpectedReturnType(MESSAGE_PHONENUMBER, TextInput()) this.createMessage( MESSAGE_EMAIL, MessageBodyText( "Nu behöver jag bara din mailadress så att jag kan skicka en bekräftelse", TextContentType.EMAIL_ADDRESS, KeyboardType.EMAIL_ADDRESS ) ) this.setExpectedReturnType(MESSAGE_EMAIL, EmailAdress()) this.createMessage( MESSAGE_FORSAKRINGIDAG, MessageBodySingleSelect( "Har du någon hemförsäkring idag?", SelectOption("Ja", MESSAGE_FORSAKRINGIDAGJA), SelectOption("Nej", MESSAGE_FORSLAG2) ) ) this.createMessage( MESSAGE_FORSAKRINGIDAGJA, MessageBodySingleSelect( "Okej! Vilket försäkringsbolag har du?", SelectOption("If", "if"), SelectOption("ICA", "ICA"), SelectOption("Folksam", "Folksam"), SelectOption("Trygg-Hansa", "Trygg-Hansa"), SelectOption("Länsförsäkringar", "Länsförsäkringar"), SelectOption("Länsförsäkringar Stockholm", "Länsförsäkringar Stockholm"), SelectOption("Annat bolag", "message.bolag.annat.expand"), SelectOption("Ingen aning", "message.bolag.vetej") ) ) this.createMessage( "message.bolag.annat.expand", MessageBodySingleSelect( "Okej! Är det något av dessa kanske?", SelectOption("Moderna", "Moderna"), SelectOption("Tre Kronor", "Tre Kronor"), SelectOption("Vardia", "Vardia"), SelectOption("Gjensidige", "Gjensidige"), SelectOption("Aktsam", "Aktsam"), SelectOption("Dina Försäkringar", "Dina Försäkringar"), SelectOption("Annat bolag", MESSAGE_ANNATBOLAG) ) ) this.createMessage( "message.bolag.vetej", MessageBodyParagraph("Inga problem, det kan vi ta senare") ) this.addRelay("message.bolag.vetej", MESSAGE_FORSLAG2) this.createMessage( MESSAGE_ANNATBOLAG, MessageBodyText("Okej, vilket försäkringsbolag har du?"), 2000 ) this.createChatMessage( "message.bolag.not.switchable", MessageBodySingleSelect( "👀\u000C" + "Okej! Om du blir medlem hos mig så aktiveras din försäkring här först när din nuvarande försäkring gått ut\u000C" + "Du kommer behöva ringa ditt försäkringbolag och säga upp din försäkring. Men jag hjälper dig med det så gott jag kan 😊", listOf( SelectOption("Jag förstår", MESSAGE_FORSLAG2_ALT_1), // Create product SelectOption("Förklara mer", "message.forklara.mer.bolag.not.switchable") ) ) ) this.createChatMessage( MESSAGE_BYTESINFO, MessageBodySingleSelect( "👀\u000C" + "Okej, om du blir medlem hos mig sköter jag bytet åt dig\u000CSå när din gamla försäkring går ut, flyttas du automatiskt till Hedvig", listOf( SelectOption("Jag förstår", MESSAGE_FORSLAG2_ALT_1), // Create product SelectOption("Förklara mer", "message.bytesinfo3") ) ) ) this.createChatMessage( "message.bytesinfo3", MessageBodySingleSelect( "Självklart!\u000C" + "Oftast har du ett tag kvar på bindningstiden på din gamla försäkring\u000C" + "Om du väljer att byta till Hedvig så hör jag av mig till ditt försäkringsbolag och meddelar att du vill byta försäkring så fort bindningstiden går ut\u000C" + "Till det behöver jag en fullmakt från dig som du skriver under med mobilt BankID \u000C" + "Sen börjar din nya försäkring gälla direkt när den gamla går ut\u000C" + "Så du behöver aldrig vara orolig att gå utan försäkring efter att du skrivit på med mig", object : ArrayList<SelectItem>() { init { add(SelectOption("Okej!", MESSAGE_FORSLAG2_ALT_2)) // Create product } }) ) this.createChatMessage( "message.forklara.mer.bolag.not.switchable", MessageBodySingleSelect( "Självklart! De flesta försäkringsbolagen har som policy att man måste säga upp sin försäkring över telefon, kanske för att göra det extra krångligt för dig att säga upp din försäkring 🙄 Jag kommer maila dig vilket nummer du behöver ringa och vad du behöver säga, det brukar gå rätt fort", object : ArrayList<SelectItem>() { init { add(SelectOption("Okej!", MESSAGE_FORSLAG2_ALT_2)) // Create product } }) ) this.createChatMessage( "message.hedvig.uwlimit.askemail", MessageBodyText( "Tack! Tyvärr kan vi inte ta fram ett pris till dig här i appen. En av våra försäkringsexperter behöver kika på din ansökan. För att få ditt erbjudande, maila till oss på [email protected]" ) ) this.createChatMessage( MESSAGE_50K_LIMIT, WrappedMessage( MessageBodySingleSelect( "Toppen!\u000CÄger du något som du tar med dig utanför hemmet som är värt över 50 000 kr som du vill försäkra? 💍", SelectOption("Ja, berätta om objektsförsäkring", MESSAGE_50K_LIMIT_YES), SelectOption("Nej, gå vidare utan", MESSAGE_50K_LIMIT_NO) ) ) { body, userContext, m -> val ssn = userContext.onBoardingData.ssn if (checkSSN(ssn) == Flag.RED) { completeOnboarding() return@WrappedMessage ("message.hedvig.uwlimit.askemail") } for (o in body.choices) { if (o.selected) { m.body.text = o.text addToChat(m) } } if (body.selectedItem.value.equals(MESSAGE_50K_LIMIT_YES, ignoreCase = true)) { userContext.putUserData("{50K_LIMIT}", "true") } body.selectedItem.value } ) this.createChatMessage( MESSAGE_50K_LIMIT_YES, MessageBodySingleSelect( "Om du har något som är värt mer än 50 000 kr och som du har med dig på stan, så behöver du lägga till ett extra skydd för den saken!\u000CDet kallas objektsförsäkring, och du lägger enkelt till det i efterhand om du skaffar Hedvig", SelectOption("Jag förstår!", MESSAGE_50K_LIMIT_YES_YES) ) ) //This message is used as the last message to the 25K LIMIT flow as well as to 50K LIMIT flow this.createMessage( MESSAGE_50K_LIMIT_YES_YES, MessageBodyParagraph("Toppen, så hör bara av dig i chatten så fixar jag det!"), 1500 ) this.addRelay(MESSAGE_50K_LIMIT_YES_YES, MESSAGE_FORSAKRINGIDAG) this.createMessage( MESSAGE_50K_LIMIT_YES_NO, MessageBodyParagraph("Då skippar jag det $emoji_thumbs_up"), 2000 ) this.addRelay(MESSAGE_50K_LIMIT_YES_NO, MESSAGE_FORSAKRINGIDAG) this.createMessage( MESSAGE_50K_LIMIT_NO, MessageBodyParagraph("Vad bra! Då täcks dina prylar av drulleförsäkringen när du är ute på äventyr"), 2000 ) this.createMessage( MESSAGE_50K_LIMIT_NO_1, MessageBodyParagraph( "Köper du någon dyr pryl i framtiden så fixar jag så klart det också!" ), 2000 ) this.addRelay(MESSAGE_50K_LIMIT_NO, MESSAGE_50K_LIMIT_NO_1) this.addRelay(MESSAGE_50K_LIMIT_NO_1, MESSAGE_FORSAKRINGIDAG) this.createMessage( MESSAGE_FORSLAG, MessageBodyParagraph("Sådär, det var all info jag behövde. Tack!"), 2000 ) this.createChatMessage( MESSAGE_FORSLAG2, WrappedMessage(MessageBodySingleSelect( "Sådärja, tack {NAME}! Det var alla frågor jag hade!", Lists.newArrayList<SelectItem>( SelectLink.toOffer("Gå vidare för att se ditt förslag 👏", "message.forslag.dashboard") ) ), addMessageCallback = { uc -> this.completeOnboarding() }, receiveMessageCallback = { _, _, _ -> MESSAGE_FORSLAG2 }) ) this.createChatMessage( MESSAGE_FORSLAG2_ALT_1, WrappedMessage(MessageBodySingleSelect( "Sådärja, tack {NAME}! Det var alla frågor jag hade!", Lists.newArrayList<SelectItem>( SelectLink.toOffer("Gå vidare för att se ditt förslag 👏", "message.forslag.dashboard") ) ), addMessageCallback = { uc -> this.completeOnboarding() }, receiveMessageCallback = { _, _, _ -> MESSAGE_FORSLAG2 }) ) this.createChatMessage( MESSAGE_FORSLAG2_ALT_2, WrappedMessage(MessageBodySingleSelect( "Sådärja, tack {NAME}! Det var alla frågor jag hade!", Lists.newArrayList<SelectItem>( SelectLink.toOffer("Gå vidare för att se ditt förslag 👏", "message.forslag.dashboard") ) ), addMessageCallback = { uc -> this.completeOnboarding() }, receiveMessageCallback = { _, _, _ -> MESSAGE_FORSLAG2 }) ) this.addRelay(MESSAGE_FORSLAG, MESSAGE_FORSLAG2) this.createChatMessage( "message.tryggt", MessageBodySingleSelect( "" + "Självklart!\u000CHedvig är backat av en av världens största försäkringsbolag, så att du kan känna dig trygg i alla lägen\u000CDe är där för mig, så jag alltid kan vara där för dig\u000CJag är självklart också auktoriserad av Finansinspektionen " + emoji_mag, object : ArrayList<SelectItem>() { init { add( SelectLink( "Visa förslaget igen", "message.forslag.dashboard", "Offer", null, null, false ) ) add(SelectOption("Jag har en annan fråga", "message.quote.close")) } }) ) this.createChatMessage( "message.skydd", MessageBodySingleSelect( "" + "Såklart! Med mig har du samma grundskydd som en vanlig hemförsäkring\u000CUtöver det ingår alltid drulle, alltså till exempel om du tappar din telefon i golvet och den går sönder, och ett bra reseskydd", object : ArrayList<SelectItem>() { init { add( SelectLink( "Visa förslaget igen", "message.forslag.dashboard", "Offer", null, null, false ) ) add(SelectOption("Jag har en annan fråga", "message.quote.close")) // add(new SelectOption("Jag vill bli medlem", "message.forslag")); } }) ) this.createMessage( "message.frionboardingfragatack", MessageBodySingleSelect( "Tack! Jag hör av mig inom kort", object : ArrayList<SelectItem>() { init { add(SelectOption("Jag har fler frågor", MESSAGE_FRIONBOARDINGFRAGA)) } }) ) this.createMessage( "message.frifragatack", MessageBodySingleSelect( "Tack! Jag hör av mig inom kort", object : ArrayList<SelectItem>() { init { add( SelectLink( "Visa förslaget igen", "message.forslag.dashboard", "Offer", null, null, false ) ) add(SelectOption("Jag har fler frågor", MESSAGE_FRIFRAGA)) } }) ) this.createChatMessage( "message.uwlimit.housingsize", MessageBodyText( "Det var stort! För att kunna försäkra så stora lägenheter behöver vi ta några grejer över telefon\u000CVad är ditt nummer?", TextContentType.TELEPHONE_NUMBER, KeyboardType.DEFAULT ) ) this.createChatMessage( "message.uwlimit.householdsize", MessageBodyText( "Okej! För att kunna försäkra så många i samma lägenhet behöver vi ta några grejer över telefon\u000CVad är ditt nummer?", TextContentType.TELEPHONE_NUMBER, KeyboardType.DEFAULT ) ) this.createChatMessage( "message.pris", MessageBodySingleSelect( "Det är knepigt att jämföra försäkringspriser, för alla försäkringar är lite olika.\u000CMen grundskyddet jag ger är väldigt brett utan att du behöver betala för krångliga tillägg\u000CSom Hedvigmedlem gör du dessutom skillnad för världen runtomkring dig, vilket du garanterat inte gör genom din gamla försäkring!", object : ArrayList<SelectItem>() { init { add( SelectLink( "Visa förslaget igen", "message.forslag.dashboard", "Offer", null, null, false ) ) add(SelectOption("Jag har fler frågor", "message.quote.close")) } }) ) this.createMessage( "message.bankid.error.expiredTransaction", MessageBodyParagraph(BankIDStrings.expiredTransactionError), 1500 ) this.createMessage( "message.bankid.error.certificateError", MessageBodyParagraph(BankIDStrings.certificateError), 1500 ) this.createMessage( "message.bankid.error.userCancel", MessageBodyParagraph(BankIDStrings.userCancel), 1500 ) this.createMessage( "message.bankid.error.cancelled", MessageBodyParagraph(BankIDStrings.cancelled), 1500 ) this.createMessage( "message.bankid.error.startFailed", MessageBodyParagraph(BankIDStrings.startFailed), 1500 ) //Deperecated 2018-12-17 this.createMessage( "message.kontraktklar", MessageBodyParagraph("Hurra! 🎉 Välkommen som medlem {NAME}!") ) this.createMessage( "message.kontraktklar.ss", MessageBodySingleSelect( "Hurra! 🎉 Välkommen som medlem {NAME}!", SelectLink.toDashboard("Kolla in appen och bjud in dina vänner till Hedvig! 🙌 💕", "message.noop") ) ) this.createMessage( "message.kontrakt.email", MessageBodyText("OK! Vad är din mailadress?", TextContentType.EMAIL_ADDRESS, KeyboardType.EMAIL_ADDRESS) ) this.setExpectedReturnType("message.kontrakt.email", EmailAdress()) this.createMessage( "message.avslutvalkommen", MessageBodySingleSelect( "Hej så länge och ännu en gång, varmt välkommen!", object : ArrayList<SelectItem>() { init { add( SelectLink( "Nu utforskar jag", "onboarding.done", "Dashboard", null, null, false ) ) } }) ) this.createMessage( MESSAGE_AVSLUTOK, MessageBodySingleSelect( "Okej! Trevligt att chattas, ha det fint och hoppas vi hörs igen!", Lists.newArrayList<SelectItem>( SelectOption("Jag vill starta om chatten", MESSAGE_ONBOARDINGSTART_SHORT) ) ) ) this.createChatMessage( "message.quote.close", MessageBodySingleSelect( "Du kanske undrade över något" + "\u000CNågot av det här kanske?", object : ArrayList<SelectItem>() { init { add(SelectOption("Är Hedvig tryggt?", "message.tryggt")) add(SelectOption("Ger Hedvig ett bra skydd?", "message.skydd")) add(SelectOption("Är Hedvig prisvärt?", "message.pris")) add(SelectOption("Jag har en annan fråga", MESSAGE_FRIFRAGA)) add( SelectLink( "Visa förslaget igen", "message.forslag.dashboard", "Offer", null, null, false ) ) } }) ) this.createMessage("error", MessageBodyText("Oj nu blev något fel...")) // Student policy-related messages this.createMessage( "message.student", MessageBodySingleSelect( "Okej! Jag ser att du är under 30. Är du kanske student? $emoji_school_satchel", SelectOption("Ja", "message.studentja"), SelectOption("Nej", "message.studentnej") ) ) this.createMessage("message.studentnej", MessageBodyParagraph("Okej, då vet jag")) this.addRelay("message.studentnej", MESSAGE_KVADRAT) this.createMessage( "message.studentja", MessageBodySingleSelect( "Vad kul! Då har jag ett erbjudande som är skräddarsytt för studenter som bor max två personer på max 50 kvm", object : ArrayList<SelectItem>() { init { add(SelectOption("Okej, toppen!", MESSAGE_KVADRAT_ALT)) } }) ) this.createChatMessage( MESSAGE_STUDENT_LIMIT_LIVING_SPACE, MessageBodySingleSelect( "Okej! För så stora lägenheter (över 50 kvm) gäller dessvärre inte studentförsäkringen\u000C" + "Men inga problem, du får den vanliga hemförsäkringen som ger ett bredare skydd och jag fixar ett grymt pris till dig ändå! 🙌", Lists.newArrayList<SelectItem>( SelectOption( "Okej, jag förstår", MESSAGE_STUDENT_LIMIT_LIVING_SPACE_HOUSE_TYPE ) ) ) ) this.createMessage( MESSAGE_STUDENT_LIMIT_LIVING_SPACE_HOUSE_TYPE, MessageBodySingleSelect( "Hyr du eller äger du lägenheten?", SelectOption("Jag hyr den", ProductTypes.RENT.toString()), SelectOption("Jag äger den", ProductTypes.BRF.toString()) ) ) this.createChatMessage( MESSAGE_STUDENT_LIMIT_PERSONS, MessageBodySingleSelect( "Okej! För så många personer (fler än 2) gäller dessvärre inte studentförsäkringen\u000C" + "Men inga problem, du får den vanliga hemförsäkringen som ger ett bredare skydd och jag fixar ett grymt pris till dig ändå! 🙌", Lists.newArrayList<SelectItem>(SelectOption("Okej, jag förstår", MESSAGE_STUDENT_25K_LIMIT)) ) ) this.createMessage( MESSAGE_STUDENT_ELIGIBLE_BRF, MessageBodySingleSelect( "Grymt! Då får du vår fantastiska studentförsäkring där drulle ingår och betalar bara 99 kr per månad! 🙌", Lists.newArrayList<SelectItem>(SelectOption("Okej, nice!", MESSAGE_STUDENT_25K_LIMIT)) ) ) this.createMessage( MESSAGE_STUDENT_ELIGIBLE_RENT, MessageBodySingleSelect( "Grymt! Då får du vår fantastiska studentförsäkring där drulle ingår och betalar bara 79 kr per månad! 🙌", Lists.newArrayList<SelectItem>(SelectOption("Okej, nice!", MESSAGE_STUDENT_25K_LIMIT)) ) ) this.createChatMessage( MESSAGE_STUDENT_25K_LIMIT, WrappedMessage( MessageBodySingleSelect( "Äger du något som du tar med dig utanför hemmet som är värt över 25 000 kr som du vill försäkra? 💍", Lists.newArrayList<SelectItem>( SelectOption("Ja, berätta om objektsförsäkring", MESSAGE_STUDENT_25K_LIMIT_YES), SelectOption("Nej, gå vidare utan", MESSAGE_50K_LIMIT_NO) ) ) ) { body, userContext, m -> for (o in body.choices) { if (o.selected) { m.body.text = o.text addToChat(m) } } if (body.selectedItem.value.equals(MESSAGE_STUDENT_25K_LIMIT_YES, ignoreCase = true)) { userContext.putUserData(UserData.TWENTYFIVE_THOUSAND_LIMIT, "true") } body.selectedItem.value } ) this.createChatMessage( MESSAGE_STUDENT_25K_LIMIT_YES, MessageBodySingleSelect( "Om du har något som är värt mer än 25 000 kr och som du har med dig på stan, så behöver du lägga till ett extra skydd för den saken!\u000CDet kallas objektsförsäkring, och du lägger enkelt till det i efterhand om du skaffar Hedvig", SelectOption("Jag förstår!", MESSAGE_50K_LIMIT_YES_YES) ) ) } private fun setupBankidErrorHandlers(messageId: String, optinalRelayId: String? = null) { val relayId = optinalRelayId ?: messageId this.createMessage( "$messageId.bankid.error.expiredTransaction", MessageBodyParagraph(BankIDStrings.expiredTransactionError), 1500 ) this.addRelay("$messageId.bankid.error.expiredTransaction", relayId) this.createMessage( "$messageId.bankid.error.certificateError", MessageBodyParagraph(BankIDStrings.certificateError), 1500 ) this.addRelay("$messageId.bankid.error.certificateError", relayId) this.createMessage( "$messageId.bankid.error.userCancel", MessageBodyParagraph(BankIDStrings.userCancel), 1500 ) this.addRelay("$messageId.bankid.error.userCancel", relayId) this.createMessage( "$messageId.bankid.error.cancelled", MessageBodyParagraph(BankIDStrings.cancelled), 1500 ) this.addRelay("$messageId.bankid.error.cancelled", relayId) this.createMessage( "$messageId.bankid.error.startFailed", MessageBodyParagraph(BankIDStrings.startFailed), 1500 ) this.addRelay("$messageId.bankid.error.startFailed", relayId) this.createMessage( "$messageId.bankid.error.invalidParameters", MessageBodyParagraph(BankIDStrings.userCancel), 1500 ) this.addRelay("$messageId.bankid.error.invalidParameters", relayId) } override fun init() { log.info("Starting onboarding conversation") startConversation(MESSAGE_ONBOARDINGSTART_ASK_NAME) // Id of first message } override fun init(startMessage: String) { log.info("Starting onboarding conversation with message: $startMessage") if (startMessage == MESSAGE_START_LOGIN) { userContext.putUserData(LOGIN, "true") } startConversation(startMessage) // Id of first message } // --------------------------------------------------------------------------- // // ------------------------------------------------------------------------------- // override fun receiveEvent(e: Conversation.EventTypes, value: String) { when (e) { // This is used to let Hedvig say multiple message after another Conversation.EventTypes.MESSAGE_FETCHED -> { log.info("Message fetched: $value") // New way of handeling relay messages val relay = getRelay(value) if (relay != null) { completeRequest(relay) } if (value == "message.kontraktklar") { endConversation(userContext) } } } } private fun completeOnboarding() { underwriter.createQuote(userContext) this.memberService.finalizeOnBoarding( userContext.memberId, userContext.onBoardingData ) } private fun phoneNumberIsCorrectSwedishFormat(b: MessageBody, m: Message): Boolean { val regex = Regex("[^0-9]") userContext.onBoardingData.phoneNumber = regex.replace(b.text, "") try { val swedishNumber = phoneNumberUtil.parse(userContext.onBoardingData.phoneNumber, "SE") if (phoneNumberUtil.isValidNumberForRegion(swedishNumber, "SE")) { sendPhoneNumberMessage(userContext) addToChat(m) return true } else { addToChat(m) return false } } catch (error: Exception) { "Error thrown when trying to validate phone number" + error.toString() } return false } private fun sendPhoneNumberMessage(uc: UserContext) { eventPublisher.publishEvent( OnboardingCallForQuoteEvent( uc.memberId, uc.onBoardingData.firstName, uc.onBoardingData.familyName, uc.onBoardingData.phoneNumber ) ) } override fun handleMessage(m: Message) { var nxtMsg = "" if (!validateReturnType(m)) { return } // Lambda if (this.hasSelectItemCallback(m.id) && m.body.javaClass == MessageBodySingleSelect::class.java) { // MessageBodySingleSelect body = (MessageBodySingleSelect) m.body; nxtMsg = this.execSelectItemCallback(m.id, m.body as MessageBodySingleSelect) addToChat(m) } val onBoardingData = userContext.onBoardingData // ... and then the incoming message id when (m.strippedBaseMessageId) { MESSAGE_STUDENT_LIMIT_LIVING_SPACE_HOUSE_TYPE, "message.lghtyp" -> { val item = (m.body as MessageBodySingleSelect).selectedItem // Additional question for sublet contracts m.body.text = item.text addToChat(m) if (item.value == "message.lghtyp.sublet") { nxtMsg = "message.lghtyp.sublet" } else { val obd = userContext.onBoardingData obd.houseType = item.value nxtMsg = MESSAGE_ASK_NR_RESIDENTS } } "message.lghtyp.sublet" -> { val item = (m.body as MessageBodySingleSelect).selectedItem val obd = userContext.onBoardingData obd.houseType = item.value m.body.text = item.text nxtMsg = MESSAGE_ASK_NR_RESIDENTS } "message.student" -> { val sitem2 = (m.body as MessageBodySingleSelect).selectedItem if (sitem2.value == "message.studentja") { m.body.text = "Yes" addToChat(m) userContext.putUserData(IS_STUDENT, "1") } else { m.body.text = "Nix" userContext.putUserData(IS_STUDENT, "0") } } MESSAGE_NYHETSBREV -> { onBoardingData.newsLetterEmail = m.body.text addToChat(m) nxtMsg = MESSAGE_NAGOTMER } "message.uwlimit.housingsize", "message.uwlimit.householdsize" -> nxtMsg = handleUnderwritingLimitResponse(userContext, m, m.baseMessageId) MESSAGE_TIPSA -> { onBoardingData.setRecommendFriendEmail(m.body.text) nxtMsg = MESSAGE_NAGOTMER } MESSAGE_FRIFRAGA -> { handleFriFraga(userContext, m) nxtMsg = "message.frifragatack" } MESSAGE_FRIONBOARDINGFRAGA -> { handleFriFraga(userContext, m) nxtMsg = "message.frionboardingfragatack" } MESSAGE_ASK_NR_RESIDENTS -> { val nrPersons = (m.body as MessageBodyNumber).value onBoardingData.setPersonInHouseHold(nrPersons) m.body.text = if (nrPersons == 1) { m.id = "message.pers.only.one" "Jag bor själv" } else { m.id = "message.pers.more.than.one" "Vi är {NR_PERSONS}" } addToChat(m) nxtMsg = if (nrPersons > 6) { "message.uwlimit.householdsize" } else { handleStudentPolicyPersonLimit(MESSAGE_FORSAKRINGIDAG, userContext) } } MESSAGE_KVADRAT, MESSAGE_KVADRAT_ALT -> { val kvm = m.body.text onBoardingData.livingSpace = java.lang.Float.parseFloat(kvm) m.body.text = "{KVM} kvm" addToChat(m) nxtMsg = if (Integer.parseInt(kvm) > MAX_LIVING_SPACE_RENT_SQM) { "message.uwlimit.housingsize" } else { handleStudentPolicyLivingSpace("message.lghtyp", userContext) } } "message.manuellnamn" -> { onBoardingData.firstName = m.body.text addToChat(m) nxtMsg = "message.manuellfamilyname" } "message.manuellfamilyname" -> { onBoardingData.familyName = m.body.text addToChat(m) nxtMsg = "message.manuellpersonnr" } "message.manuellpersonnr" -> { onBoardingData.ssn = m.body.text // Member service is responsible for handling SSN->birth date conversion try { memberService.startOnBoardingWithSSN(userContext.memberId, m.body.text) val member = memberService.getProfile(userContext.memberId) onBoardingData.birthDate = member.birthDate } catch (ex: Exception) { log.error("Error loading memberProfile from memberService", ex) } addToChat(m) nxtMsg = "message.varborduadress" } "message.bankidja.noaddress", MESSAGE_VARBORDUFELADRESS, "message.varborduadress" -> { onBoardingData.addressStreet = m.body.text addToChat(m) nxtMsg = "message.varbordupostnr" } "message.varbordupostnr" -> { onBoardingData.addressZipCode = m.body.text addToChat(m) nxtMsg = handleStudentEntrypoint(MESSAGE_KVADRAT, userContext) } "message.varbordu" -> { onBoardingData.addressStreet = m.body.text addToChat(m) nxtMsg = MESSAGE_KVADRAT } MESSAGE_SAKERHET -> { val body = m.body as MessageBodyMultipleSelect if (body.noSelectedOptions == 0L) { m.body.text = "Jag har inga säkerhetsgrejer" } else { m.body.text = String.format("Jag har %s", body.selectedOptionsAsString()) for (o in body.selectedOptions()) { onBoardingData.addSecurityItem(o.value) } } addToChat(m) val userData = userContext.onBoardingData nxtMsg = if (userData.studentPolicyEligibility == true) { MESSAGE_STUDENT_25K_LIMIT } else { MESSAGE_FORSAKRINGIDAG } } MESSAGE_PHONENUMBER -> { val trim = m.body.text.trim { it <= ' ' } userContext.putUserData("{PHONE_NUMBER}", trim) m.body.text = "Mitt telefonnummer är {PHONE_NUMBER}" addToChat(m) nxtMsg = MESSAGE_FORSAKRINGIDAG } MESSAGE_EMAIL -> { val trim2 = m.body.text.trim { it <= ' ' } userContext.putUserData("{EMAIL}", trim2) m.body.text = "Min email är {EMAIL}" memberService.updateEmail(userContext.memberId, trim2) addToChat(m) endConversation(userContext) return } MESSAGE_LOGIN_ASK_EMAIL -> { val trimEmail = m.body.text.trim().toLowerCase() userContext.putUserData("{LOGIN_EMAIL}", trimEmail) m.body.text = trimEmail addToChat(m) nxtMsg = if (trimEmail == appleUserEmail.toLowerCase()) { MESSAGE_LOGIN_WITH_EMAIL_ASK_PASSWORD } else { MESSAGE_LOGIN_FAILED_WITH_EMAIL } } MESSAGE_LOGIN_WITH_EMAIL_ASK_PASSWORD -> { val pwd = m.body.text m.body.text = "*****" addToChat(m) if (pwd == appleUserPassword) { nxtMsg = MESSAGE_LOGIN_WITH_EMAIL_PASSWORD_SUCCESS } else { nxtMsg = MESSAGE_LOGIN_WITH_EMAIL_TRY_AGAIN } } MESSAGE_LOGIN_WITH_EMAIL_PASSWORD_SUCCESS -> { endConversation(userContext); return; } // nxtMsg = MESSAGE_FORSAKRINGIDAG; // case "message.bytesinfo": "message.bytesinfo2", MESSAGE_FORSAKRINGIDAG, "message.missingvalue", MESSAGE_FORSLAG2, MESSAGE_FORSLAG2_ALT_1, MESSAGE_FORSLAG2_ALT_2 -> { val item = (m.body as MessageBodySingleSelect).selectedItem /* * Check if there is any data missing. Keep ask until Hedvig has got all info */ val missingItems = userContext.missingDataItem if (missingItems != null) { this.createMessage( "message.missingvalue", MessageBodyText( "Oj, nu verkar det som om jag saknar lite viktig information.$missingItems" ) ) m.body.text = item.text nxtMsg = "message.missingvalue" addToChat(m) addToChat(getMessage("message.missingvalue")) } else if (m.id == "message.missingvalue" || item.value == MESSAGE_FORSLAG2 || item.value == MESSAGE_FORSLAG2_ALT_1 || item.value == MESSAGE_FORSLAG2_ALT_2 ) { completeOnboarding() } } MESSAGE_ANNATBOLAG -> { val comp = m.body.text userContext.onBoardingData.currentInsurer = comp m.body.text = comp nxtMsg = MESSAGE_INSURER_NOT_SWITCHABLE addToChat(m) } MESSAGE_FORSAKRINGIDAGJA, "message.bolag.annat.expand" -> { val comp = (m.body as MessageBodySingleSelect).selectedItem.value if (!comp.startsWith("message.")) { userContext.onBoardingData.currentInsurer = comp m.body.text = comp if (comp != null && SwitchableInsurers.SWITCHABLE_INSURERS.contains(comp)) { nxtMsg = MESSAGE_BYTESINFO } else { nxtMsg = MESSAGE_INSURER_NOT_SWITCHABLE } addToChat(m) } } "message.forslagstart3" -> addToChat(m) "message.bankid.start.manual" -> { val ssn = m.body.text val ssnResponse = memberService.auth(ssn) if (!ssnResponse.isPresent) { log.error("Could not start bankIdAuthentication!") nxtMsg = "message.bankid.start.manual.error" } else { userContext.startBankIdAuth(ssnResponse.get()) } if (nxtMsg == "") { nxtMsg = "message.bankid.autostart.respond" } addToChat(m) } } val handledNxtMsg = handleSingleSelect(m, nxtMsg, listOf(MESSAGE_HUS)) completeRequest(handledNxtMsg) } private fun handleStudentEntrypoint(defaultMessage: String, uc: UserContext): String { val onboardingData = uc.onBoardingData return if (onboardingData.age in 1..29) { "message.student" } else defaultMessage } private fun handleStudentPolicyLivingSpace(defaultMessage: String, uc: UserContext): String { val onboardingData = uc.onBoardingData val isStudent = onboardingData.isStudent if (!isStudent) { return defaultMessage } val livingSpace = onboardingData.livingSpace return if (livingSpace > 50) { MESSAGE_STUDENT_LIMIT_LIVING_SPACE } else defaultMessage } private fun handleStudentPolicyPersonLimit(defaultMessage: String, uc: UserContext): String { val onboardingData = uc.onBoardingData val isStudent = onboardingData.isStudent if (!isStudent) { return defaultMessage } val livingSpace = onboardingData.livingSpace if (livingSpace > 50) { return defaultMessage } val personsInHousehold = onboardingData.personsInHouseHold if (personsInHousehold > 2) { onboardingData.studentPolicyEligibility = false return MESSAGE_STUDENT_LIMIT_PERSONS } onboardingData.studentPolicyEligibility = true val houseType = onboardingData.houseType if (houseType == ProductTypes.BRF.toString()) { onboardingData.houseType = ProductTypes.STUDENT_BRF.toString() return MESSAGE_STUDENT_ELIGIBLE_BRF } if (houseType == ProductTypes.RENT.toString()) { onboardingData.houseType = ProductTypes.STUDENT_RENT.toString() return MESSAGE_STUDENT_ELIGIBLE_RENT } log.error("This state should be unreachable") return defaultMessage } private fun handleFriFraga(userContext: UserContext, m: Message) { userContext.putUserData( "{ONBOARDING_QUESTION_" + LocalDateTime.now().toString() + "}", m.body.text ) eventPublisher.publishEvent( OnboardingQuestionAskedEvent(userContext.memberId, m.body.text) ) addToChat(m) } private fun handleUnderwritingLimitResponse( userContext: UserContext, m: Message, messageId: String ): String { userContext.putUserData("{PHONE_NUMBER}", m.body.text) val type = if (messageId.endsWith("householdsize")) UnderwritingLimitExcededEvent.UnderwritingType.HouseholdSize else UnderwritingLimitExcededEvent.UnderwritingType.HouseingSize val onBoardingData = userContext.onBoardingData eventPublisher.publishEvent( UnderwritingLimitExcededEvent( userContext.memberId, m.body.text, onBoardingData.firstName, onBoardingData.familyName, type ) ) addToChat(m) return "message.uwlimit.tack" } private fun endConversation(userContext: UserContext) { userContext.completeConversation(this) } /* * Generate next chat message or ends conversation */ override fun completeRequest(nxtMsg: String) { var nxtMsg = nxtMsg when (nxtMsg) { "message.medlem", "message.bankid.start", MESSAGE_LAGENHET, MESSAGE_LOGIN_WITH_EMAIL, MESSAGE_LOGIN_FAILED_WITH_EMAIL -> { val authResponse = memberService.auth(userContext.memberId) if (!authResponse.isPresent) { log.error("Could not start bankIdAuthentication!") nxtMsg = MESSAGE_ONBOARDINGSTART_SHORT } else { val bankIdAuthResponse = authResponse.get() userContext.startBankIdAuth(bankIdAuthResponse) } } MESSAGE_HUS -> { userContext.completeConversation(this) val conversation = conversationFactory.createConversation(HouseOnboardingConversation::class.java, userContext) userContext.startConversation(conversation, HouseConversationConstants.HOUSE_FIRST.id) return } "onboarding.done" -> { } "" -> { log.error("I dont know where to go next...") nxtMsg = "error" } } super.completeRequest(nxtMsg) } override fun getSelectItemsForAnswer(): List<SelectItem> { val items = Lists.newArrayList<SelectItem>() val questionId: String if (userContext.onBoardingData.houseType == MESSAGE_HUS) { questionId = MESSAGE_FRIONBOARDINGFRAGA } else { questionId = MESSAGE_FRIFRAGA items.add(SelectLink.toOffer("Visa mig förslaget", "message.forslag.dashboard")) } items.add(SelectOption("Jag har en till fråga", questionId)) return items } override fun canAcceptAnswerToQuestion(): Boolean { return true } override fun bankIdAuthComplete() { when { userContext.onBoardingData.userHasSigned!! -> { userContext.completeConversation(this) val mc = conversationFactory.createConversation(MainConversation::class.java, userContext) userContext.startConversation(mc, MESSAGE_HEDVIG_COM_POST_LOGIN) } userContext.getDataEntry(LOGIN) != null -> { userContext.removeDataEntry(LOGIN) addToChat(getMessage("message.membernotfound")) } else -> addToChat(getMessage(MESSAGE_BANKIDJA)) } } fun emailLoginComplete() { when { userContext.onBoardingData.userHasSigned ?: false -> { userContext.completeConversation(this) val mc = conversationFactory.createConversation(MainConversation::class.java, userContext) userContext.startConversation(mc) } } } override fun bankIdAuthCompleteNoAddress() { addToChat(getMessage("message.bankidja.noaddress")) } override fun bankIdAuthGeneralCollectError() { addToChat(getMessage("message.bankid.error")) val bankIdStartMessage = userContext.onBoardingData.bankIdMessage addToChat(getMessage(bankIdStartMessage)) } override fun memberSigned(referenceId: String) { val signed = userContext.onBoardingData.userHasSigned if (!signed) { val maybeActiveConversation = userContext.activeConversation if (maybeActiveConversation.isPresent) { val activeConversation = maybeActiveConversation.get() if (activeConversation.containsConversation(FreeChatConversation::class.java)) { activeConversation.setConversationStatus(Conversation.conversationStatus.COMPLETE) userContext.setActiveConversation(this) // Duct tape to shift onboarding conversation back into the correct state val onboardingConversation = userContext .activeConversation .orElseThrow { RuntimeException( "active conversation is for some reason not onboarding chat anymore" ) } onboardingConversation.conversationStatus = Conversation.conversationStatus.ONGOING } } addToChat(getMessage("message.kontraktklar.ss")) userContext.onBoardingData.userHasSigned = true userContext.setInOfferState(false) userContext.setOnboardingComplete() val productType = userContext.getDataEntry(UserData.HOUSE) val memberId = userContext.memberId val fiftyKLimit = userContext.getDataEntry("{50K_LIMIT}") val twentyFiveKLimit = userContext.getDataEntry(UserData.TWENTYFIVE_THOUSAND_LIMIT) when { fiftyKLimit == "true" -> eventPublisher.publishEvent(RequestObjectInsuranceEvent(memberId, productType)) twentyFiveKLimit == "true" -> eventPublisher.publishEvent( RequestStudentObjectInsuranceEvent( memberId, productType ) ) else -> eventPublisher.publishEvent(MemberSignedEvent(memberId, productType)) } } } override fun bankIdSignError() { addToChat(getMessage("message.kontrakt.signError")) } override fun oustandingTransaction() {} override fun noClient() {} override fun started() {} override fun userSign() {} override fun couldNotLoadMemberProfile() { addToChat(getMessage("message.missing.bisnode.data")) } override fun signalSignFailure(errorType: ErrorType, detail: String) { addBankIdErrorMessage(errorType, "message.kontraktpop.startBankId") } override fun signalAuthFailiure(errorType: ErrorType, detail: String) { addBankIdErrorMessage(errorType, userContext.onBoardingData.bankIdMessage) } private fun addBankIdErrorMessage(errorType: ErrorType, baseMessage: String) { val errorPostfix: String = when (errorType) { ErrorType.EXPIRED_TRANSACTION -> ".bankid.error.expiredTransaction" ErrorType.CERTIFICATE_ERR -> ".bankid.error.certificateError" ErrorType.USER_CANCEL -> ".bankid.error.userCancel" ErrorType.CANCELLED -> ".bankid.error.cancelled" ErrorType.START_FAILED -> ".bankid.error.startFailed" ErrorType.INVALID_PARAMETERS -> ".bankid.error.invalidParameters" else -> "" } val messageID = baseMessage + errorPostfix log.info("Adding bankIDerror message: {}", messageID) addToChat(getMessage(messageID)) } private fun String.capitalizeAll(): String { return this.split(regex = Regex("\\s")).map { it.toLowerCase().capitalize() }.joinToString(" ") } private fun checkSSN(ssn: String): Flag { try { memberService.checkPersonDebt(ssn) val personStatus = memberService.getPersonStatus(ssn) if (personStatus.whitelisted) { return Flag.GREEN } return personStatus.flag } catch (ex: Exception) { log.error("Error getting debt status from member-service", ex) return Flag.GREEN } } companion object { const val MAX_LIVING_SPACE_RENT_SQM = 250 const val MESSAGE_HUS = "message.hus" const val MESSAGE_NYHETSBREV = "message.nyhetsbrev" const val MESSAGE_FRIONBOARDINGFRAGA = "message.frionboardingfraga" const val MESSAGE_FRIFRAGA = "message.frifraga" const val MESSAGE_TIPSA = "message.tipsa" const val MESSAGE_AVSLUTOK = "message.avslutok" const val MESSAGE_NAGOTMER = "message.nagotmer" const val MESSAGE_ONBOARDINGSTART = "message.onboardingstart" const val MESSAGE_ONBOARDINGSTART_SHORT = "message.onboardingstart.short" const val MESSAGE_ONBOARDINGSTART_ASK_NAME = "message.onboardingstart.ask.name" const val MESSAGE_ONBOARDINGSTART_REPLY_NAME = "message.onboardingstart.reply.name" const val MESSAGE_ONBOARDINGSTART_ASK_EMAIL = "message.onboardingstart.ask.email" const val MESSAGE_ONBOARDINGSTART_ASK_EMAIL_ALT = "message.onboardingstart.ask.email.two" const val MESSAGE_ONBOARDINGSTART_ASK_EMAIL_NOT_MEMBER = "message.onboardingstart.ask.email.not.member" const val MESSAGE_LOGIN_ASK_EMAIL = "message.login.ask.email" const val MESSAGE_FORSLAG = "message.forslag" const val MESSAGE_FORSLAG2 = "message.forslag2" const val MESSAGE_FORSLAG2_ALT_1 = "message.forslag2.one" const val MESSAGE_FORSLAG2_ALT_2 = "message.forslag2.two" const val MESSAGE_50K_LIMIT = "message.fifty.k.limit" const val MESSAGE_50K_LIMIT_YES_NO = "message.fifty.k.limit.yes.no" @JvmField val MESSAGE_50K_LIMIT_YES_YES = "message.fifty.k.limit.yes.yes" const val MESSAGE_50K_LIMIT_YES = "message.fifty.k.limit.yes" const val MESSAGE_50K_LIMIT_NO = "message.fifty.k.limit.no" const val MESSAGE_50K_LIMIT_NO_1 = "message.fifty.k.limit.no.one" const val MESSAGE_PHONENUMBER = "message.phonenumber" const val MESSAGE_FORSAKRINGIDAG = "message.forsakringidag" const val MESSAGE_SAKERHET = "message.sakerhet" const val MESSAGE_FORSAKRINGIDAGJA = "message.forsakringidagja" const val MESSAGE_BYTESINFO = "message.bytesinfo" const val MESSAGE_ANNATBOLAG = "message.annatbolag" const val MESSAGE_FORSLAGSTART = "message.forslagstart" const val MESSAGE_EMAIL = "message.email" const val MESSAGE_PRE_FORSLAGSTART = "message.pre.forslagstart" @JvmField val MESSAGE_START_LOGIN = "message.start.login" const val MESSAGE_LAGENHET_PRE = "message.lagenhet.pre" const val MESSAGE_LAGENHET = "message.lagenhet" const val MESSAGE_LAGENHET_NO_PERSONNUMMER = "message.lagenhet.no.personnummer" const val MESSAGE_LAGENHET_ADDRESSNOTFOUND = "message.lagenhet.addressnotfound" const val MESSAGE_STUDENT_LIMIT_PERSONS = "message.student.limit.persons" const val MESSAGE_STUDENT_LIMIT_LIVING_SPACE = "message.student.limit.livingspace" const val MESSAGE_STUDENT_LIMIT_LIVING_SPACE_HOUSE_TYPE = "message.student.limit.livingspace.lghtyp" const val MESSAGE_STUDENT_ELIGIBLE_BRF = "message.student.eligible.brf" const val MESSAGE_STUDENT_ELIGIBLE_RENT = "message.student.eligible.rent" const val MESSAGE_STUDENT_25K_LIMIT = "message.student.twentyfive.k.limit" const val MESSAGE_STUDENT_25K_LIMIT_YES = "message.student.twentyfive.k.limit.yes" const val MESSAGE_LOGIN_WITH_EMAIL_ASK_PASSWORD = "message.login.with.mail.ask.password" const val MESSAGE_LOGIN_WITH_EMAIL = "message.login.with.mail" const val MESSAGE_LOGIN_WITH_EMAIL_TRY_AGAIN = "message.login.with.mail.try.again" const val MESSAGE_LOGIN_WITH_EMAIL_PASSWORD_SUCCESS = "message.login.with.mail.passwrod.success" const val MESSAGE_LOGIN_FAILED_WITH_EMAIL = "message.login.failed.with.mail" const val MESSAGE_INSURER_NOT_SWITCHABLE = "message.bolag.not.switchable" const val MESSAGE_MEMBER_UNDER_EIGHTEEN = "message.member.under.eighteen" const val MESSAGE_ASK_NR_RESIDENTS = "message.pers" @JvmField val IN_OFFER = "{IN_OFFER}" @JvmField val MESSAGE_BANKIDJA = "message.bankidja" private const val MESSAGE_KVADRAT = "message.kvadrat" private const val MESSAGE_KVADRAT_ALT = "message.kvadrat.one" @JvmField val MESSAGE_VARBORDUFELADRESS = "message.varbordufeladress" private const val MESSAGE_NOTMEMBER = "message.notmember" /* * Need to be stateless. I.e no data beyond response scope * * Also, message names cannot end with numbers!! Numbers are used for internal sectioning */ private val log = LoggerFactory.getLogger(OnboardingConversationDevi::class.java) val emoji_smile = String( byteArrayOf(0xF0.toByte(), 0x9F.toByte(), 0x98.toByte(), 0x81.toByte()), Charset.forName("UTF-8") ) val emoji_school_satchel = String( byteArrayOf(0xF0.toByte(), 0x9F.toByte(), 0x8E.toByte(), 0x92.toByte()), Charset.forName("UTF-8") ) val emoji_mag = String( byteArrayOf(0xF0.toByte(), 0x9F.toByte(), 0x94.toByte(), 0x8D.toByte()), Charset.forName("UTF-8") ) val emoji_thumbs_up = String( byteArrayOf(0xF0.toByte(), 0x9F.toByte(), 0x91.toByte(), 0x8D.toByte()), Charset.forName("UTF-8") ) val emoji_hug = String( byteArrayOf(0xF0.toByte(), 0x9F.toByte(), 0xA4.toByte(), 0x97.toByte()), Charset.forName("UTF-8") ) val emoji_flushed_face = String( byteArrayOf(0xF0.toByte(), 0x9F.toByte(), 0x98.toByte(), 0xB3.toByte()), Charset.forName("UTF-8") ) } }
agpl-3.0
a996ff50eda002161a9223ced3c10ee0
40.232203
331
0.558002
4.359196
false
false
false
false
Ztiany/Repository
Kotlin/Kotlin-Coroutines/src/main/kotlin/core/concurrency/06_MutualExclusion.kt
2
1728
package core.concurrency import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlin.system.measureTimeMillis /* 该问题的互斥解决方案:使用永远不会同时执行的 关键代码块 来保护共享状态的所有修改。在阻塞的世界中,你通常会为此目的使用 synchronized 或者 ReentrantLock。 在协程中的替代品叫做 Mutex 。它具有 lock 和 unlock 方法, 可以隔离关键的部分。关键的区别在于 Mutex.lock() 是一个挂起函数,它不会阻塞线程。 还有 withLock 扩展函数,可以方便的替代常用的 mutex.lock(); try { …… } finally { mutex.unlock() } 模式: 此示例中锁是细粒度的,因此会付出一些代价。但是对于某些必须定期修改共享状态的场景,它是一个不错的选择,但是没有自然线程可以限制此状态。 */ private suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) { val n = 100 // number of coroutines to launch val k = 1000 // times an action is repeated by each coroutine val time = measureTimeMillis { val jobs = List(n) { launch { repeat(k) { action() } } } jobs.forEach { it.join() } } println("Completed ${n * k} actions in $time ms") } private val mutex = Mutex() private var counter = 0 private fun main() = runBlocking<Unit> { //sampleStart GlobalScope.massiveRun { mutex.withLock { counter++ } } println("Counter = $counter") //sampleEnd }
apache-2.0
4ce9a537d75144c60bacaaa2fcee721e
27.847826
91
0.693062
3.218447
false
false
false
false
apixandru/intellij-community
python/src/com/jetbrains/python/inspections/PyOverloadsInspection.kt
11
4736
/* * 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.jetbrains.python.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import com.intellij.util.Processor import com.intellij.util.containers.SortedList import com.jetbrains.python.codeInsight.controlflow.ScopeOwner import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.PyUtil import com.jetbrains.python.pyi.PyiFile import com.jetbrains.python.pyi.PyiUtil import java.util.* class PyOverloadsInspection : PyInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session) private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) { override fun visitPyClass(node: PyClass?) { if (node?.containingFile is PyiFile) return super.visitPyClass(node) if (node != null) { processScope(node, { node.visitMethods(it, false, myTypeEvalContext) }) } } override fun visitPyFile(node: PyFile?) { if (node is PyiFile) return super.visitPyFile(node) if (node != null) { processScope(node, { processor -> node.topLevelFunctions.forEach { processor.process(it) } }) } } private fun processScope(owner: ScopeOwner, processorUsage: (GroupingFunctionsByNameProcessor) -> Unit) { val processor = GroupingFunctionsByNameProcessor() processorUsage(processor) processor.result.values.forEach { processSameNameFunctions(owner, it) } } private fun processSameNameFunctions(owner: ScopeOwner, functions: List<PyFunction>) { if (functions.find { PyiUtil.isOverload(it, myTypeEvalContext) } == null) return val implementation = functions.lastOrNull { !PyiUtil.isOverload(it, myTypeEvalContext) } if (implementation == null) { functions .maxBy { it.textOffset } ?.let { registerProblem(it.nameIdentifier, "A series of @overload-decorated ${chooseBetweenFunctionsAndMethods(owner)} " + "should always be followed by an implementation that is not @overload-ed") } } else { if (implementation != functions.last()) { registerProblem(functions.last().nameIdentifier, "A series of @overload-decorated ${chooseBetweenFunctionsAndMethods(owner)} " + "should always be followed by an implementation that is not @overload-ed") } functions .asSequence() .filter { isIncompatibleOverload(implementation, it) } .forEach { registerProblem(it.nameIdentifier, "Signature of this @overload-decorated ${chooseBetweenFunctionAndMethod(owner)} " + "is not compatible with the implementation") } } } private fun chooseBetweenFunctionsAndMethods(owner: ScopeOwner) = if (owner is PyClass) "methods" else "functions" private fun chooseBetweenFunctionAndMethod(owner: ScopeOwner) = if (owner is PyClass) "method" else "function" private fun isIncompatibleOverload(implementation: PyFunction, overload: PyFunction): Boolean { return implementation != overload && PyiUtil.isOverload(overload, myTypeEvalContext) && !PyUtil.isSignatureCompatibleTo(implementation, overload, myTypeEvalContext) } } private class GroupingFunctionsByNameProcessor : Processor<PyFunction> { val result: MutableMap<String, MutableList<PyFunction>> = HashMap() override fun process(t: PyFunction?): Boolean { val name = t?.name if (name != null) { result .getOrPut(name, { SortedList<PyFunction> { f1, f2 -> f1.textOffset - f2.textOffset } }) .add(t!!) } return true } } }
apache-2.0
8abc14904781d6b4d8550ee0537be665
37.201613
125
0.680743
4.693756
false
false
false
false
zathras/misc
maven_import/src/main/kotlin/Main.kt
1
1841
import com.jovial.db9010.* import java.util.logging.Logger import java.util.logging.Level import java.util.logging.LogRecord import java.util.logging.Handler object People : Table("People") { val id = TableColumn(this, "id", "INT AUTO_INCREMENT", Types.sqlInt) val name = TableColumn(this, "name", "VARCHAR(50) NOT NULL", Types.sqlString) val worried = TableColumn(this, "worried", "BOOLEAN NOT NULL", Types.sqlBoolean) override val primaryKeys = listOf(id) } fun main() { // Send logging to stdout so we can see the statements val logger = Logger.getLogger("com.jovial.db9010") val handler = object : Handler() { override fun publish(r: LogRecord) = println(r.message) override fun flush() { } override fun close() { } } logger.addHandler(handler) logger.setLevel(Level.FINE) Database.withConnection("jdbc:h2:mem:test", "root", "") { db -> db.createTable(People) db.statement().qualifyColumnNames(false).doNotCache() + "CREATE INDEX " + People + "_name on " + People + "(" + People.name + ")" run {} People.apply { db.insertInto(this) run { row -> row[name] = "Alfred E. Neuman" row[worried] = false } } val param = Parameter(Types.sqlString) db.select(People.columns).from(People) + "WHERE " + People.name + " <> " + param run { query -> query[param] = "Bob Dobbs" // Hide Bob, if he's there while (query.next()) { val idValue = query[People.id]; // It's type-safe println("id: ${idValue}") println("name: ${query[People.name]}") println("worried? ${query[People.worried]}") } } db.dropTable(People) } }
mit
7694245c2999862fc6784b7bb5aee2ec
32.472727
103
0.576317
3.819502
false
false
false
false
slartus/4pdaClient-plus
app/src/main/java/org/softeg/slartus/forpdaplus/devdb/helpers/ParseHelper.kt
1
6123
package org.softeg.slartus.forpdaplus.devdb.helpers import com.google.gson.Gson import org.jsoup.Jsoup import org.jsoup.nodes.Element import org.softeg.slartus.forpdaplus.devdb.model.* class ParseHelper { private val parsed = ParsedModel() fun parseHelper(page: String): ParsedModel { val main = Jsoup.parse(page).select(".device-frame").first() ?: error("device-frame not found") parseTitle(main) parseSpec(main) parseFirmware(main) parseComments(main) parseReviews(main) parseDiscussions(main) parsePrices(main) return parsed } private fun parseTitle(main: Element) { parsed.title = main.select(".product-name").first()?.text().orEmpty() } private fun parseSpec(main: Element) { val specModel = SpecModel() val spec = main.select("#specification").first() ?: return for (element in spec.select(".item-visual .item-gallery a")) { specModel.galleryLinks.add(element.attr("href")) specModel.galleryImages.add(element.select("img").first()!!.attr("src")) } val temp = spec.select(".item-main .price-box .price strong") if (temp.text().isNotEmpty()) specModel.price = temp.first()?.text().orEmpty() specModel.specTable = spec.select(".item-content .content .specifications-list") parsed.specModel = specModel } private fun parseDiscussions(main: Element) { var link: String var title: String var time: String var description: String val cache: MutableList<DiscussionModel> = ArrayList() for (element in main.select("#discussions .article-list li")) { link = element.select(".title a").first()?.attr("href").orEmpty() title = element.select(".title").first()?.text().orEmpty() time = element.select(".upd").first()?.text().orEmpty() description = element.select(".description").first()?.text().orEmpty() cache.add(DiscussionModel(description, time, link, title)) } parsed.discussionModels = Gson().toJson(cache) } private fun parseComments(main: Element) { var comment: String var link: String var userName: String var date: String var ratingNum: String var ratingText: String val cache: MutableList<CommentsModel> = ArrayList() val dr = ArrayList<String>() for (element1 in main.select("#comments .reviews li")) { if (!element1.select(".text-box").text().isEmpty()) { /** * Тут короче если текст бокс не нуль, то и все остальное не нуль. */ var element = element1.select(".text-box .w-toggle").first() if (element == null) element = element1.select(".text-box").first() comment = element?.text().orEmpty() element = element1.select("div.name a").first() link = element?.attr("href").orEmpty() userName = element?.attr("title").orEmpty() date = element1.select("div.date").first()?.text().orEmpty() ratingNum = element1.select("span.num").first()?.text().orEmpty() ratingText = element1.select("span.text").first()?.text().orEmpty() // for detail dialog val elements1 = element1.getElementsByClass("reviews-list") for (element2 in elements1) dr.add(element2.select("div.line").text()) cache.add(CommentsModel(date, ratingNum, ratingText, comment, link, userName, dr)) } } parsed.commentsModels = Gson().toJson(cache) } private fun parsePrices(main: Element) { var link: String var title: String var time: String var description: String val cache: MutableList<PricesModel> = ArrayList() val elements = main.select("#prices .article-list li") for (element in elements) { link = element.select(".title a").first()?.attr("href").orEmpty() title = element.select(".title").first()?.text().orEmpty() time = element.select(".upd").first()?.text().orEmpty() description = element.select(".description").first()?.text().orEmpty() cache.add(PricesModel(time, description, link, title)) } parsed.pricesModels = Gson().toJson(cache) } private fun parseFirmware(main: Element) { var link: String var title: String var time: String var description: String val cache: MutableList<FirmwareModel> = ArrayList() for (element in main.select("#firmware .article-list li")) { link = element.select(".title a").first()?.attr("href").orEmpty() title = element.select(".title").first()?.text().orEmpty() time = element.select(".upd").first()?.text().orEmpty() description = element.select(".description").first()?.text().orEmpty() cache.add(FirmwareModel(time, description, link, title)) } parsed.firmwareModels = Gson().toJson(cache) } private fun parseReviews(main: Element) { var url: String var imgLink: String var title: String var date: String var description: String val cache: MutableList<ReviewsModel> = ArrayList() for (element in main.select("#reviews .article-list li")) { url = element.select("a").first()?.attr("href").orEmpty() imgLink = element.select(".article-img img").first()?.attr("src").orEmpty() title = element.select(".title").first()?.text().orEmpty() date = element.select(".upd").first()?.text().orEmpty() description = element.select(".description").first()?.text().orEmpty() cache.add(ReviewsModel(date, imgLink, url, description, title)) } parsed.reviewsModels = Gson().toJson(cache) } }
apache-2.0
b247f1d07442d63822e8aa6a32d39f62
42.085106
98
0.589068
4.411038
false
false
false
false
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/payment/ml/CardDetectModelManager.kt
1
902
package com.stripe.android.stripecardscan.payment.ml import android.content.Context import com.stripe.android.stripecardscan.framework.Fetcher import com.stripe.android.stripecardscan.framework.ResourceFetcher import com.stripe.android.stripecardscan.payment.ModelManager private const val CARD_DETECT_ASSET_FULL = "ux_0_5_23_16.tflite" internal object CardDetectModelManager : ModelManager() { override fun getModelFetcher(context: Context): Fetcher = object : ResourceFetcher() { override val assetFileName: String = CARD_DETECT_ASSET_FULL override val modelVersion: String = "0.5.23.16" override val hash: String = "ea51ca5c693a4b8733b1cf1a63557a713a13fabf0bcb724385077694e63a51a7" override val hashAlgorithm: String = "SHA-256" override val modelClass: String = "card_detection" override val modelFrameworkVersion: Int = 1 } }
mit
757bb5b27afadf4de3cf96217b514bf7
44.1
90
0.759424
3.789916
false
false
false
false
hannesa2/owncloud-android
owncloudApp/src/main/java/com/owncloud/android/presentation/ui/logging/LogsListActivity.kt
2
3673
/* * ownCloud Android client application * * @author Fernando Sanz Velasco * Copyright (C) 2021 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * 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.owncloud.android.presentation.ui.logging import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.isVisible import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.owncloud.android.R import com.owncloud.android.databinding.LogsListActivityBinding import com.owncloud.android.extensions.openFile import com.owncloud.android.extensions.sendFile import com.owncloud.android.presentation.adapters.logging.RecyclerViewLogsAdapter import com.owncloud.android.presentation.viewmodels.logging.LogListViewModel import org.koin.androidx.viewmodel.ext.android.viewModel import java.io.File class LogsListActivity : AppCompatActivity() { private val viewModel by viewModel<LogListViewModel>() private var _binding: LogsListActivityBinding? = null val binding get() = _binding!! private val recyclerViewLogsAdapter = RecyclerViewLogsAdapter(object : RecyclerViewLogsAdapter.Listener { override fun share(file: File) { sendFile(file) } override fun delete(file: File) { file.delete() setData() } override fun open(file: File) { openFile(file) } }, context = this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = LogsListActivityBinding.inflate(layoutInflater) setContentView(binding.root) initToolbar() initList() } private fun initToolbar() { val toolbar = findViewById<Toolbar>(R.id.standard_toolbar) toolbar.isVisible = true findViewById<ConstraintLayout>(R.id.root_toolbar).isVisible = false setSupportActionBar(toolbar) supportActionBar?.apply { setTitle(R.string.prefs_log_open_logs_list_view) setDisplayHomeAsUpEnabled(true) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> finish() } return super.onOptionsItemSelected(item) } private fun initList() { binding.recyclerViewActivityLogsList.apply { layoutManager = LinearLayoutManager(context) itemAnimator = DefaultItemAnimator() adapter = recyclerViewLogsAdapter addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) } setData() } private fun setData() { val items = viewModel.getLogsFiles() binding.recyclerViewActivityLogsList.isVisible = items.isNotEmpty() binding.textViewNoLogs.isVisible = items.isEmpty() recyclerViewLogsAdapter.setData(items) } }
gpl-2.0
ef7167e54da5757ab6d08ad600515cb3
33.009259
109
0.719031
4.871353
false
false
false
false
noud02/Akatsuki
src/main/kotlin/moe/kyubey/akatsuki/commands/Volume.kt
1
2805
/* * Copyright (c) 2017-2019 Yui * * 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 moe.kyubey.akatsuki.commands import moe.kyubey.akatsuki.annotations.Argument import moe.kyubey.akatsuki.annotations.Load import moe.kyubey.akatsuki.annotations.Perm import moe.kyubey.akatsuki.entities.Command import moe.kyubey.akatsuki.entities.Context import moe.kyubey.akatsuki.music.MusicManager import moe.kyubey.akatsuki.utils.I18n import net.dv8tion.jda.core.Permission @Load @Perm(Permission.MANAGE_SERVER) @Argument("volume", "number", true) class Volume : Command() { override val desc = "Change the volume of the music." override val guildOnly = true override fun run(ctx: Context) { val manager = MusicManager.musicManagers[ctx.guild!!.id] ?: return ctx.send( I18n.parse( ctx.lang.getString("not_connected"), mapOf("username" to ctx.author.name) ) ) if ("volume" in ctx.args) { val vol = ctx.args["volume"] as Int if (vol > 100) { return ctx.send(ctx.lang.getString("too_loud")) } if (vol < 0) { return ctx.send(ctx.lang.getString("cant_hear")) } manager.player.volume = vol } ctx.send( I18n.parse( ctx.lang.getString("volume_changed"), mapOf( "volume" to "#".repeat(manager.player.volume / 10) + "-".repeat(10 - manager.player.volume / 10), "number" to manager.player.volume ) ) ) } }
mit
0a2fc8f2ffa36a79765ff01d18cbc4d3
35.441558
129
0.624599
4.295559
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/hints/parameter/RsInlayParameterHints.kt
2
2839
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.hints.parameter import com.intellij.codeInsight.hints.InlayInfo import com.intellij.codeInsight.hints.Option import com.intellij.psi.PsiElement import org.rust.RsBundle import org.rust.ide.utils.CallInfo import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.existsAfterExpansion import org.rust.lang.core.psi.ext.startOffset import org.rust.lang.core.types.emptySubstitution import org.rust.stdext.buildList @Suppress("UnstableApiUsage") object RsInlayParameterHints { val smartOption: Option = Option("SMART_HINTS", RsBundle.messagePointer("settings.rust.inlay.parameter.hints.only.smart"), true) val smart: Boolean get() = smartOption.get() fun provideHints(elem: PsiElement): List<InlayInfo> { val (callInfo, valueArgumentList) = when (elem) { is RsCallExpr -> (CallInfo.resolve(elem) to elem.valueArgumentList) is RsMethodCall -> (CallInfo.resolve(elem) to elem.valueArgumentList) else -> return emptyList() } if (!elem.existsAfterExpansion) return emptyList() if (callInfo == null) return emptyList() val hints = buildList<String> { if (callInfo.selfParameter != null && elem is RsCallExpr) { add(callInfo.selfParameter) } addAll(callInfo.parameters.map { it.pattern ?: (it.typeRef?.substAndGetText(emptySubstitution) ?: "_") }) }.zip(valueArgumentList.exprList) if (smart) { if (onlyOneParam(hints, callInfo, elem)) { if (callInfo.methodName?.startsWith("set_") != false) { return emptyList() } if (callInfo.methodName == callInfo.parameters.getOrNull(0)?.pattern) { return emptyList() } if (hints.lastOrNull()?.second is RsLambdaExpr) { return emptyList() } } if (hints.all { (hint, _) -> hint == "_" }) { return emptyList() } return hints .filter { (hint, arg) -> !arg.text.endsWith(hint) } .map { (hint, arg) -> InlayInfo("$hint:", arg.startOffset) } } return hints.map { (hint, arg) -> InlayInfo("$hint:", arg.startOffset) } } private fun onlyOneParam(hints: List<Pair<String, RsExpr>>, callInfo: CallInfo, elem: PsiElement): Boolean { if (callInfo.selfParameter != null && elem is RsCallExpr && hints.size == 2) { return true } if (!(callInfo.selfParameter != null && elem is RsCallExpr) && hints.size == 1) { return true } return false } }
mit
6ec2bbd339a35757f5f153d06471323f
37.890411
132
0.598098
4.40155
false
false
false
false
androidx/androidx
work/work-runtime/src/main/java/androidx/work/impl/model/WorkName.kt
3
1408
/* * Copyright 2018 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.work.impl.model import androidx.annotation.RestrictTo import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index /** * Database entity that defines a mapping from a name to a [WorkSpec] id. * * @hide */ @Entity( foreignKeys = [ForeignKey( entity = WorkSpec::class, parentColumns = ["id"], childColumns = ["work_spec_id"], onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.CASCADE )], primaryKeys = ["name", "work_spec_id"], indices = [Index(value = ["work_spec_id"])] ) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class WorkName( @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "work_spec_id") val workSpecId: String )
apache-2.0
6e314c7d6cf667a1541326469f5ea21b
29.630435
75
0.702415
4.011396
false
false
false
false
solkin/drawa-android
app/src/main/java/com/tomclaw/drawa/draw/DrawInteractor.kt
1
3305
package com.tomclaw.drawa.draw import com.tomclaw.drawa.core.Journal import com.tomclaw.drawa.dto.Record import com.tomclaw.drawa.util.SchedulersFactory import io.reactivex.Observable import io.reactivex.Single interface DrawInteractor { fun loadHistory(): Observable<Unit> fun saveHistory(): Observable<Unit> fun undo(): Observable<Unit> fun duplicate(): Observable<Unit> fun delete(): Observable<Unit> } class DrawInteractorImpl(private val recordId: Int, private val imageProvider: ImageProvider, private val journal: Journal, private val history: History, private val drawHostHolder: DrawHostHolder, private val schedulers: SchedulersFactory) : DrawInteractor { private var isDeleted = false override fun loadHistory(): Observable<Unit> { return resolve({ history.load() .flatMap { imageProvider.readImage(recordId) } .map { bitmap -> drawHostHolder.drawHost.applyBitmap(bitmap) bitmap.recycle() } .toObservable() .subscribeOn(schedulers.io()) }, { Observable.just(Unit) }) } override fun saveHistory(): Observable<Unit> { return resolve({ history.save() .flatMap { imageProvider.saveImage( recordId, drawHostHolder.drawHost.bitmap ) } .map { } .toObservable() .subscribeOn(schedulers.io()) }, { Observable.just(Unit) }) } override fun undo(): Observable<Unit> { return resolve({ Single .create<Unit> { emitter -> history.undo() emitter.onSuccess(Unit) } .toObservable() }, { Observable.just(Unit) }).subscribeOn(schedulers.single()) } override fun duplicate(): Observable<Unit> = Single .create<Record> { emitter -> val record = journal.create() journal.add(record) emitter.onSuccess(record) } .flatMap { record -> history.duplicate(record.id).map { record } } .flatMap { record -> imageProvider.duplicateImage( sourceRecordId = recordId, targetRecordId = record.id ) } .flatMap { journal.save() } .toObservable() .subscribeOn(schedulers.io()) override fun delete(): Observable<Unit> { isDeleted = true return history.delete() .flatMap { journal.delete(id = recordId) } .toObservable() .subscribeOn(schedulers.io()) } private fun <T> resolve(notDeleted: () -> T, deleted: () -> T): T { return if (isDeleted) deleted.invoke() else notDeleted.invoke() } }
apache-2.0
be8ea5d6e2a923148e1e55489cfb5b54
29.601852
86
0.4941
5.409165
false
false
false
false
coffeemakr/OST
app/src/main/java/ch/unstable/ost/views/lists/station/SectionsStopsListAdapter.kt
1
1203
package ch.unstable.ost.views.lists.station import android.view.View import ch.unstable.ost.R import ch.unstable.ost.api.model.PassingCheckpoint import ch.unstable.ost.utils.TimeDateUtils import ch.unstable.ost.views.lists.SingleTypeSimplerAdapter import ch.unstable.ost.views.StopDotView class SectionsStopsListAdapter : SingleTypeSimplerAdapter<PassingCheckpoint, SectionStationViewHolder>() { override val layout: Int get() = R.layout.item_connection_journey_station override fun onBindViewHolder(viewHolder: SectionStationViewHolder, element: PassingCheckpoint, position: Int) { with(viewHolder) { stationName.text = element.location.name if (position == 0) { stopDotView.setLineMode(StopDotView.Type.TOP) } else if (position == itemCount - 1) { stopDotView.setLineMode(StopDotView.Type.BOTTOM) } else { stopDotView.setLineMode(StopDotView.Type.BOTH) } TimeDateUtils.setStationStay(stationTime, element.arrivalTime, element.departureTime) } } override fun onCreateViewHolder(itemView: View) = SectionStationViewHolder(itemView) }
gpl-3.0
a4c20557fd7bcb6ae8d57d758ee1871e
34.382353
116
0.710723
4.327338
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/widget/LongHintEditText.kt
1
2218
/* * Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.widget import android.content.Context import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import androidx.appcompat.widget.AppCompatEditText /** * @author [email protected] * Inspired by http://stackoverflow.com/questions/31832665/android-how-to-create-edit-text-with-single-line-input-and-multiline-hint */ class LongHintEditText : AppCompatEditText { var mySingleLine = false constructor(context: Context) : super(context) { setTextChangedListener() } private fun setTextChangedListener() { addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable) { val singleLineNew = s.isNotEmpty() if (mySingleLine != singleLineNew) { mySingleLine = singleLineNew [email protected] = s.isNotEmpty() if (mySingleLine) { [email protected](s.length) } } } }) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { setTextChangedListener() } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { setTextChangedListener() } }
apache-2.0
1add0ad06a86d2838abfd2f3688bcc70
36.59322
132
0.672678
4.611227
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/debugger/remote/value/LuaRPrimitive.kt
2
2296
/* * 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.debugger.remote.value import com.intellij.xdebugger.frame.XValueNode import com.intellij.xdebugger.frame.XValuePlace import com.intellij.xdebugger.frame.presentation.XValuePresentation import com.tang.intellij.lua.debugger.LuaXNumberPresentation import com.tang.intellij.lua.debugger.LuaXStringPresentation import com.tang.intellij.lua.debugger.LuaXValuePresentation import com.tang.intellij.lua.highlighting.LuaHighlightingData import org.luaj.vm2.* /** * * Created by tangzx on 2017/4/16. */ class LuaRPrimitive(name: String) : LuaRValue(name) { private var type: String? = null private lateinit var data: String private var valuePresentation: XValuePresentation? = null override fun parse(data: LuaValue, desc: String) { this.data = data.toString() when (data) { is LuaString -> { type = "string" valuePresentation = LuaXStringPresentation(this.data) } is LuaNumber -> { type = "number" valuePresentation = LuaXNumberPresentation(this.data) } is LuaBoolean -> { type = "boolean" valuePresentation = LuaXValuePresentation(type!!, this.data, LuaHighlightingData.PRIMITIVE_TYPE) } is LuaFunction -> type = "function" } } override fun computePresentation(xValueNode: XValueNode, xValuePlace: XValuePlace) { if (valuePresentation == null) { xValueNode.setPresentation(null, type, data, false) } else { xValueNode.setPresentation(null, valuePresentation!!, false) } } }
apache-2.0
1fa252766081f1564874e73d2cd1b3be
35.444444
112
0.679878
4.365019
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/search/authors/SearchAuthorsFragment.kt
2
4019
package ru.fantlab.android.ui.modules.search.authors import android.content.Context import android.os.Bundle import android.view.View import androidx.annotation.StringRes import com.evernote.android.state.State import kotlinx.android.synthetic.main.micro_grid_refresh_list.* import kotlinx.android.synthetic.main.state_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.SearchAuthor import ru.fantlab.android.helper.InputHelper import ru.fantlab.android.provider.rest.loadmore.OnLoadMore import ru.fantlab.android.ui.adapter.SearchAuthorsAdapter import ru.fantlab.android.ui.base.BaseFragment import ru.fantlab.android.ui.modules.author.AuthorPagerActivity import ru.fantlab.android.ui.modules.search.SearchMvp class SearchAuthorsFragment : BaseFragment<SearchAuthorsMvp.View, SearchAuthorsPresenter>(), SearchAuthorsMvp.View { @State var searchQuery = "" private val onLoadMore: OnLoadMore<String> by lazy { OnLoadMore(presenter, searchQuery) } private val adapter: SearchAuthorsAdapter by lazy { SearchAuthorsAdapter(arrayListOf()) } private var countCallback: SearchMvp.View? = null override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { if (savedInstanceState == null) { stateLayout.hideProgress() } stateLayout.setEmptyText(R.string.no_search_results) getLoadMore().initialize(presenter.getCurrentPage() - 1, presenter.getPreviousTotal()) stateLayout.setOnReloadListener(this) refresh.setOnRefreshListener(this) recycler.setEmptyView(stateLayout, refresh) adapter.listener = presenter recycler.adapter = adapter recycler.addKeyLineDivider() recycler.addOnScrollListener(getLoadMore()) if (!InputHelper.isEmpty(searchQuery)) { onRefresh() } if (InputHelper.isEmpty(searchQuery)) { stateLayout.showEmptyState() } fastScroller.attachRecyclerView(recycler) } override fun onAttach(context: Context) { super.onAttach(context) if (context is SearchMvp.View) { countCallback = context } } override fun onDetach() { countCallback = null super.onDetach() } override fun onDestroyView() { recycler.removeOnScrollListener(getLoadMore()) super.onDestroyView() } override fun providePresenter(): SearchAuthorsPresenter = SearchAuthorsPresenter() override fun onNotifyAdapter(items: ArrayList<SearchAuthor>, page: Int) { hideProgress() if (items.isEmpty()) { adapter.clear() stateLayout.showEmptyState() return } if (page <= 1) { adapter.insertItems(items) } else { adapter.addItems(items) } } override fun onSetTabCount(count: Int) { countCallback?.onSetCount(count, 0) } override fun onSetSearchQuery(query: String) { this.searchQuery = query getLoadMore().reset() adapter.clear() if (!InputHelper.isEmpty(query)) { recycler.removeOnScrollListener(getLoadMore()) recycler.addOnScrollListener(getLoadMore()) onRefresh() } } override fun onQueueSearch(query: String) { onSetSearchQuery(query) } override fun getLoadMore(): OnLoadMore<String> { onLoadMore.parameter = searchQuery return onLoadMore } override fun onItemClicked(item: SearchAuthor) { AuthorPagerActivity.startActivity(context!!, item.authorId, item.rusName, 0) } override fun fragmentLayout(): Int = R.layout.micro_grid_refresh_list override fun onRefresh() { if (searchQuery.isEmpty()) { refresh.isRefreshing = false return } presenter.onCallApi(1, searchQuery) } override fun onClick(v: View?) { onRefresh() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.hideProgress() } override fun showProgress(@StringRes resId: Int, cancelable: Boolean) { refresh.isRefreshing = true stateLayout.showProgress() } override fun showErrorMessage(msgRes: String?) { callback?.showErrorMessage(msgRes) } override fun showMessage(titleRes: Int, msgRes: Int) { showReload() super.showMessage(titleRes, msgRes) } private fun showReload() { hideProgress() stateLayout.showReload(adapter.itemCount) } }
gpl-3.0
2d17e3de86990730b824fa51d90704cd
26.346939
92
0.763623
3.849617
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/logic/NetworkUtil.kt
1
4403
package at.ac.tuwien.caa.docscan.logic import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest import android.os.Build import android.os.Handler import android.os.Looper import androidx.annotation.RequiresPermission import at.ac.tuwien.caa.docscan.extensions.safeOffer import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.distinctUntilChanged class NetworkUtil @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) constructor( private val connectivityManager: ConnectivityManager ) { private val mainThreadHandler = Handler(Looper.getMainLooper()) private val unmeteredCapabilities = listOf( NetworkCapabilities.NET_CAPABILITY_INTERNET, NetworkCapabilities.NET_CAPABILITY_NOT_METERED ) private val connectedCapabilities = listOf( NetworkCapabilities.NET_CAPABILITY_INTERNET ) @Suppress("unused") fun getNetworkStatus(): NetworkStatus { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) ?.getNetworkStatus() ?: NetworkStatus.DISCONNECTED } else { @Suppress("DEPRECATION") if (connectivityManager.activeNetworkInfo?.isConnected == true) { if (connectivityManager.isActiveNetworkMetered) { NetworkStatus.CONNECTED_METERED } else { NetworkStatus.CONNECTED_UNMETERED } } else { NetworkStatus.DISCONNECTED } } } /** * @return a flow which emits the network status as described in the states in [NetworkStatus]. */ fun watchNetworkAvailability() = callbackFlow { val callback = object : ConnectivityManager.NetworkCallback() { override fun onLost(network: Network) { super.onLost(network) offerStatus(NetworkStatus.DISCONNECTED) } override fun onUnavailable() { super.onUnavailable() offerStatus(NetworkStatus.DISCONNECTED) } override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { super.onCapabilitiesChanged(network, networkCapabilities) offerStatus(networkCapabilities.getNetworkStatus()) } private fun offerStatus(networkStatus: NetworkStatus) { mainThreadHandler.post { safeOffer(networkStatus) } } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { connectivityManager.registerDefaultNetworkCallback(callback) } else { val builder = NetworkRequest.Builder() connectedCapabilities.forEach { builder.addCapability(it) } connectivityManager.registerNetworkCallback(builder.build(), callback) } awaitClose { connectivityManager.unregisterNetworkCallback(callback) } }.distinctUntilChanged() private fun NetworkCapabilities.getNetworkStatus(): NetworkStatus { return when { hasCapabilities(unmeteredCapabilities) -> { NetworkStatus.CONNECTED_UNMETERED } hasCapabilities(connectedCapabilities) -> { NetworkStatus.CONNECTED_METERED } else -> NetworkStatus.DISCONNECTED } } } private fun NetworkCapabilities.hasCapabilities(capabilities: List<Int>): Boolean { capabilities.forEach { if (!hasCapability(it)) { return false } } return true } /** * The network status represents for most android versions the default network which is currently used, * it doesn't matter which transport type it is, it rather uses metered/unmetered flags to determine * if the network may cause charges for the user. */ enum class NetworkStatus { CONNECTED_UNMETERED, CONNECTED_METERED, DISCONNECTED }
lgpl-3.0
0507e147cf88b6244fc4c795bb2a460e
33.398438
103
0.631842
5.718182
false
false
false
false
world-federation-of-advertisers/panel-exchange-client
src/main/kotlin/org/wfanet/panelmatch/client/tools/ParseDecryptedEventData.kt
1
3993
// 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.panelmatch.client.tools import com.google.protobuf.Message import com.google.protobuf.Parser import java.io.BufferedInputStream import java.io.File import java.io.PrintWriter import kotlin.properties.Delegates import org.wfanet.measurement.common.commandLineMain import org.wfanet.measurement.common.toJson import org.wfanet.panelmatch.client.eventpreprocessing.CombinedEvents import org.wfanet.panelmatch.client.privatemembership.KeyedDecryptedEventDataSet import org.wfanet.panelmatch.client.privatemembership.isPaddingQuery import org.wfanet.panelmatch.client.tools.DataProviderEventSetKt.entry import org.wfanet.panelmatch.common.ShardedFileName import picocli.CommandLine.Command import picocli.CommandLine.Option import wfa_virtual_people.Event.DataProviderEvent private const val BUFFER_SIZE_BYTES = 32 * 1024 * 1024 // 32MiB @Command( name = "parse-decrypted-event-data", description = ["Parses the decrypted event data produced by an exchange."] ) class ParseDecryptedEventData : Runnable { @Option( names = ["--manifest-path"], description = ["Path to the manifest file of the decrypted event data set."], required = true, ) private lateinit var manifestFile: File @Option( names = ["--output-path"], description = ["Path to output the parsed JSON result."], required = true, ) private lateinit var outputFile: File @set:Option( names = ["--max-shards-to-parse"], description = ["If specified, up to this many shards will be parsed."], required = false, defaultValue = "-1", ) private var maxShardsToParse by Delegates.notNull<Int>() override fun run() { val fileSpec = manifestFile.readText().trim() val shardedFileName = ShardedFileName(fileSpec) val parsedShards = shardedFileName.parseAllShards(KeyedDecryptedEventDataSet.parser()) PrintWriter(outputFile.outputStream()).use { printWriter -> for (keyedDecryptedEventDataSet in parsedShards) { if (!keyedDecryptedEventDataSet.hasPaddingNonce()) { printWriter.println(keyedDecryptedEventDataSet.toDataProviderEventSetEntry().toJson()) } } } } private fun KeyedDecryptedEventDataSet.toDataProviderEventSetEntry(): DataProviderEventSet.Entry { return entry { joinKeyAndId = plaintextJoinKeyAndId events += decryptedEventDataList.flatMap { plaintext -> val combinedEvents = CombinedEvents.parseFrom(plaintext.payload) combinedEvents.serializedEventsList.map { DataProviderEvent.parseFrom(it) } } } } private fun <T : Message> ShardedFileName.parseAllShards(parser: Parser<T>): Sequence<T> { return sequence { fileNames.forEachIndexed { shardNum, fileName -> if (maxShardsToParse in 0..shardNum) { return@sequence } val shardFile = manifestFile.parentFile.resolve(fileName) BufferedInputStream(shardFile.inputStream(), BUFFER_SIZE_BYTES).use { inputStream -> while (true) { val message: T = parser.parseDelimitedFrom(inputStream) ?: break yield(message) } } } } } private fun KeyedDecryptedEventDataSet.hasPaddingNonce(): Boolean { return plaintextJoinKeyAndId.joinKeyIdentifier.isPaddingQuery } } fun main(args: Array<String>) = commandLineMain(ParseDecryptedEventData(), args)
apache-2.0
3588cd9098b6b4df4fa7a5eef93aea85
34.651786
100
0.732281
4.378289
false
false
false
false
daniloqueiroz/nsync
src/main/kotlin/extensions/Byte.kt
1
526
package extensions // extensions to print Byte/ByteArray as Hex private val CHARS = arrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f') internal fun Byte.toHexString(): String { val i = this.toInt() val char2 = CHARS[i and 0x0f] val char1 = CHARS[i shr 4 and 0x0f] return "$char1$char2" } internal fun ByteArray.toHexString(): String { val builder = StringBuilder() for (b in this) { builder.append(b.toHexString()) } return builder.toString() }
gpl-3.0
87eca5e63c1fdc3caf4cfb56d1122337
25.3
107
0.595057
3.076023
false
false
false
false
ligee/kotlin-jupyter
jupyter-lib/api/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/annotationsHandling.kt
1
856
package org.jetbrains.kotlinx.jupyter.api import kotlin.reflect.KClass /** * Callback to handle new class or interface declarations in executed snippets */ typealias ClassDeclarationsCallback = KotlinKernelHost.(List<KClass<*>>) -> Unit /** * Annotation handler used to hook class declarations with specific annotations */ class ClassAnnotationHandler(val annotation: KClass<out Annotation>, val callback: ClassDeclarationsCallback) typealias ExecutionCallback<T> = KotlinKernelHost.() -> T typealias AfterCellExecutionCallback = KotlinKernelHost.(snippetInstance: Any, result: FieldValue) -> Unit typealias InterruptionCallback = KotlinKernelHost.() -> Unit typealias FileAnnotationCallback = KotlinKernelHost.(List<Annotation>) -> Unit class FileAnnotationHandler(val annotation: KClass<out Annotation>, val callback: FileAnnotationCallback)
apache-2.0
dcf813065334e0312c791d27e6ea83ae
36.217391
109
0.806075
5.095238
false
false
false
false
jiaminglu/kotlin-native
shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/ClangArgs.kt
1
5197
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed -> 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.konan.target import org.jetbrains.kotlin.konan.properties.KonanProperties import org.jetbrains.kotlin.konan.file.File class ClangTarget(val target: KonanTarget, konanProperties: KonanProperties) { val sysRoot = konanProperties.absoluteTargetSysRoot val targetArg = konanProperties.targetArg val specificClangArgs: List<String> get() { val result = when (target) { KonanTarget.LINUX -> listOf("--sysroot=$sysRoot", "-DUSE_GCC_UNWIND=1", "-DUSE_ELF_SYMBOLS=1", "-DELFSIZE=64") KonanTarget.RASPBERRYPI -> listOf("-target", targetArg!!, "-mfpu=vfp", "-mfloat-abi=hard", "-DUSE_GCC_UNWIND=1", "-DUSE_ELF_SYMBOLS=1", "-DELFSIZE=32", "--sysroot=$sysRoot", // TODO: those two are hacks. "-I$sysRoot/usr/include/c++/4.8.3", "-I$sysRoot/usr/include/c++/4.8.3/arm-linux-gnueabihf") KonanTarget.MINGW -> listOf("-target", targetArg!!, "--sysroot=$sysRoot", "-DUSE_GCC_UNWIND=1", "-DUSE_PE_COFF_SYMBOLS=1", "-DKONAN_WINDOWS=1") KonanTarget.MACBOOK -> listOf("--sysroot=$sysRoot", "-mmacosx-version-min=10.11", "-DKONAN_OSX=1", "-DKONAN_OBJC_INTEROP=1") KonanTarget.IPHONE -> listOf("-stdlib=libc++", "-arch", "arm64", "-isysroot", sysRoot, "-miphoneos-version-min=8.0.0", "-DKONAN_OBJC_INTEROP=1") KonanTarget.IPHONE_SIM -> listOf("-stdlib=libc++", "-isysroot", sysRoot, "-miphoneos-version-min=8.0.0", "-DKONAN_OBJC_INTEROP=1") KonanTarget.ANDROID_ARM32 -> listOf("-target", targetArg!!, "--sysroot=$sysRoot", "-D__ANDROID__", "-DUSE_GCC_UNWIND=1", "-DUSE_ELF_SYMBOLS=1", "-DELFSIZE=32", "-DKONAN_ANDROID", // HACKS! "-I$sysRoot/usr/include/c++/4.9.x", "-I$sysRoot/usr/include/c++/4.9.x/arm-linux-androideabi") KonanTarget.ANDROID_ARM64 -> listOf("-target", targetArg!!, "--sysroot=$sysRoot", "-D__ANDROID__", "-DUSE_GCC_UNWIND=1", "-DUSE_ELF_SYMBOLS=1", "-DELFSIZE=64", "-DKONAN_ANDROID", // HACKS! "-I$sysRoot/usr/include/c++/4.9.x", "-I$sysRoot/usr/include/c++/4.9.x/aarch64-linux-android") KonanTarget.WASM32 -> listOf("-target", targetArg!!, "-O1", "-fno-rtti", "-fno-exceptions", "-DKONAN_WASM=1", "-D_LIBCPP_ABI_VERSION=2", "-D_LIBCPP_NO_EXCEPTIONS=1", "-DKONAN_NO_FFI=1", "-DKONAN_NO_THREADS=1", "-DKONAN_NO_EXCEPTIONS=1", "-DKONAN_INTERNAL_DLMALLOC=1", "-DKONAN_INTERNAL_SNPRINTF=1", "-DKONAN_INTERNAL_NOW=1", "-nostdinc", "-Xclang", "-nobuiltininc", "-Xclang", "-nostdsysteminc", "-Xclang", "-isystem$sysRoot/include/libcxx", "-Xclang", "-isystem$sysRoot/lib/libcxxabi/include", "-Xclang", "-isystem$sysRoot/include/compat", "-Xclang", "-isystem$sysRoot/include/libc") } return result + (if (target != KonanTarget.WASM32) listOf("-g") else emptyList()) } } class ClangHost(val hostProperties: KonanProperties) { val targetToolchain get() = hostProperties.absoluteTargetToolchain val gccToolchain get() = hostProperties.absoluteGccToolchain val sysRoot get() = hostProperties.absoluteTargetSysRoot val llvmDir get() = hostProperties.absoluteLlvmHome val binDir = when(TargetManager.host) { KonanTarget.LINUX -> "$targetToolchain/bin" KonanTarget.MINGW -> "$sysRoot/bin" KonanTarget.MACBOOK -> "$sysRoot/usr/bin" else -> throw TargetSupportException("Unexpected host platform") } private val extraHostClangArgs = if (TargetManager.host == KonanTarget.LINUX) { listOf("--gcc-toolchain=$gccToolchain") } else { emptyList() } val commonClangArgs = listOf("-B$binDir") + extraHostClangArgs val hostClangPath = listOf("$llvmDir/bin", binDir) private val jdkHome = File.jdkHome.absoluteFile.parent val hostCompilerArgsForJni = listOf("", TargetManager.jniHostPlatformIncludeDir).map { "-I$jdkHome/include/$it" } }
apache-2.0
5c9cef7793cd46133282e1c2cfbe62ba
44.587719
150
0.576102
3.895802
false
false
false
false
walleth/walleth
app/src/main/java/org/walleth/data/tokens/TokenDAO.kt
1
934
package org.walleth.data.tokens import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import org.kethereum.model.Address @Dao interface TokenDAO { @Query("SELECT * FROM tokens ORDER BY \"order\" DESC ,\"chain\",\"symbol\"") suspend fun all(): List<Token> @Query("UPDATE tokens SET softDeleted=0") suspend fun unDeleteAll() @Query("DELETE FROM addressbook where deleted = 1") suspend fun deleteAllSoftDeleted() @Query("SELECT * FROM tokens WHERE address = :address COLLATE NOCASE") suspend fun forAddress(address: Address): Token? @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsert(entry: Token) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsert(entries: List<Token>) @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun addIfNotPresent(entries: List<Token>) }
gpl-3.0
9afd7d3f5db23252f47e597a38d4a313
26.5
80
0.734475
4.364486
false
false
false
false
k-kagurazaka/rx-property-android
sample/src/main/kotlin/jp/keita/kagurazaka/rxproperty/sample/todo/TodoItem.kt
1
366
package jp.keita.kagurazaka.rxproperty.sample.todo import java.util.* class TodoItem(var isDone: Boolean, var title: String) { val id: String = UUID.randomUUID().toString().toUpperCase() override fun equals(other: Any?) = when (other) { is TodoItem -> id == other.id else -> false } override fun hashCode() = 31 * id.hashCode() }
mit
0719d8638dbd4b8db55595284044256d
25.142857
63
0.650273
3.893617
false
false
false
false
jdiazcano/modulartd
editor/core/src/main/kotlin/com/jdiazcano/modulartd/ui/widgets/lists/LayerList.kt
1
1944
package com.jdiazcano.modulartd.ui.widgets.lists import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.jdiazcano.modulartd.beans.Layer import com.jdiazcano.modulartd.bus.Bus import com.jdiazcano.modulartd.bus.BusTopic import com.jdiazcano.modulartd.ui.widgets.LayerView import com.jdiazcano.modulartd.ui.widgets.TableList import com.kotcrab.vis.ui.widget.VisCheckBox import mu.KLogging class LayerList(items: MutableList<Layer>) : TableList<Layer, LayerView>(items) { companion object: KLogging() init { Bus.register<Layer>(BusTopic.CREATED) { addItem(it) logger.debug { "Added layer: ${it.name}" } } Bus.register<kotlin.Unit>(BusTopic.RESET) { clearList() logger.debug { "Cleared list of: Layer" } } Bus.register<Layer>(BusTopic.LOAD_FINISHED) { invalidateList() } } override fun getView(position: Int, lastView: LayerView?): LayerView { var lastView = lastView val layer = getItem(position) if (lastView == null) { lastView = LayerView(layer) lastView.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { // TODO I don't remember what's this lol InfiniteEditor.stage.setKeyboardFocus(this@LayerList) if (event!!.target.parent !is VisCheckBox) { var a = event.target while (a.parent !is TableList<*, *>) { a = a.parent } selectView(a as LayerView) } } }) } lastView.layer = layer lastView.name.setText(layer.name) lastView.check.isChecked = layer.visible return lastView } }
apache-2.0
50da1d0940896e13a2ca3b5500132f54
31.966102
114
0.593621
4.32
false
false
false
false
exponentjs/exponent
packages/expo-updates/android/src/androidTest/java/expo/modules/updates/manifest/UpdateManifestFactoryTest.kt
2
2886
package expo.modules.updates.manifest import android.net.Uri import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner import expo.modules.updates.UpdatesConfiguration import expo.modules.updates.manifest.ManifestFactory.getEmbeddedManifest import expo.modules.updates.manifest.ManifestFactory.getManifest import org.json.JSONException import org.json.JSONObject import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import java.util.* @RunWith(AndroidJUnit4ClassRunner::class) class UpdateManifestFactoryTest { private val legacyManifestJson = "{\"sdkVersion\":\"39.0.0\",\"id\":\"@esamelson/native-component-list\",\"releaseId\":\"0eef8214-4833-4089-9dff-b4138a14f196\",\"commitTime\":\"2020-11-11T00:17:54.797Z\",\"bundleUrl\":\"https://classic-assets.eascdn.net/%40esamelson%2Fnative-component-list%2F39.0.0%2F01c86fd863cfee878068eebd40f165df-39.0.0-ios.js\"}" private val newManifestJson = "{\"runtimeVersion\":\"1\",\"id\":\"0eef8214-4833-4089-9dff-b4138a14f196\",\"createdAt\":\"2020-11-11T00:17:54.797Z\",\"launchAsset\":{\"url\":\"https://classic-assets.eascdn.net/%40esamelson%2Fnative-component-list%2F39.0.0%2F01c86fd863cfee878068eebd40f165df-39.0.0-ios.js\",\"contentType\":\"application/javascript\"}}" private val bareManifestJson = "{\"id\":\"0eef8214-4833-4089-9dff-b4138a14f196\",\"commitTime\":1609975977832}" private fun createConfig(): UpdatesConfiguration { val configMap = mapOf("updateUrl" to Uri.parse("https://exp.host/@esamelson/native-component-list")) return UpdatesConfiguration(null, configMap) } @Test @Throws(Exception::class) fun testGetManifest_Legacy() { val actual = getManifest( JSONObject(legacyManifestJson), ManifestHeaderData(), null, createConfig() ) Assert.assertTrue(actual is LegacyUpdateManifest) } @Test @Throws(Exception::class) fun testGetManifest_New() { val actual = getManifest( JSONObject(newManifestJson), ManifestHeaderData(protocolVersion = "0"), null, createConfig() ) Assert.assertTrue(actual is NewUpdateManifest) } @Test(expected = Exception::class) @Throws(Exception::class) fun testGetManifest_UnsupportedProtocolVersion() { getManifest( JSONObject(newManifestJson), ManifestHeaderData(protocolVersion = "1"), null, createConfig() ) } @Test @Throws(JSONException::class) fun testGetEmbeddedManifest_Legacy() { val actual = getEmbeddedManifest( JSONObject(legacyManifestJson), createConfig() ) Assert.assertTrue(actual is LegacyUpdateManifest) } @Test @Throws(JSONException::class) fun testGetEmbeddedManifest_Legacy_Bare() { val actual = getEmbeddedManifest( JSONObject(bareManifestJson), createConfig() ) Assert.assertTrue(actual is BareUpdateManifest) } }
bsd-3-clause
f529c4207579937c797dd3bcce48859b
33.771084
325
0.72973
3.709512
false
true
false
false
exponentjs/exponent
packages/expo-dev-client/android/src/androidTest/java/com/expo/modules/devclient/selectors/Views.kt
2
939
package com.expo.modules.devclient.selectors internal object DevLauncherErrorScreenViews { val main = TaggedView("DevLauncherErrorScreen") val goToLauncher = TaggedView("DevLauncherErrorScreenGoToLauncher") val goToDetails = TaggedView("DevLauncherErrorScreenGoToDetails") val reload = TaggedView("DevLauncherErrorScreenReload") val details = TaggedView("DevLauncherErrorScreenDetails") } internal object DevLauncherViews { val main = TaggedView("DevLauncherMainScreen") val urlInput = TaggedView("DevLauncherURLInput") val loadAppButton = TaggedView("DevLauncherLoadAppButton") val ErrorScreen = DevLauncherErrorScreenViews } internal object DevMenuViews { val main = TaggedView("DevMenuMainScreen") } internal object BundledAppViews { val main = TaggedView("BundledAppMainScreen") } internal object Views { val DevLauncher = DevLauncherViews val DevMenu = DevMenuViews val BundledApp = BundledAppViews }
bsd-3-clause
8971faba3afdc3fbca00f29e25a0ca0d
30.3
69
0.804047
4.536232
false
false
false
false
Zackratos/PureMusic
app/src/main/kotlin/org/zack/music/update/UpdateDialog.kt
1
3345
package org.zack.music.update import android.app.Dialog import android.graphics.Color import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v7.app.AlertDialog import android.widget.TextView import android.app.DownloadManager import android.content.Context import android.net.Uri import android.os.Environment import org.zack.music.R import org.zack.music.tools.AppUtils import java.io.File /** * @author : Zhangwenchao * @e-mail : [email protected] * @time : 2018/5/31 */ class UpdateDialog: DialogFragment() { companion object { private const val CHECK = "check" fun newInstance(check: Update.Check): UpdateDialog { val dialog = UpdateDialog() val arg = Bundle() arg.putParcelable(CHECK, check) dialog.arguments = arg return dialog } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val check: Update.Check = arguments.getParcelable(CHECK) val dialog = AlertDialog.Builder(activity) .setIcon(R.drawable.ic_music) .setTitle(String.format(getString(R.string.update_title), check.version)) .setMessage(check.updateContent) .setCancelable(false) .setPositiveButton(R.string.update_update) { _, _ -> downloadNewVersion(check.url, check.fileName) } .setNegativeButton(R.string.update_refuse, null) .create() dialog.setCanceledOnTouchOutside(false) val window = dialog.window window.setBackgroundDrawableResource(R.drawable.bg_setup_card) dialog.setOnShowListener { val titleView = window.findViewById(R.id.alertTitle) as TextView titleView.setTextColor(Color.WHITE) val messageView = window.findViewById(android.R.id.message) as TextView messageView.setTextColor(Color.WHITE) } return dialog } private fun downloadNewVersion(url: String, name: String) { val file = File(activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), name) if (file.exists() && file.isFile) { AppUtils.installApk(activity, file) return } val folder = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) if (folder != null) { deleteFile(folder) } val downloadManager = activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager val request = DownloadManager.Request(Uri.parse(url)) .setMimeType("application/vnd.android.package-archive") .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) .setDestinationInExternalFilesDir(activity, Environment.DIRECTORY_DOWNLOADS, name) val id = downloadManager.enqueue(request) } private fun deleteFile(file: File) { if (!file.exists()) return if (file.isDirectory) { file.listFiles().forEach { f -> deleteFile(f) } // file.delete()//如要保留文件夹,只删除文件,请注释这行 } else if (file.exists()) { file.delete() } } }
apache-2.0
c3dd8d9f9c225f157da2e9501751a4c2
35.179775
116
0.635924
4.52394
false
false
false
false
Heiner1/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSettingBasalProfileAll.kt
1
2361
package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.shared.logging.LTag import java.util.* /** * Created by mike on 05.07.2016. * * * * * THIS IS BROKEN IN PUMP... SENDING ONLY 1 PROFILE */ class MsgSettingBasalProfileAll( injector: HasAndroidInjector ) : MessageBase(injector) { override fun handleMessage(bytes: ByteArray) { danaPump.pumpProfiles = Array(4) { Array(48) { 0.0 } } if (danaPump.basal48Enable) { for (profile in 0..3) { val position = intFromBuff(bytes, 107 * profile, 1) for (index in 0..47) { var basal = intFromBuff(bytes, 107 * profile + 2 * index + 1, 2) if (basal < 10) basal = 0 danaPump.pumpProfiles!![position][index] = basal / 100.0 } } } else { for (profile in 0..3) { val position = intFromBuff(bytes, 49 * profile, 1) for (index in 0..23) { var basal = intFromBuff(bytes, 59 * profile + 2 * index + 1, 2) if (basal < 10) basal = 0 aapsLogger.debug(LTag.PUMPCOMM, "position $position index $index") danaPump.pumpProfiles!![position][index] = basal / 100.0 } } } if (danaPump.basal48Enable) { for (profile in 0..3) { for (index in 0..47) { aapsLogger.debug(LTag.PUMPCOMM, "Basal profile " + profile + ": " + String.format(Locale.ENGLISH, "%02d", index) + "h: " + danaPump.pumpProfiles!![profile][index]) } } } else { for (profile in 0..3) { for (index in 0..23) { //this is absurd danaRPump.pumpProfiles[profile][index] returns nullPointerException aapsLogger.debug( LTag.PUMPCOMM, "Basal profile " + profile + ": " + String.format(Locale.ENGLISH, "%02d", index / 2) + ":" + String.format(Locale.ENGLISH, "%02d", index % 2 * 30) + " : " + danaPump.pumpProfiles!![profile][index]) } } } } init { setCommand(0x3206) aapsLogger.debug(LTag.PUMPCOMM, "New message") } }
agpl-3.0
b8f3964fd42169b77737c136aa810942
36.492063
183
0.513342
4.201068
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/util.kt
3
3280
// 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.gradleTooling.arguments import org.gradle.api.Task import org.gradle.api.logging.Logger import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder import org.jetbrains.kotlin.idea.gradleTooling.getDeclaredMethodOrNull import org.jetbrains.kotlin.idea.gradleTooling.getMethodOrNull import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheMapper import java.io.File import java.lang.reflect.Method private fun buildDependencyClasspath(compileKotlinTask: Task): List<String> { val abstractKotlinCompileClass = compileKotlinTask.javaClass.classLoader.loadClass(AbstractKotlinGradleModelBuilder.ABSTRACT_KOTLIN_COMPILE_CLASS) val getCompileClasspath = abstractKotlinCompileClass.getDeclaredMethodOrNull("getCompileClasspath") ?: abstractKotlinCompileClass.getDeclaredMethodOrNull( "getClasspath" ) ?: return emptyList() @Suppress("UNCHECKED_CAST") return (getCompileClasspath(compileKotlinTask) as? Collection<File>)?.map { it.path } ?: emptyList() } fun buildCachedArgsInfo( compileKotlinTask: Task, cacheMapper: CompilerArgumentsCacheMapper, ): CachedExtractedArgsInfo { val cachedCurrentArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileKotlinTask, cacheMapper, defaultsOnly = false) val cachedDefaultArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileKotlinTask, cacheMapper, defaultsOnly = true) val dependencyClasspath = buildDependencyClasspath(compileKotlinTask).map { KotlinCachedRegularCompilerArgument(cacheMapper.cacheArgument(it)) } return CachedExtractedArgsInfo(cacheMapper.cacheOriginIdentifier, cachedCurrentArguments, cachedDefaultArguments, dependencyClasspath) } fun buildSerializedArgsInfo( compileKotlinTask: Task, cacheMapper: CompilerArgumentsCacheMapper, logger: Logger ): CachedSerializedArgsInfo { val compileTaskClass = compileKotlinTask.javaClass val getCurrentArguments = compileTaskClass.getMethodOrNull("getSerializedCompilerArguments") val getDefaultArguments = compileTaskClass.getMethodOrNull("getDefaultSerializedCompilerArguments") val currentArguments = safelyGetArguments(compileKotlinTask, getCurrentArguments, logger) .map { KotlinCachedRegularCompilerArgument(cacheMapper.cacheArgument(it)) } val defaultArguments = safelyGetArguments(compileKotlinTask, getDefaultArguments, logger) .map { KotlinCachedRegularCompilerArgument(cacheMapper.cacheArgument(it)) } val dependencyClasspath = buildDependencyClasspath(compileKotlinTask) .map { KotlinCachedRegularCompilerArgument(cacheMapper.cacheArgument(it)) } return CachedSerializedArgsInfo(cacheMapper.cacheOriginIdentifier, currentArguments, defaultArguments, dependencyClasspath) } @Suppress("UNCHECKED_CAST") private fun safelyGetArguments(compileKotlinTask: Task, accessor: Method?, logger: Logger) = try { accessor?.invoke(compileKotlinTask) as? List<String> } catch (e: Exception) { logger.warn(e.message ?: "Unexpected exception: $e", e) null } ?: emptyList()
apache-2.0
15b5e9b61169f0335c014dc1a7f60f2f
54.59322
158
0.810366
5.34202
false
false
false
false
zachdeibert/operation-manipulation
operation-missing-android/app/src/main/java/com/zachdeibert/operationmissing/ui/Color.kt
1
655
package com.zachdeibert.operationmissing.ui import android.content.Context import android.graphics.Color import android.support.v4.content.res.ResourcesCompat class Color { var R: Float var G: Float var B: Float var A: Float constructor(r: Float, g: Float, b: Float, a: Float = 1f) { R = r G = g B = b A = a } constructor(context: Context, id: Int) { val color = ResourcesCompat.getColor(context.resources, id, context.theme) R = Color.red(color) / 256f G = Color.green(color) / 256f B = Color.blue(color) / 256f A = Color.alpha(color) / 256f } }
mit
86054e7162ddf9590d5126ec2c03fe5e
23.259259
82
0.607634
3.429319
false
false
false
false
ligi/PassAndroid
android/src/main/java/org/ligi/passandroid/functions/Barcode.kt
1
2074
package org.ligi.passandroid.functions import android.content.res.Resources import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import com.google.zxing.MultiFormatWriter import org.ligi.passandroid.model.pass.PassBarCodeFormat import timber.log.Timber fun generateBitmapDrawable(resources: Resources, data: String, type: PassBarCodeFormat): BitmapDrawable? { val bitmap = generateBarCodeBitmap(data, type) ?: return null return BitmapDrawable(resources, bitmap).apply { isFilterBitmap = false setAntiAlias(false) } } fun generateBarCodeBitmap(data: String, type: PassBarCodeFormat): Bitmap? { if (data.isEmpty()) { return null } try { val matrix = getBitMatrix(data, type) val is1D = matrix.height == 1 // generate an image from the byte matrix val width = matrix.width val height = if (is1D) width / 5 else matrix.height // create buffered image to draw to // NTFS Bitmap.Config.ALPHA_8 sounds like an awesome idea - been there - done that .. val barcodeImage = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565) // iterate through the matrix and draw the pixels to the image for (y in 0 until height) { for (x in 0 until width) { barcodeImage.setPixel(x, y, if (matrix.get(x, if (is1D) 0 else y)) 0 else 0xFFFFFF) } } return barcodeImage } catch (e: com.google.zxing.WriterException) { Timber.w(e, "could not write image") // TODO check if we should better return some rescue Image here return null } catch (e: IllegalArgumentException) { Timber.w("could not write image: $e") return null } catch (e: ArrayIndexOutOfBoundsException) { // happens for ITF barcode on certain inputs Timber.w("could not write image: $e") return null } } fun getBitMatrix(data: String, type: PassBarCodeFormat) = MultiFormatWriter().encode(data, type.zxingBarCodeFormat(), 0, 0)!!
gpl-3.0
f82943277b314723cf2c7ecfb5cd0525
32.451613
125
0.666827
4.198381
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/mediapicker/VideoThumbnailViewHolder.kt
1
2219
package org.wordpress.android.ui.mediapicker import android.view.ViewGroup import android.widget.ImageView import android.widget.ImageView.ScaleType.FIT_CENTER import android.widget.TextView import kotlinx.coroutines.CoroutineScope import org.wordpress.android.R import org.wordpress.android.R.id import org.wordpress.android.util.image.ImageManager /* * ViewHolder containing a device thumbnail */ class VideoThumbnailViewHolder( parent: ViewGroup, private val mediaThumbnailViewUtils: MediaThumbnailViewUtils, private val imageManager: ImageManager, private val coroutineScope: CoroutineScope ) : ThumbnailViewHolder( parent, R.layout.media_picker_thumbnail_item ) { private val imgThumbnail: ImageView = itemView.findViewById(id.image_thumbnail) private val txtSelectionCount: TextView = itemView.findViewById(id.text_selection_count) private val videoOverlay: ImageView = itemView.findViewById(id.image_video_overlay) fun bind(item: MediaPickerUiItem.VideoItem, animateSelection: Boolean, updateCount: Boolean) { val isSelected = item.isSelected mediaThumbnailViewUtils.setupTextSelectionCount( txtSelectionCount, isSelected, item.selectedOrder, item.showOrderCounter, animateSelection ) // Only count is updated so do not redraw the whole item if (updateCount) { return } imageManager.cancelRequestAndClearImageView(imgThumbnail) imageManager.loadThumbnailFromVideoUrl( coroutineScope, imgThumbnail, item.url, FIT_CENTER ) imgThumbnail.apply { contentDescription = resources.getString(R.string.photo_picker_video_thumbnail_content_description) } mediaThumbnailViewUtils.setupListeners( imgThumbnail, true, item.isSelected, item.toggleAction, item.clickAction, animateSelection ) mediaThumbnailViewUtils.setupVideoOverlay(videoOverlay, item.clickAction) } }
gpl-2.0
3b0836332b4ff8a7cb72cd84dc9d6f3c
35.377049
111
0.671023
5.148492
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/ui/fragments/qms/QmsBlackListFragment.kt
1
5554
package forpdateam.ru.forpda.ui.fragments.qms import android.os.Bundle import androidx.appcompat.widget.AppCompatAutoCompleteTextView import androidx.recyclerview.widget.LinearLayoutManager import android.view.* import android.widget.ArrayAdapter import moxy.presenter.InjectPresenter import moxy.presenter.ProvidePresenter import forpdateam.ru.forpda.App import forpdateam.ru.forpda.R import forpdateam.ru.forpda.common.simple.SimpleTextWatcher import forpdateam.ru.forpda.entity.remote.others.user.ForumUser import forpdateam.ru.forpda.entity.remote.qms.QmsContact import forpdateam.ru.forpda.presentation.qms.blacklist.QmsBlackListPresenter import forpdateam.ru.forpda.presentation.qms.blacklist.QmsBlackListView import forpdateam.ru.forpda.ui.fragments.RecyclerFragment import forpdateam.ru.forpda.ui.fragments.qms.adapters.QmsContactsAdapter import forpdateam.ru.forpda.ui.views.ContentController import forpdateam.ru.forpda.ui.views.DynamicDialogMenu import forpdateam.ru.forpda.ui.views.FunnyContent import forpdateam.ru.forpda.ui.views.adapters.BaseAdapter /** * Created by radiationx on 22.03.17. */ class QmsBlackListFragment : RecyclerFragment(), BaseAdapter.OnItemClickListener<QmsContact>, QmsBlackListView { private lateinit var nickField: AppCompatAutoCompleteTextView private lateinit var adapter: QmsContactsAdapter private val dialogMenu = DynamicDialogMenu<QmsBlackListFragment, QmsContact>() @InjectPresenter lateinit var presenter: QmsBlackListPresenter @ProvidePresenter fun providePresenter(): QmsBlackListPresenter = QmsBlackListPresenter( App.get().Di().qmsInteractor, App.get().Di().router, App.get().Di().linkHandler, App.get().Di().errorHandler ) init { configuration.defaultTitle = App.get().getString(R.string.fragment_title_blacklist) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) val viewStub = findViewById(R.id.toolbar_content) as ViewStub viewStub.layoutResource = R.layout.toolbar_qms_black_list viewStub.inflate() nickField = findViewById(R.id.qms_black_list_nick_field) as AppCompatAutoCompleteTextView return viewFragment } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setScrollFlagsEnterAlways() nickField.addTextChangedListener(object : SimpleTextWatcher() { override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { presenter.searchUser(s.toString()) } }) refreshLayout.setOnRefreshListener { presenter.loadContacts() } recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) dialogMenu.apply { addItem(getString(R.string.profile)) { _, data -> presenter.openProfile(data) } addItem(getString(R.string.dialogs)) { _, data -> presenter.openDialogs(data) } addItem(getString(R.string.delete)) { _, data -> presenter.unBlockUser(data.id) } } adapter = QmsContactsAdapter() recyclerView.adapter = adapter adapter.setOnItemClickListener(this) } override fun addBaseToolbarMenu(menu: Menu) { super.addBaseToolbarMenu(menu) menu.add(R.string.add) .setIcon(App.getVecDrawable(context, R.drawable.ic_toolbar_add)) .setOnMenuItemClickListener { var nick = "" if (nickField.text != null) nick = nickField.text.toString() presenter.blockUser(nick) false } .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS) } override fun showContacts(items: List<QmsContact>) { setRefreshing(false) if (items.isEmpty()) { if (!contentController.contains(ContentController.TAG_NO_DATA)) { val funnyContent = FunnyContent(context) .setImage(R.drawable.ic_contacts) .setTitle(R.string.funny_blacklist_nodata_title) .setDesc(R.string.funny_blacklist_nodata_desc) contentController.addContent(funnyContent, ContentController.TAG_NO_DATA) } contentController.showContent(ContentController.TAG_NO_DATA) } else { contentController.hideContent(ContentController.TAG_NO_DATA) } recyclerView.scrollToPosition(0) adapter.addAll(items) } override fun clearNickField() { nickField.setText("") } override fun showFoundUsers(items: List<ForumUser>) { val nicks = items.map { it.nick.orEmpty() } nickField.setAdapter(ArrayAdapter(context!!, android.R.layout.simple_dropdown_item_1line, nicks)) } override fun showItemDialogMenu(item: QmsContact) { dialogMenu.apply { disallowAll() allowAll() show(context, this@QmsBlackListFragment, item) } } override fun onItemClick(item: QmsContact) { presenter.onItemLongClick(item) } override fun onItemLongClick(item: QmsContact): Boolean { presenter.onItemLongClick(item) return false } }
gpl-3.0
9b5c604b2ddef79ca308702284e01a34
37.569444
116
0.675909
4.70678
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/ManagementNewsCardUseCase.kt
1
3207
package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.R import org.wordpress.android.analytics.AnalyticsTracker.Stat import org.wordpress.android.fluxc.store.StatsStore.ManagementType import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.StatelessUseCase import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.BigTitle import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.DialogButtons import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ImageItem import org.wordpress.android.ui.utils.ListItemInteraction import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Tag import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Text import org.wordpress.android.ui.stats.refresh.utils.NewsCardHandler import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import org.wordpress.android.viewmodel.ResourceProvider import javax.inject.Inject import javax.inject.Named class ManagementNewsCardUseCase @Inject constructor( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val resourceProvider: ResourceProvider, private val newsCardHandler: NewsCardHandler, private val analyticsTrackerWrapper: AnalyticsTrackerWrapper ) : StatelessUseCase<Boolean>(ManagementType.NEWS_CARD, mainDispatcher, backgroundDispatcher, listOf()) { override suspend fun loadCachedData() = true override suspend fun fetchRemoteData(forced: Boolean): State<Boolean> = State.Data(true) override fun buildLoadingItem(): List<BlockListItem> = listOf() override fun buildUiModel(domainModel: Boolean): List<BlockListItem> { val highlightedText = resourceProvider.getString(R.string.stats_management_add_new_stats_card) val newsCardMessage = resourceProvider.getString(R.string.stats_management_news_card_message, highlightedText) return listOf( ImageItem(R.drawable.insights_management_feature_image), Tag(R.string.stats_management_new), BigTitle(R.string.stats_manage_your_stats), Text(text = newsCardMessage, bolds = listOf(highlightedText)), DialogButtons( R.string.stats_management_try_it_now, ListItemInteraction.create(this::onEditInsights), R.string.stats_management_dismiss_insights_news_card, ListItemInteraction.create(this::onDismiss) ) ) } private fun onEditInsights() { analyticsTrackerWrapper.track(Stat.STATS_INSIGHTS_MANAGEMENT_HINT_CLICKED) newsCardHandler.goToEdit() } private fun onDismiss() { analyticsTrackerWrapper.track(Stat.STATS_INSIGHTS_MANAGEMENT_HINT_DISMISSED) newsCardHandler.dismiss() } }
gpl-2.0
08ec7ffa1602b855aa9fc84ad8a5d7fa
49.904762
118
0.76333
4.504213
false
false
false
false
Yubico/yubioath-android
app/src/main/kotlin/com/yubico/yubioath/client/CredentialData.kt
1
3422
package com.yubico.yubioath.client import android.net.Uri import com.yubico.yubikitold.application.oath.HashAlgorithm import com.yubico.yubikitold.application.oath.OathType import org.apache.commons.codec.binary.Base32 data class CredentialData(val secret: ByteArray, var issuer: String?, var name: String, val oathType: OathType, val algorithm: HashAlgorithm = HashAlgorithm.SHA1, val digits: Int = 6, val period: Int = 30, val counter: Int = 0, var touch: Boolean = false) { companion object { fun fromUri(uri: Uri): CredentialData { val scheme = uri.scheme if (!uri.isHierarchical || scheme == null || scheme != "otpauth") { throw IllegalArgumentException("Uri scheme must be otpauth://") } val key = uri.getQueryParameter("secret").orEmpty().toUpperCase().let { val base32 = Base32() when { base32.isInAlphabet(it) -> base32.decode(it) else -> throw IllegalArgumentException("Secret must be base32 encoded") } } var data = uri.path if (data == null || data.isEmpty()) throw IllegalArgumentException("Path must contain name") if (data[0] == '/') data = data.substring(1) if (data.length > 64) data = data.substring(0, 64) val issuer = if (':' in data) { val parts = data.split(':', limit = 2) data = parts[1] parts[0] } else uri.getQueryParameter("issuer") val name = data val oathType = when (uri.host.orEmpty().toLowerCase()) { "totp" -> OathType.TOTP "hotp" -> OathType.HOTP else -> throw IllegalArgumentException("Invalid or missing OATH algorithm") } val algorithm = when (uri.getQueryParameter("algorithm").orEmpty().toLowerCase()) { "", "sha1" -> HashAlgorithm.SHA1 //This is the default value "sha256" -> HashAlgorithm.SHA256 "sha512" -> HashAlgorithm.SHA512 else -> throw IllegalArgumentException("Invalid or missing HMAC algorithm") } val digits: Int = when (uri.getQueryParameter("digits").orEmpty().trimStart('+', '0')) { "", "6" -> 6 "7" -> 7 "8" -> 8 else -> throw IllegalArgumentException("Digits must be in range 6-8") } val period = with(uri.getQueryParameter("period")) { if (this == null || isEmpty()) { 30 } else try { toInt() } catch (e: NumberFormatException) { throw IllegalArgumentException("Invalid value for period") } } val counter = with(uri.getQueryParameter("counter")) { if (this == null || isEmpty()) { 0 } else try { toInt() } catch (e: NumberFormatException) { throw IllegalArgumentException("Invalid value for counter") } } return CredentialData(key, issuer, name, oathType, algorithm, digits, period, counter) } } val encodedSecret: String = Base32().encodeToString(secret).trimEnd('=') }
bsd-2-clause
c711fd9f975e62a37bf7b6621a3882ba
40.240964
257
0.534483
4.853901
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/util/StationTableReader.kt
1
4452
package au.id.micolous.metrodroid.util import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.Station import au.id.micolous.metrodroid.transit.TransitName import au.id.micolous.metrodroid.transit.Trip expect internal fun StationTableReaderGetSTR(name: String): StationTableReader? data class ProtoStation(val operatorId: Int?, val name: TransitName, val latitude: Float, val longitude: Float, val lineIdList: List<Int>) interface StationTableReader { val notice: String? fun getOperatorDefaultMode(oper: Int): Trip.Mode? fun getOperatorName(oper: Int): TransitName? fun getStationById(id: Int, humanReadableID: String): ProtoStation? fun getLineName(id: Int): TransitName? fun getLineMode(id: Int): Trip.Mode? companion object { private fun fallbackName(humanReadableId: String): FormattedString = Localizer.localizeFormatted(R.string.unknown_format, humanReadableId) private fun getSTR(reader: String?): StationTableReader? = reader?.let { StationTableReaderGetSTR(it) } private fun fromProto(humanReadableID: String, ps: ProtoStation, operatorName: TransitName?, pl: Map<Int, TransitName?>?): Station { val hasLocation = ps.latitude != 0f && ps.longitude != 0f var lines: MutableList<FormattedString>? = null var lineIds: MutableList<String>? = null if (pl != null) { lines = ArrayList() lineIds = ArrayList() for ((first, second) in pl) { lines.addAll(listOfNotNull(second?.selectBestName(true))) lineIds.add(NumberUtils.intToHex(first)) } } return Station( humanReadableID, operatorName?.selectBestName(true), lines, ps.name.selectBestName(false), ps.name.selectBestName(true), if (hasLocation) ps.latitude else null, if (hasLocation) ps.longitude else null, false, lineIds.orEmpty()) } fun getStationNoFallback(reader: String?, id: Int, humanReadableId: String = NumberUtils.intToHex(id)): Station? { val str = getSTR(reader) ?: return null try { val ps = str.getStationById(id, humanReadableId) ?: return null val lines = mutableMapOf<Int, TransitName?>() for (lineId in ps.lineIdList) { lines[lineId] = str.getLineName(lineId) } return fromProto(humanReadableId, ps, ps.operatorId?.let { str.getOperatorName(it) }, lines) } catch (e: Exception) { return null } } fun getStation(reader: String?, id: Int, humanReadableId: String = NumberUtils.intToHex(id)): Station = getStationNoFallback(reader, id, humanReadableId) ?: Station.unknown(humanReadableId) fun getOperatorDefaultMode(reader: String?, id: Int): Trip.Mode = getSTR(reader)?.getOperatorDefaultMode(id) ?: Trip.Mode.OTHER fun getLineNameNoFallback(reader: String?, id: Int): FormattedString? = getSTR(reader)?.getLineName (id)?.selectBestName(false) fun getLineName(reader: String?, id: Int, humanReadableId: String = NumberUtils.intToHex(id)): FormattedString = getLineNameNoFallback(reader, id) ?: fallbackName(humanReadableId) fun getLineMode(reader: String?, id: Int): Trip.Mode? = getSTR(reader)?.getLineMode(id) fun getOperatorName(reader: String?, id: Int, isShort: Boolean, humanReadableId: String = NumberUtils.intToHex(id)): FormattedString? = getSTR(reader)?.getOperatorName(id)?.selectBestName(isShort) ?: fallbackName(humanReadableId) /** * Gets a licensing notice that applies to a particular MdST file. * @param reader Station database to read from. * @return String containing license notice, or null if not available. */ fun getNotice(reader: String?): String? = getSTR(reader)?.notice } }
gpl-3.0
efb29d68d04cd9e3da8d4a5b994a1a43
42.223301
138
0.614331
4.552147
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/card/desfire/DesfireManufacturingData.kt
1
4068
/* * DesfireManufacturingData.kt * * Copyright (C) 2011 Eric Butler * * Authors: * Eric Butler <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.card.desfire import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.util.Preferences import au.id.micolous.metrodroid.ui.HeaderListItem import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray class DesfireManufacturingData(val data: ImmutableByteArray) { val info: List<ListItem> get() { val items = mutableListOf( HeaderListItem(R.string.hardware_information), ListItem(R.string.desfire_vendor_id, hwVendorID.toString()), ListItem(R.string.desfire_type, hwType.toString()), ListItem(R.string.desfire_subtype, hwSubType.toString()), ListItem(R.string.desfire_major_version, hwMajorVersion.toString()), ListItem(R.string.desfire_minor_version, hwMinorVersion.toString()), ListItem(R.string.desfire_storage_size, hwStorageSize.toString()), ListItem(R.string.desfire_protocol, hwProtocol.toString()), HeaderListItem(R.string.software_information), ListItem(R.string.desfire_vendor_id, swVendorID.toString()), ListItem(R.string.desfire_type, swType.toString()), ListItem(R.string.desfire_subtype, swSubType.toString()), ListItem(R.string.desfire_major_version, swMajorVersion.toString()), ListItem(R.string.desfire_minor_version, swMinorVersion.toString()), ListItem(R.string.desfire_storage_size, swStorageSize.toString()), ListItem(R.string.desfire_protocol, swProtocol.toString())) if (!Preferences.hideCardNumbers) { items.add(HeaderListItem(R.string.desfire_general_info)) items.add(ListItem(R.string.calypso_serial_number, uid.toHexString())) items.add(ListItem(R.string.desfire_batch_number, batchNo.toHexString())) items.add(ListItem(R.string.manufacture_week, weekProd.toString(16))) items.add(ListItem(R.string.manufacture_year, yearProd.toString(16))) } return items } private val hwVendorID get() = data[0].toInt() private val hwType get() = data[1].toInt() private val hwSubType get() = data[2].toInt() private val hwMajorVersion get() = data[3].toInt() private val hwMinorVersion get() = data[4].toInt() private val hwStorageSize get() = data[5].toInt() private val hwProtocol get() = data[6].toInt() private val swVendorID get() = data[7].toInt() private val swType get() = data[8].toInt() private val swSubType = data[9].toInt() private val swMajorVersion get() = data[10].toInt() private val swMinorVersion get() = data[11].toInt() private val swStorageSize get() = data[12].toInt() private val swProtocol get() = data[13].toInt() val uid: ImmutableByteArray get() = data.sliceOffLen(14, 7) // FIXME: This is returning a negative number. Probably is unsigned. private val batchNo: ImmutableByteArray get() = data.sliceOffLen(21, 5) private val weekProd get() = data[26].toInt() private val yearProd get() = data[27].toInt() }
gpl-3.0
a2e355a33827818d92f3b80cec5378c8
46.302326
89
0.663225
4.15526
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/JavaToKotlinAction.kt
1
14319
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.ide.highlighter.ArchiveFileType import com.intellij.ide.highlighter.JavaFileType import com.intellij.ide.scratch.ScratchFileService import com.intellij.ide.scratch.ScratchRootType import com.intellij.openapi.actionSystem.* import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ex.MessagesEx import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileVisitor import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.base.codeInsight.pathBeforeJavaToKotlinConversion import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils import org.jetbrains.kotlin.idea.configuration.ExperimentalFeatures import org.jetbrains.kotlin.idea.core.util.toPsiFile import org.jetbrains.kotlin.idea.formatter.commitAndUnblockDocument import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices import org.jetbrains.kotlin.idea.j2k.J2kPostProcessor import org.jetbrains.kotlin.idea.statistics.ConversionType import org.jetbrains.kotlin.idea.statistics.J2KFusCollector import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.j2k.ConverterSettings import org.jetbrains.kotlin.j2k.ConverterSettings.Companion.defaultSettings import org.jetbrains.kotlin.j2k.FilesResult import org.jetbrains.kotlin.j2k.J2kConverterExtension import org.jetbrains.kotlin.j2k.OldJavaToKotlinConverter import org.jetbrains.kotlin.psi.KtFile import java.io.IOException import kotlin.io.path.notExists import kotlin.system.measureTimeMillis class JavaToKotlinAction : AnAction() { companion object { private fun uniqueKotlinFileName(javaFile: VirtualFile): String { val nioFile = javaFile.fileSystem.getNioPath(javaFile) var i = 0 while (true) { val fileName = javaFile.nameWithoutExtension + (if (i > 0) i else "") + ".kt" if (nioFile == null || nioFile.resolveSibling(fileName).notExists()) return fileName i++ } } val title = KotlinBundle.message("action.j2k.name") private fun saveResults(javaFiles: List<PsiJavaFile>, convertedTexts: List<String>): List<VirtualFile> { val result = ArrayList<VirtualFile>() for ((psiFile, text) in javaFiles.zip(convertedTexts)) { try { val document = PsiDocumentManager.getInstance(psiFile.project).getDocument(psiFile) val errorMessage = when { document == null -> KotlinBundle.message("action.j2k.error.cant.find.document", psiFile.name) !document.isWritable -> KotlinBundle.message("action.j2k.error.read.only", psiFile.name) else -> null } if (errorMessage != null) { val message = KotlinBundle.message("action.j2k.error.cant.save.result", errorMessage) MessagesEx.error(psiFile.project, message).showLater() continue } document!!.replaceString(0, document.textLength, text) FileDocumentManager.getInstance().saveDocument(document) val virtualFile = psiFile.virtualFile if (ScratchRootType.getInstance().containsFile(virtualFile)) { val mapping = ScratchFileService.getInstance().scratchesMapping mapping.setMapping(virtualFile, KotlinFileType.INSTANCE.language) } else { val fileName = uniqueKotlinFileName(virtualFile) virtualFile.pathBeforeJavaToKotlinConversion = virtualFile.path virtualFile.rename(this, fileName) } result += virtualFile } catch (e: IOException) { MessagesEx.error(psiFile.project, e.message ?: "").showLater() } } return result } /** * For binary compatibility with third-party plugins. */ fun convertFiles( files: List<PsiJavaFile>, project: Project, module: Module, enableExternalCodeProcessing: Boolean = true, askExternalCodeProcessing: Boolean = true, forceUsingOldJ2k: Boolean = false ): List<KtFile> = convertFiles( files, project, module, enableExternalCodeProcessing, askExternalCodeProcessing, forceUsingOldJ2k, defaultSettings ) fun convertFiles( files: List<PsiJavaFile>, project: Project, module: Module, enableExternalCodeProcessing: Boolean = true, askExternalCodeProcessing: Boolean = true, forceUsingOldJ2k: Boolean = false, settings: ConverterSettings = defaultSettings ): List<KtFile> { val javaFiles = files.filter { it.virtualFile.isWritable }.ifEmpty { return emptyList() } var converterResult: FilesResult? = null fun convert() { val converter = if (forceUsingOldJ2k) OldJavaToKotlinConverter( project, settings, IdeaJavaToKotlinServices ) else J2kConverterExtension.extension(useNewJ2k = ExperimentalFeatures.NewJ2k.isEnabled).createJavaToKotlinConverter( project, module, settings, IdeaJavaToKotlinServices ) converterResult = converter.filesToKotlin( javaFiles, if (forceUsingOldJ2k) J2kPostProcessor(formatCode = true) else J2kConverterExtension.extension(useNewJ2k = ExperimentalFeatures.NewJ2k.isEnabled) .createPostProcessor(formatCode = true), progress = ProgressManager.getInstance().progressIndicator!! ) } fun convertWithStatistics() { val conversionTime = measureTimeMillis { convert() } val linesCount = runReadAction { javaFiles.sumOf { StringUtil.getLineBreakCount(it.text) } } J2KFusCollector.log( ConversionType.FILES, ExperimentalFeatures.NewJ2k.isEnabled, conversionTime, linesCount, javaFiles.size ) } if (!ProgressManager.getInstance().runProcessWithProgressSynchronously( ::convertWithStatistics, title, true, project ) ) return emptyList() var externalCodeUpdate: ((List<KtFile>) -> Unit)? = null val result = converterResult ?: return emptyList() val externalCodeProcessing = result.externalCodeProcessing if (enableExternalCodeProcessing && externalCodeProcessing != null) { val question = KotlinBundle.message("action.j2k.correction.required") if (!askExternalCodeProcessing || (Messages.showYesNoDialog( project, question, title, Messages.getQuestionIcon() ) == Messages.YES) ) { ProgressManager.getInstance().runProcessWithProgressSynchronously( { runReadAction { externalCodeUpdate = externalCodeProcessing.prepareWriteOperation( ProgressManager.getInstance().progressIndicator!! ) } }, title, true, project ) } } return project.executeWriteCommand(KotlinBundle.message("action.j2k.task.name"), null) { CommandProcessor.getInstance().markCurrentCommandAsGlobal(project) val newFiles = saveResults(javaFiles, result.results) .map { it.toPsiFile(project) as KtFile } .onEach { it.commitAndUnblockDocument() } externalCodeUpdate?.invoke(newFiles) PsiDocumentManager.getInstance(project).commitAllDocuments() newFiles.singleOrNull()?.let { FileEditorManager.getInstance(project).openFile(it.virtualFile, true) } newFiles } } } override fun actionPerformed(e: AnActionEvent) { val javaFiles = selectedJavaFiles(e).filter { it.isWritable }.toList() val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return val module = e.getData(PlatformCoreDataKeys.MODULE) ?: return if (javaFiles.isEmpty()) { val statusBar = WindowManager.getInstance().getStatusBar(project) JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(KotlinBundle.message("action.j2k.errornothing.to.convert"), MessageType.ERROR, null) .createBalloon() .showInCenterOf(statusBar.component) } if (!J2kConverterExtension.extension(useNewJ2k = ExperimentalFeatures.NewJ2k.isEnabled) .doCheckBeforeConversion(project, module) ) return val firstSyntaxError = javaFiles.asSequence().map { PsiTreeUtil.findChildOfType(it, PsiErrorElement::class.java) }.firstOrNull() if (firstSyntaxError != null) { val count = javaFiles.filter { PsiTreeUtil.hasErrorElements(it) }.count() assert(count > 0) val firstFileName = firstSyntaxError.containingFile.name val question = when (count) { 1 -> KotlinBundle.message("action.j2k.correction.errors.single", firstFileName) else -> KotlinBundle.message("action.j2k.correction.errors.multiple", firstFileName, count - 1) } val okText = KotlinBundle.message("action.j2k.correction.investigate") val cancelText = KotlinBundle.message("action.j2k.correction.proceed") if (Messages.showOkCancelDialog( project, question, title, okText, cancelText, Messages.getWarningIcon() ) == Messages.OK ) { NavigationUtil.activateFileWithPsiElement(firstSyntaxError.navigationElement) return } } convertFiles(javaFiles, project, module) } override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isEnabled(e) } private fun isEnabled(e: AnActionEvent): Boolean { if (KotlinPlatformUtils.isCidr) return false val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return false val project = e.project ?: return false e.getData(PlatformCoreDataKeys.MODULE) ?: return false return isAnyJavaFileSelected(project, virtualFiles) } private fun isAnyJavaFileSelected(project: Project, files: Array<VirtualFile>): Boolean { if (files.any { it.isSuitableDirectory() }) return true // Giving up on directories val manager = PsiManager.getInstance(project) return files.any { it.extension == JavaFileType.DEFAULT_EXTENSION && manager.findFile(it) is PsiJavaFile && it.isWritable } } private fun VirtualFile.isSuitableDirectory(): Boolean = isDirectory && fileType !is ArchiveFileType && isWritable private fun selectedJavaFiles(e: AnActionEvent): Sequence<PsiJavaFile> { val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return sequenceOf() val project = e.project ?: return sequenceOf() return allJavaFiles(virtualFiles, project) } private fun allJavaFiles(filesOrDirs: Array<VirtualFile>, project: Project): Sequence<PsiJavaFile> { val manager = PsiManager.getInstance(project) return allFiles(filesOrDirs) .asSequence() .mapNotNull { manager.findFile(it) as? PsiJavaFile } } private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> { val result = ArrayList<VirtualFile>() for (file in filesOrDirs) { VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Unit>() { override fun visitFile(file: VirtualFile): Boolean { result.add(file) return true } }) } return result } }
apache-2.0
47d55ee95eb79b4715428f726c9e0f0e
43.061538
158
0.616593
5.444487
false
false
false
false
GunoH/intellij-community
uast/uast-common/src/com/intellij/psi/UastReferenceByUsageResolver.kt
2
4002
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("UastReferenceByUsageResolver") package com.intellij.psi import com.intellij.lang.jvm.JvmModifier import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.DumbService import com.intellij.psi.impl.cache.CacheManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.UsageSearchContext import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.containers.ContainerUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.ULocalVariable import org.jetbrains.uast.UVariable import org.jetbrains.uast.UastLanguagePlugin import org.jetbrains.uast.toUElementOfType private const val MAX_FILES_TO_FIND_USAGES: Int = 5 /** * Searches for direct variable usages not only in the same file but also in the module. * Must be used only from [PsiReference.resolve], do not call from [PsiReferenceProvider.getReferencesByElement]. */ @ApiStatus.Experimental internal fun getDirectVariableUsagesWithNonLocal(uVar: UVariable): Sequence<PsiElement> { val variablePsi = uVar.sourcePsi ?: return emptySequence() val project = variablePsi.project if (DumbService.isDumb(project)) return emptySequence() // do not try to search in dumb mode val cachedValue = CachedValuesManager.getManager(project).getCachedValue(variablePsi, CachedValueProvider { val anchors = findAllDirectVariableUsages(variablePsi).map(PsiAnchor::create) CachedValueProvider.Result.createSingleDependency(anchors, PsiModificationTracker.MODIFICATION_COUNT) }) return cachedValue.asSequence().mapNotNull(PsiAnchor::retrieve) } private fun findAllDirectVariableUsages(variablePsi: PsiElement): Iterable<PsiElement> { val uVariable = variablePsi.toUElementOfType<UVariable>() val variableName = uVariable?.name if (variableName.isNullOrEmpty()) return emptyList() val currentFile = variablePsi.containingFile ?: return emptyList() val localUsages = findReferencedVariableUsages(variablePsi, variableName, arrayOf(currentFile)) // non-local searches are limited for real-life use cases, we do not try to find all possible usages if (uVariable is ULocalVariable || (variablePsi is PsiModifierListOwner && variablePsi.hasModifier(JvmModifier.PRIVATE)) || !STRICT_CONSTANT_NAME_PATTERN.matches(variableName)) { return localUsages } val module = ModuleUtilCore.findModuleForPsiElement(variablePsi) ?: return localUsages val uastScope = getUastScope(module.moduleScope) val searchHelper = PsiSearchHelper.getInstance(module.project) if (searchHelper.isCheapEnoughToSearch(variableName, uastScope, currentFile, null) != PsiSearchHelper.SearchCostResult.FEW_OCCURRENCES) { return localUsages } val cacheManager = CacheManager.getInstance(variablePsi.project) val containingFiles = cacheManager.getVirtualFilesWithWord( variableName, UsageSearchContext.IN_CODE, uastScope, true) val useScope = variablePsi.useScope val psiManager = PsiManager.getInstance(module.project) val filesToSearch = containingFiles.asSequence() .filter { useScope.contains(it) && it != currentFile.virtualFile } .mapNotNull { psiManager.findFile(it) } .sortedBy { it.virtualFile.canonicalPath } .take(MAX_FILES_TO_FIND_USAGES) .toList() .toTypedArray() val nonLocalUsages = findReferencedVariableUsages(variablePsi, variableName, filesToSearch) return ContainerUtil.concat(localUsages, nonLocalUsages) } private fun getUastScope(originalScope: GlobalSearchScope): GlobalSearchScope { val fileTypes = UastLanguagePlugin.getInstances().map { it.language.associatedFileType }.toTypedArray() return GlobalSearchScope.getScopeRestrictedByFileTypes(originalScope, *fileTypes) }
apache-2.0
0bdc9327357797ffd08468f7fdef5d96
42.978022
139
0.802849
4.775656
false
false
false
false
NiciDieNase/chaosflix
leanback/src/main/java/de/nicidienase/chaosflix/leanback/events/EventsActivity.kt
1
4800
package de.nicidienase.chaosflix.leanback.events import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import de.nicidienase.chaosflix.common.ChaosflixUtil import de.nicidienase.chaosflix.common.mediadata.MediaRepository import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Conference import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Event import de.nicidienase.chaosflix.common.viewmodel.BrowseViewModel import de.nicidienase.chaosflix.common.viewmodel.ViewModelFactory import de.nicidienase.chaosflix.leanback.BrowseErrorFragment import de.nicidienase.chaosflix.leanback.R class EventsActivity : androidx.fragment.app.FragmentActivity() { lateinit var viewModel: BrowseViewModel private lateinit var conference: Conference private var fragment: EventsFragment? = null private var errorFragment: BrowseErrorFragment? = null public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) conference = intent.getParcelableExtra(CONFERENCE) setContentView(R.layout.activity_events_browse) viewModel = ViewModelProviders.of(this, ViewModelFactory.getInstance(this)).get(BrowseViewModel::class.java) } override fun onStart() { super.onStart() viewModel.updateEventsForConference(conference).observe(this, Observer { event -> when (event?.state) { MediaRepository.State.RUNNING -> { Log.i(TAG, "Refresh running") if (errorFragment == null) { errorFragment = BrowseErrorFragment.showErrorFragment(supportFragmentManager, R.id.browse_fragment) } } MediaRepository.State.DONE -> { Log.i(TAG, "Refresh done") if (event.error != null) { val errorMessage = event.error ?: "Error refreshing events" errorFragment?.setErrorContent(errorMessage, supportFragmentManager) } else { if (event.data?.isEmpty() == true) { errorFragment?.setErrorContent("No Events found for this conference", supportFragmentManager) } else { errorFragment?.dismiss(supportFragmentManager) errorFragment = null } } } } }) viewModel.getEventsforConference(conference).observe(this, Observer { events -> events?.let { if (it.isNotEmpty()) { updateFragment(ChaosflixUtil.areTagsUsefull(events, conference.acronym)) (fragment as EventsFragment).updateEvents(conference, it) } } }) } private fun updateFragment(tagsUseful: Boolean) { if ((tagsUseful && fragment is EventsRowsBrowseFragment) || (!tagsUseful && fragment is EventsGridBrowseFragment)) { Log.i(TAG, "Fragment is up-to-date, returning") return } val newFragment: Fragment = // EventsRowsBrowseFragment.create(conference) if (tagsUseful) { Log.i(TAG, "setting RowsFragment") EventsRowsBrowseFragment.create(conference) } else { Log.i(TAG, "setting gridFragment") EventsGridBrowseFragment.create(conference) } errorFragment?.dismiss(supportFragmentManager) ?: Log.e(TAG, "Cannot dismiss, errorFragment is null") errorFragment = null supportFragmentManager.beginTransaction().replace(R.id.browse_fragment, newFragment).commit() fragment = newFragment as EventsFragment } interface EventsFragment { fun updateEvents(conference: Conference, events: List<Event>) } companion object { @JvmStatic val CONFERENCE = "conference" @JvmStatic val SHARED_ELEMENT_NAME = "shared_element" private val TAG = EventsActivity::class.java.simpleName @JvmStatic @JvmOverloads fun start(context: Context, conference: Conference, transition: Bundle? = null) { val i = Intent(context, EventsActivity::class.java) i.putExtra(CONFERENCE, conference) if (transition != null) { context.startActivity(i, transition) } else { context.startActivity(i) } } } }
mit
61c2d7e0c0deb4ad06f76e90144e1b24
40.37931
123
0.62625
5.251641
false
false
false
false
CzBiX/v2ex-android
app/src/main/kotlin/com/czbix/v2ex/db/CommentDao.kt
1
1228
package com.czbix.v2ex.db import androidx.paging.DataSource import androidx.room.* @Dao abstract class CommentDao { @Query("SELECT Comment.*, Member.username as member_username, Member.baseUrl as member_baseUrl FROM Comment INNER JOIN Member ON Comment.username = Member.username WHERE topicId = :id ORDER BY id ASC") abstract fun getCommentsByTopicId(id: Int): DataSource.Factory<Int, CommentAndMember> @Delete(entity = Comment::class) abstract suspend fun deleteCommentsByPage(page: CommentPage) @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insertComments(comments: List<Comment>) @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insertMembers(members: List<Member>) @Transaction open suspend fun updateCommentAndMembers(list: List<CommentAndMember>, page: CommentPage) { val comments = MutableList(list.size) { list[it].comment } val members = list.map { it.member }.toSet().toList() deleteCommentsByPage(page) insertMembers(members) insertComments(comments) } class CommentPage( val topicId: Int, val page: Int ) }
apache-2.0
e9dfd97019ae85879b67b82f50e26736
31.342105
205
0.696254
4.498168
false
false
false
false
marius-m/wt4
components/src/main/java/lt/markmerkk/timecounter/WorkGoalDurationCalculator.kt
1
1636
package lt.markmerkk.timecounter import lt.markmerkk.ActiveDisplayRepository import lt.markmerkk.utils.hourglass.HourGlass import org.joda.time.DateTime import org.joda.time.Duration import org.joda.time.Interval import org.joda.time.LocalDate /** * Responsible for calculating duration for worklogs */ class WorkGoalDurationCalculator( private val hourGlass: HourGlass, private val activeDisplayRepository: ActiveDisplayRepository, ) { fun durationWorked( displayDateStart: LocalDate, displayDateEnd: LocalDate, ): Duration { return durationRunningClock( displayDateStart = displayDateStart, displayDateEnd = displayDateEnd, ).plus(durationLoggedForTarget(displayDateStart)) } fun durationRunningClock( hourGlass: HourGlass = this.hourGlass, displayDateStart: LocalDate, displayDateEnd: LocalDate, ): Duration { val intStart = displayDateStart.toDateTimeAtStartOfDay() val intEnd = displayDateEnd.toDateTimeAtStartOfDay() val isClockDateBetweenDisplayDate = Interval( intStart, intEnd ).contains(hourGlass.start) || hourGlass.start.toLocalDate().isEqual(displayDateStart) if (isClockDateBetweenDisplayDate) { return hourGlass.duration } return Duration.ZERO } fun durationLogged(): Duration { return activeDisplayRepository.totalAsDuration() } fun durationLoggedForTarget(target: LocalDate): Duration { return activeDisplayRepository .durationForTargetDate(target) } }
apache-2.0
e93c2a8adc4f4820e14f4ee6d5cc8d2f
29.886792
70
0.699878
4.840237
false
true
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-double-receive/jvm/src/io/ktor/server/plugins/doublereceive/FileCacheJvm.kt
1
1665
// ktlint-disable filename /* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.doublereceive import io.ktor.util.cio.* import io.ktor.utils.io.* import kotlinx.coroutines.* import java.io.* import java.nio.* import kotlin.coroutines.* internal actual class FileCache actual constructor( private val body: ByteReadChannel, bufferSize: Int, context: CoroutineContext ) : DoubleReceiveCache { private val file = File.createTempFile("ktor-double-receive-cache", ".tmp") @OptIn(DelicateCoroutinesApi::class) private val saveJob = GlobalScope.launch(context + Dispatchers.IO) { val buffer = ByteBuffer.allocate(bufferSize) @Suppress("BlockingMethodInNonBlockingContext") FileOutputStream(file).use { stream -> stream.channel.use { out -> out.truncate(0L) buffer.position(buffer.limit()) while (true) { while (buffer.hasRemaining()) { out.write(buffer) } buffer.clear() if (body.readAvailable(buffer) == -1) break buffer.flip() } } } } actual override fun read(): ByteReadChannel = file.readChannel() actual override fun dispose() { runCatching { saveJob.cancel() } runCatching { file.delete() } if (!body.isClosedForRead) { runCatching { body.cancel() } } } }
apache-2.0
e9d94653340d6322367ce4e1876e4e9b
26.75
119
0.574174
4.770774
false
false
false
false
pureal-code/pureal-os
traits/src/net/pureal/traits/math/operations/SubtractionValue.kt
1
1370
package net.pureal.traits.math.operations import net.pureal.traits.math.* import net.pureal.traits.* public trait SubtractionValue : RealBinaryOperation { public companion object : Constructor2<SubtractionValue, Real, Real> { override fun invoke(a: Real, b: Real): SubtractionValue = object : SubtractionValue, Calculatable() { override val subReals: Array<Real> = array(a, b) } } private val constructor: Constructor2<SubtractionValue, Real, Real> get() = SubtractionValue final override val priority: Int get() = 0 override val description: String get() = "Subtraction" final override val operationSign: String get() = "-" final override val isOrderDependent: Boolean get() = true override fun approximate(): InternalReal { return value1.approximate() tryMinus value2.approximate() } override fun calculate(): Real { val s1: Real = value1.calculate() val s2: Real = value2.calculate() if (s1 is RealPrimitive && s2 is RealPrimitive) return real(s1.value - s2.value) // return this if no simplification is possible return this } override fun minus(): SubtractionValue = SubtractionValue.invoke(-value1, -value2) override val isPositive: Boolean get() = value1.isPositive || !value2.isPositive }
bsd-3-clause
0502c61b7a1e760a26bc7c88151e45dd
29.444444
109
0.672263
4.228395
false
false
false
false
code-disaster/lwjgl3
modules/generator/src/main/kotlin/org/lwjgl/generator/Generator.kt
4
16429
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.generator import java.io.* import java.lang.reflect.* import java.nio.* import java.nio.file.* import java.nio.file.attribute.* import java.util.* import java.util.concurrent.* import java.util.concurrent.atomic.* import kotlin.math.* /* A template will be generated in the following cases: - The target Java source does not exist. - The source template has a later timestamp than the target. - Any file in the source package has later timestamp than the target. - Any file in the generator itself has later timestamp than the target. (implies re-generation of all templates) Example template: <templates>/opengl/templates/ARB_imaging.kt - Generator source -> <generator>/src/main/kotlin/org/lwjgl/generator/ - Source package -> <templates>/opengl/ - Source template -> <templates>/opengl/templates/ARB_imaging.kt - Target source (Java) -> <module>/src/generated/java/opengl/org/lwjgl/opengl/ARBImaging.java - Target source (C) -> <module>/src/generated/c/opengl/org_lwjgl_opengl_ARBImaging.c */ fun main(args: Array<String>) { System.setProperty("file.encoding", "UTF8") System.setProperty("line.separator", "\n") require(args.isNotEmpty()) { "Module root path not specified" } require(Files.isDirectory(Paths.get(args[0]))) { "Invalid module root path: ${args[0]}" } Generator(args[0]).apply { // We discover templates reflectively. // For a package passed to the generate function, we search for <package>.templates.* class files and run any public static methods that return // NativeClass objects. // Note: For a Kotlin package X.Y.Z, <Z>Package is the class Kotlin generates that contains all top-level functions/properties in that package. // Example: org.lwjgl.opengl -> org.lwjgl.opengl.OpenglPackage (the first letter is capitalized) val pool = ForkJoinPool.commonPool() // Generate bindings try { val errors = AtomicInteger() Module.values().let { modules -> val latch = CountDownLatch(modules.size) modules.forEach { pool.submit { try { this.generateModule(it) } catch (t: Throwable) { errors.incrementAndGet() t.printStackTrace() } latch.countDown() } } latch.await() } if (errors.get() != 0) throw RuntimeException("Generation failed") // Generate utility classes. These are auto-registered during the process above. CountDownLatch(4).let { latch -> fun submit(work: () -> Unit) { pool.submit { try { work() } catch (t: Throwable) { errors.incrementAndGet() t.printStackTrace() } latch.countDown() } } fun <T : GeneratorTarget> generateRegistered(typeName: String, targets: Iterable<T>) { targets.forEach { try { generateSimple(it) } catch (e: Exception) { throw RuntimeException("Uncaught exception while generating $typeName: ${it.packageName}.${it.className}", e) } } } submit { generateRegistered("struct", Generator.structs) } submit { generateRegistered("callback", Generator.callbacks) } submit { generateRegistered("custom class", Generator.customClasses) } Generator.callbacks.forEach { if (it.module.enabled) JNI.register(it) } submit { generateSimple(JNI) } latch.await() } if (errors.get() != 0) throw RuntimeException("Generation failed") } finally { pool.shutdown() } } } class Generator(private val moduleRoot: String) { companion object { // package -> #name -> class#prefix_name internal val tokens = ConcurrentHashMap<Module, MutableMap<String, String>>() // package -> #name() -> class#prefix_name() internal val functions = ConcurrentHashMap<Module, MutableMap<String, String>>() internal val structs = ConcurrentLinkedQueue<Struct>() internal val structChildren = ConcurrentHashMap<Module, MutableMap<String, MutableList<Struct>>>() internal val callbacks = ConcurrentLinkedQueue<CallbackFunction>() internal val customClasses = ConcurrentLinkedQueue<GeneratorTarget>() /** Registers a struct definition. */ fun register(struct: Struct): Struct { if (struct.module.enabled) { structs.add(struct) if (struct.parentStruct != null) { structChildren .getOrPut(struct.module) { HashMap() } .getOrPut(struct.parentStruct.nativeName) { ArrayList() } .add(struct) } } return struct } /** Registers a callback function. */ fun register(callback: CallbackFunction) { if (callback.module.enabled) callbacks.add(callback) } /** Registers a custom class. */ fun <T : GeneratorTarget> register(customClass: T): T { if (customClass.module.enabled) customClasses.add(customClass) return customClass } } private val GENERATOR_LAST_MODIFIED = sequenceOf( Paths.get("modules/generator/src/main/kotlin").lastModified(), Paths.get("config/build-bindings.xml").lastModified ).fold(0L, ::max) private fun methodFilter(method: Method, javaClass: Class<*>) = // static method.modifiers and Modifier.STATIC != 0 && // returns NativeClass method.returnType === javaClass && // has no arguments method.parameterTypes.isEmpty() private fun apply(packagePath: String, packageName: String, consume: Sequence<Method>.() -> Unit) { val packageDirectory = Paths.get(packagePath) check(Files.isDirectory(packageDirectory)) Files.list(packageDirectory) .filter { KOTLIN_PATH_MATCHER.matches(it) } .sorted() .also { it.forEach { path -> try { Class .forName("$packageName.${path.fileName.toString().substringBeforeLast('.').upperCaseFirst}Kt") .methods .asSequence() .consume() } catch (e: ClassNotFoundException) { // ignore } } it.close() } } internal fun generateModule(module: Module) { val packageKotlin = module.packageKotlin val pathKotlin = "$moduleRoot/${module.path}/src/templates/kotlin/${packageKotlin.replace('.', '/')}" val moduleLastModified = Paths.get(pathKotlin).lastModified(maxDepth = 1) moduleLastModifiedMap[module] = moduleLastModified if (!module.enabled) return // Find and run configuration methods //runConfiguration(packagePath, packageName) apply(pathKotlin, packageKotlin) { this .filter { methodFilter(it, Void.TYPE) } .forEach { it.invoke(null) } } // Find the template methods val templates = TreeSet<Method> { o1, o2 -> o1.name.compareTo(o2.name) } apply("$pathKotlin/templates", "$packageKotlin.templates") { this.filterTo(templates) { methodFilter(it, NativeClass::class.java) } } if (templates.isEmpty()) { println("*WARNING* No templates found in $packageKotlin.templates package.") return } // Get classes with bodies and register tokens/functions val packageTokens = LinkedHashMap<String, String>() val packageFunctions = LinkedHashMap<String, String>() val duplicateTokens = HashSet<String>() val duplicateFunctions = HashSet<String>() val classes = ArrayList<NativeClass>() for (template in templates) { val nativeClass = template.invoke(null) as NativeClass? ?: continue check(nativeClass.module === module) { "NativeClass ${nativeClass.className} has invalid module [${nativeClass.module.name}]. Should be: [${module.name}]" } if (nativeClass.hasBody) { classes.add(nativeClass) // Register tokens/functions for javadoc link references nativeClass.registerLinks( packageTokens, duplicateTokens, packageFunctions, duplicateFunctions ) } } packageTokens.keys.removeAll(duplicateTokens) packageFunctions.keys.removeAll(duplicateFunctions) tokens[module] = packageTokens functions[module] = packageFunctions // Generate the template code classes.forEach { it.registerFunctions(module.arrayOverloads) generate(pathKotlin, it, max(moduleLastModified, GENERATOR_LAST_MODIFIED)) } } private fun generate(pathKotlin: String, nativeClass: NativeClass, moduleLastModified: Long) { val outputJava = Paths .get("$moduleRoot/${nativeClass.module.path}/src/generated/java/${nativeClass.packageName.replace('.', '/')}/${nativeClass.className}.java") val lmt = max(nativeClass.getLastModified("$pathKotlin/templates"), moduleLastModified) if (lmt < outputJava.lastModified) { //println("SKIPPED: ${nativeClass.packageName}.${nativeClass.className}") return } //println("GENERATING: ${nativeClass.packageName}.${nativeClass.className}") generateOutput(nativeClass, outputJava, lmt) { it.generateJava() } if (!nativeClass.skipNative) { generateNative(nativeClass) { generateOutput(nativeClass, it) { out -> out.generateNative() } } } else nativeClass.nativeDirectivesWarning() } internal fun generateSimple(target: GeneratorTarget) { val modulePath = "$moduleRoot/${target.module.path}" val packageKotlin = target.module.packageKotlin val pathKotlin = "$modulePath/src/templates/kotlin/${packageKotlin.replace('.', '/')}" val outputJava = Paths.get("$modulePath/src/generated/java/${target.packageName.replace('.', '/')}/${target.className}.java") val lmt = if (target.sourceFile == null) null else max( target.getLastModified(pathKotlin), max(moduleLastModifiedMap[target.module]!!, GENERATOR_LAST_MODIFIED) ) if (lmt != null && lmt < outputJava.lastModified) { //println("SKIPPED: ${target.packageName}.${target.className}") return } //println("GENERATING: ${target.packageName}.${target.className}") generateOutput(target, outputJava, lmt) { it.generateJava() } if (target is GeneratorTargetNative && !target.skipNative) { generateNative(target) { generateOutput(target, it) { out -> out.generateNative() } } } } private fun generateNative(target: GeneratorTargetNative, generate: (Path) -> Unit) { val targetFile = "${target.nativeSubPath.let { if (it.isEmpty()) "" else "$it/" }}${target.nativeFileName}.${if (target.cpp) "cpp" else "c"}" generate(Paths.get("$moduleRoot/${target.module.path}/src/generated/c/$targetFile")) } } // File management private val moduleLastModifiedMap: MutableMap<Module, Long> = ConcurrentHashMap() internal val Path.lastModified get() = if (Files.isRegularFile(this)) Files.getLastModifiedTime(this).toMillis() else 0L private val KOTLIN_PATH_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**/*.kt") internal fun Path.lastModified( maxDepth: Int = Int.MAX_VALUE, glob: String? = null, matcher: PathMatcher = if (glob == null) KOTLIN_PATH_MATCHER else FileSystems.getDefault().getPathMatcher("glob:$glob") ): Long { check(Files.isDirectory(this)) { "$this is not a directory" } return Files .find(this, maxDepth, { path, _ -> matcher.matches(path) }) .mapToLong(Path::lastModified) .reduce(0L, Math::max) } private fun ensurePath(path: Path) { val parent = path.parent ?: throw IllegalArgumentException("The given path has no parent directory.") if (!Files.isDirectory(parent)) { println("\tMKDIR: $parent") Files.createDirectories(parent) } } private fun readFile(file: Path) = Files.newByteChannel(file).use { val bytesTotal = it.size().toInt() val buffer = ByteBuffer.allocateDirect(bytesTotal) var bytesRead = 0 do { bytesRead += it.read(buffer) } while (bytesRead < bytesTotal) buffer.flip() buffer } private fun <T> generateOutput( target: T, file: Path, /** If not null, the file timestamp will be updated if no change occured since last generation. */ lmt: Long? = null, generate: T.(PrintWriter) -> Unit ) { // TODO: Add error handling ensurePath(file) if (Files.isRegularFile(file)) { // Generate in-memory val baos = ByteArrayOutputStream(4 * 1024) PrintWriter(OutputStreamWriter(baos, Charsets.UTF_8)).use { target.generate(it) } // Compare the existing file content with the generated content. val before = readFile(file) val after = baos.toByteArray() fun somethingChanged(before: ByteBuffer, after: ByteArray): Boolean { if (before.remaining() != after.size) return true return (0 until before.limit()).any { before.get(it) != after[it] } } if (somethingChanged(before, after)) { println("\tUPDATING: $file") // Overwrite Files.newOutputStream(file).use { it.write(after) } } else if (lmt != null) { // Update the file timestamp Files.setLastModifiedTime(file, FileTime.fromMillis(lmt + 1)) } } else { println("\tWRITING: $file") PrintWriter(Files.newBufferedWriter(file, Charsets.UTF_8)).use { target.generate(it) } } } /** Returns true if the array was empty. */ internal inline fun <T> Array<out T>.forEachWithMore(apply: (T, Boolean) -> Unit): Boolean { for (i in 0..this.lastIndex) apply(this[i], 0 < i) return this.isEmpty() } /** Returns true if the collection was empty. */ internal fun <T> Collection<T>.forEachWithMore(moreOverride: Boolean = false, apply: (T, Boolean) -> Unit): Boolean = this.asSequence().forEachWithMore(moreOverride, apply) /** Returns true if the sequence was empty. */ internal fun <T> Sequence<T>.forEachWithMore(moreOverride: Boolean = false, apply: (T, Boolean) -> Unit): Boolean { var more = moreOverride for (item in this) { apply(item, more) if (!more) more = true } return more } /** Returns the string with the first letter uppercase. */ internal val String.upperCaseFirst get() = if (this.length <= 1) this.uppercase() else "${Character.toUpperCase(this[0])}${this.substring(1)}"
bsd-3-clause
fa0125754dc65854426c321de3815371
34.255365
152
0.576602
4.842028
false
false
false
false
dahlstrom-g/intellij-community
platform/script-debugger/debugger-ui/src/DebuggerViewSupport.kt
16
3539
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.debugger import com.intellij.util.ThreeState import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XInlineDebuggerDataCallback import com.intellij.xdebugger.frame.XNavigatable import com.intellij.xdebugger.frame.XValueNode import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.frame.CallFrameView import org.jetbrains.debugger.values.ObjectValue import org.jetbrains.debugger.values.Value import org.jetbrains.rpc.LOG import javax.swing.Icon interface DebuggerViewSupport { val vm: Vm? get() = null fun getSourceInfo(script: Script?, frame: CallFrame): SourceInfo? = null fun getSourceInfo(functionName: String?, scriptUrl: String, line: Int, column: Int): SourceInfo? = null fun getSourceInfo(functionName: String?, script: Script, line: Int, column: Int): SourceInfo? = null fun propertyNamesToString(list: List<String>, quotedAware: Boolean): String // Please, don't hesitate to ask to share some generic implementations. Don't reinvent the wheel and keep in mind - user expects the same UI across all IDEA-based IDEs. fun computeObjectPresentation(value: ObjectValue, variable: Variable, context: VariableContext, node: XValueNode, icon: Icon) fun computeArrayPresentation(value: Value, variable: Variable, context: VariableContext, node: XValueNode, icon: Icon) fun createFrameEvaluator(frame: CallFrameView): XDebuggerEvaluator = PromiseDebuggerEvaluator(frame) /** * [org.jetbrains.debugger.values.FunctionValue] is special case and handled by SDK */ fun canNavigateToSource(variable: Variable, context: VariableContext): Boolean = false fun computeSourcePosition(name: String, value: Value?, variable: Variable, context: VariableContext, navigatable: XNavigatable) { } fun computeInlineDebuggerData(name: String, variable: Variable, context: VariableContext, callback: XInlineDebuggerDataCallback): ThreeState = ThreeState.UNSURE // return null if you don't need to add additional properties fun computeAdditionalObjectProperties(value: ObjectValue, variable: Variable, context: VariableContext, node: XCompositeNode): Promise<Any?>? = null fun getMemberFilter(context: VariableContext): Promise<MemberFilter> fun transformErrorOnGetUsedReferenceValue(value: Value?, error: String?): Value? = value fun isInLibraryContent(sourceInfo: SourceInfo, script: Script?): Boolean = false fun computeReceiverVariable(context: VariableContext, callFrame: CallFrame, node: XCompositeNode): Promise<*> } open class PromiseDebuggerEvaluator(protected val context: VariableContext) : XDebuggerEvaluator() { final override fun evaluate(expression: String, callback: XDebuggerEvaluator.XEvaluationCallback, expressionPosition: XSourcePosition?) { try { evaluate(expression, expressionPosition) .onSuccess { callback.evaluated(VariableView(VariableImpl(expression, it.value), context)) } .onError { callback.errorOccurred(it.message ?: it.toString()) } } catch (e: Throwable) { LOG.error(e) callback.errorOccurred(e.toString()) return } } protected open fun evaluate(expression: String, expressionPosition: XSourcePosition?): Promise<EvaluateResult> = context.evaluateContext.evaluate(expression) }
apache-2.0
379d350d3837240f88be6be53d3c1486
46.837838
170
0.785815
4.712383
false
false
false
false
ilya-g/intellij-markdown
src/org/intellij/markdown/parser/markerblocks/impl/CodeBlockMarkerBlock.kt
1
3375
package org.intellij.markdown.parser.markerblocks.impl import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.markerblocks.MarkdownParserUtil import org.intellij.markdown.parser.markerblocks.MarkerBlock import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl import org.intellij.markdown.parser.sequentialparsers.SequentialParser public class CodeBlockMarkerBlock(myConstraints: MarkdownConstraints, private val productionHolder: ProductionHolder, startPosition: LookaheadText.Position) : MarkerBlockImpl(myConstraints, productionHolder.mark()) { init { productionHolder.addProduction(listOf(SequentialParser.Node( startPosition.offset..startPosition.nextLineOrEofOffset, MarkdownTokenTypes.CODE_LINE))) } override fun allowsSubBlocks(): Boolean = false override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = true private var realInterestingOffset = -1 override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int { return pos.nextLineOrEofOffset } override fun getDefaultAction(): MarkerBlock.ClosingAction { return MarkerBlock.ClosingAction.DONE } override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult { if (pos.offset < realInterestingOffset) { return MarkerBlock.ProcessingResult.CANCEL } // Eat everything if we're on code line if (pos.offsetInCurrentLine != -1) { return MarkerBlock.ProcessingResult.CANCEL } assert(pos.char == '\n') val nonemptyPos = MarkdownParserUtil.findNonEmptyLineWithSameConstraints(constraints, pos) ?: return MarkerBlock.ProcessingResult.DEFAULT val nextConstraints = MarkdownConstraints.fromBase(nonemptyPos, constraints) val shifted = nonemptyPos.nextPosition(1 + nextConstraints.getCharsEaten(nonemptyPos.currentLine)) val nonWhitespace = shifted?.nextPosition(shifted.charsToNonWhitespace() ?: 0) ?: return MarkerBlock.ProcessingResult.DEFAULT if (!MarkdownParserUtil.hasCodeBlockIndent(nonWhitespace, nextConstraints)) { return MarkerBlock.ProcessingResult.DEFAULT } else { // We'll add the current line anyway val nextLineConstraints = MarkdownConstraints.fromBase(pos, constraints) val nodeRange = pos.offset + 1 + nextLineConstraints.getCharsEaten(pos.currentLine)..pos.nextLineOrEofOffset if (nodeRange.endInclusive - nodeRange.start > 0) { productionHolder.addProduction(listOf(SequentialParser.Node( nodeRange, MarkdownTokenTypes.CODE_LINE))) } realInterestingOffset = pos.nextLineOrEofOffset return MarkerBlock.ProcessingResult.CANCEL } } override fun getDefaultNodeType(): IElementType { return MarkdownElementTypes.CODE_BLOCK } }
apache-2.0
a361aa648f6f0de8ecdcfdbbf64f2b8c
42.831169
133
0.72237
5.730051
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveForLoopIndicesIntention.kt
1
2657
// 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.intentions import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.editor.fixers.range import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtForExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe @Suppress("DEPRECATION") class RemoveForLoopIndicesInspection : IntentionBasedInspection<KtForExpression>( RemoveForLoopIndicesIntention::class, KotlinBundle.message("index.is.not.used.in.the.loop.body") ), CleanupLocalInspectionTool class RemoveForLoopIndicesIntention : SelfTargetingRangeIntention<KtForExpression>( KtForExpression::class.java, KotlinBundle.lazyMessage("remove.indices.in.for.loop") ) { private val WITH_INDEX_NAME = "withIndex" private val WITH_INDEX_FQ_NAMES: Set<String> by lazy { sequenceOf("collections", "sequences", "text", "ranges").map { "kotlin.$it.$WITH_INDEX_NAME" }.toSet() } override fun applicabilityRange(element: KtForExpression): TextRange? { val loopRange = element.loopRange as? KtDotQualifiedExpression ?: return null val multiParameter = element.destructuringDeclaration ?: return null if (multiParameter.entries.size != 2) return null val resolvedCall = loopRange.resolveToCall() if (resolvedCall?.resultingDescriptor?.fqNameUnsafe?.asString() !in WITH_INDEX_FQ_NAMES) return null val indexVar = multiParameter.entries[0] if (ReferencesSearch.search(indexVar).any()) return null return indexVar.nameIdentifier?.range } override fun applyTo(element: KtForExpression, editor: Editor?) { val multiParameter = element.destructuringDeclaration!! val loopRange = element.loopRange as KtDotQualifiedExpression val elementVar = multiParameter.entries[1] val loop = KtPsiFactory(element).createExpressionByPattern("for ($0 in _) {}", elementVar.text) as KtForExpression element.loopParameter!!.replace(loop.loopParameter!!) loopRange.replace(loopRange.receiverExpression) } }
apache-2.0
c0e67bbc4aecf8d185f2a7ec066f5d8e
44.810345
122
0.773052
4.778777
false
false
false
false
dahlstrom-g/intellij-community
python/src/com/jetbrains/python/sdk/poetry/PyAddNewPoetryPanel.kt
7
8152
// 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.sdk.poetry import com.intellij.application.options.ModuleListCellRenderer import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBTextField import com.intellij.util.PlatformUtils import com.intellij.util.text.nullize import com.intellij.util.ui.FormBuilder import com.jetbrains.python.PyBundle import com.jetbrains.python.PySdkBundle import com.jetbrains.python.sdk.* import com.jetbrains.python.sdk.add.PyAddNewEnvPanel import com.jetbrains.python.sdk.add.PySdkPathChoosingComboBox import com.jetbrains.python.sdk.add.addInterpretersAsync import java.awt.BorderLayout import java.awt.Dimension import java.awt.event.ItemEvent import java.io.File import java.nio.file.Files import java.util.concurrent.ConcurrentHashMap import javax.swing.Icon import javax.swing.JComboBox import javax.swing.event.DocumentEvent /** * The UI panel for adding the poetry interpreter for the project. * * @author vlan */ /** * This source code is edited by @koxudaxi Koudai Aono <[email protected]> */ class PyAddNewPoetryPanel(private val project: Project?, private val module: Module?, private val existingSdks: List<Sdk>, override var newProjectPath: String?, context: UserDataHolder) : PyAddNewEnvPanel() { override val envName = "Poetry" override val panelName: String get() = "Poetry Environment" // TODO: Need a extension point override val icon: Icon = POETRY_ICON private val moduleField: JComboBox<Module> private val baseSdkField = PySdkPathChoosingComboBox() init { addInterpretersAsync(baseSdkField) { val sdks = findBaseSdks(existingSdks, module, context).takeIf { it.isNotEmpty() } ?: detectSystemWideSdks(module, existingSdks, context) sdks.filterNot { PythonSdkUtil.isInvalid(it) || it.isPoetry } } } private val installPackagesCheckBox = JBCheckBox("Install packages from pyproject.toml").apply { isVisible = projectPath?.let { StandardFileSystems.local().findFileByPath(it)?.findChild(PY_PROJECT_TOML)?.let { file -> getPyProjectTomlForPoetry(file) } } != null isSelected = isVisible } private val poetryPathField = TextFieldWithBrowseButton().apply { addBrowseFolderListener(null, null, null, FileChooserDescriptorFactory.createSingleFileDescriptor()) val field = textField as? JBTextField ?: return@apply detectPoetryExecutable()?.let { field.emptyText.text = "Auto-detected: ${it.absolutePath}" } PropertiesComponent.getInstance().poetryPath?.let { field.text = it } } init { layout = BorderLayout() val modules = allModules(project) moduleField = ComboBox(modules.toTypedArray()).apply { renderer = ModuleListCellRenderer() preferredSize = Dimension(Int.MAX_VALUE, preferredSize.height) addItemListener { if (it.stateChange == ItemEvent.SELECTED) { update() } } } poetryPathField.textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { update() } }) val builder = FormBuilder.createFormBuilder().apply { if (module == null && modules.size > 1) { val associatedObjectLabel = if (PlatformUtils.isPyCharm()) { PyBundle.message("python.sdk.poetry.associated.module") } else { PyBundle.message("python.sdk.poetry.associated.project") } addLabeledComponent(associatedObjectLabel, moduleField) } addLabeledComponent(PySdkBundle.message("python.venv.base.label"), baseSdkField) addComponent(installPackagesCheckBox) addLabeledComponent(PyBundle.message("python.sdk.poetry.executable"), poetryPathField) } add(builder.panel, BorderLayout.NORTH) update() } override fun getOrCreateSdk(): Sdk? { PropertiesComponent.getInstance().poetryPath = poetryPathField.text.nullize() return setupPoetrySdkUnderProgress(project, selectedModule, existingSdks, newProjectPath, baseSdkField.selectedSdk?.homePath, installPackagesCheckBox.isSelected)?.apply { PySdkSettings.instance.preferredVirtualEnvBaseSdk = baseSdkField.selectedSdk?.homePath } } override fun validateAll(): List<ValidationInfo> = listOfNotNull(validatePoetryExecutable(), validatePoetryIsNotAdded()) override fun addChangeListener(listener: Runnable) { poetryPathField.textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { listener.run() } }) super.addChangeListener(listener) } /** * Updates the view according to the current state of UI controls. */ private fun update() { selectedModule?.let { installPackagesCheckBox.isEnabled = it.pyProjectToml != null } } /** * The effective module for which we add a new environment. */ private val selectedModule: Module? get() = module ?: try { moduleField.selectedItem } catch (e: NullPointerException) { null } as? Module /** * Checks if `poetry` is available on `$PATH`. */ private fun validatePoetryExecutable(): ValidationInfo? { val executable = poetryPathField.text.nullize()?.let { File(it) } ?: detectPoetryExecutable() ?: return ValidationInfo(PyBundle.message("python.sdk.poetry.executable.not.found")) return when { !executable.exists() -> ValidationInfo(PyBundle.message("python.sdk.file.not.found", executable.absolutePath)) !Files.isExecutable(executable.toPath()) || !executable.isFile -> ValidationInfo( PyBundle.message("python.sdk.cannot.execute", executable.absolutePath)) else -> null } } private val isPoetry by lazy { existingSdks.filter { it.isPoetry }.associateBy { it.associatedModulePath } } private val homePath by lazy { existingSdks.associateBy { it.homePath } } private val pythonExecutable = ConcurrentHashMap<String, String>() private val venvInProject = ConcurrentHashMap<String, Boolean?>() private fun computePythonExecutable(homePath: String): String? { return pythonExecutable.getOrPut(homePath) { getPythonExecutable(homePath) } } private fun isVenvInProject(path: String): Boolean? { return venvInProject.getOrPut(path) { isVirtualEnvsInProject(path) } } /** * Checks if the poetry for the project hasn't been already added. */ private fun validatePoetryIsNotAdded(): ValidationInfo? { val path = projectPath ?: return null val addedPoetry = isPoetry[path] ?: return null if (addedPoetry.homeDirectory == null) return null // TODO: check existing envs if (isVenvInProject(path) == false) return null val inProjectEnvExecutable = inProjectEnvPath?.let { computePythonExecutable(it) } ?: return null val inProjectEnv = homePath[inProjectEnvExecutable] ?: return null return ValidationInfo("Poetry interpreter has been already added, select '${inProjectEnv.name}'") } /** * The effective project path for the new project or for the existing project. */ private val projectPath: String? get() = newProjectPath ?: selectedModule?.basePath ?: project?.basePath private val inProjectEnvDir = ".venv" private val inProjectEnvPath: String? get() = projectPath?.let { it + File.separator + inProjectEnvDir } }
apache-2.0
0dfafa133989775472b769d1a5dae3a5
36.054545
140
0.722399
4.674312
false
false
false
false
dahlstrom-g/intellij-community
tools/intellij.ide.starter/src/com/intellij/ide/starter/path/IDEDataPaths.kt
3
2953
package com.intellij.ide.starter.path import com.intellij.ide.starter.ci.CIServer import com.intellij.ide.starter.di.di import com.intellij.ide.starter.utils.FileSystem.getFileOrDirectoryPresentableSize import com.intellij.ide.starter.utils.createInMemoryDirectory import com.intellij.ide.starter.utils.logOutput import org.kodein.di.direct import org.kodein.di.instance import java.io.Closeable import java.nio.file.Files import java.nio.file.Path import kotlin.io.path.createDirectories import kotlin.io.path.div import kotlin.io.path.exists import kotlin.streams.toList class IDEDataPaths( private val testHome: Path, private val inMemoryRoot: Path? ) : Closeable { companion object { fun createPaths(testName: String, testHome: Path, useInMemoryFs: Boolean): IDEDataPaths { testHome.toFile().deleteRecursively() testHome.createDirectories() val inMemoryRoot = if (useInMemoryFs) { createInMemoryDirectory("ide-integration-test-$testName") } else { null } return IDEDataPaths(testHome = testHome, inMemoryRoot = inMemoryRoot) } } val logsDir = (testHome / "log").createDirectories() val reportsDir = (testHome / "reports").createDirectories() val snapshotsDir = (testHome / "snapshots").createDirectories() val tempDir = (testHome / "temp").createDirectories() // Directory used to store TeamCity artifacts. To make sure the TeamCity publishes all artifacts // files added to this directory must not be removed until the end of the tests execution . val teamCityArtifacts = (testHome / "team-city-artifacts").createDirectories() val configDir = ((inMemoryRoot ?: testHome) / "config").createDirectories() val systemDir = ((inMemoryRoot ?: testHome) / "system").createDirectories() val pluginsDir = (testHome / "plugins").createDirectories() override fun close() { if (inMemoryRoot != null) { try { inMemoryRoot.toFile().deleteRecursively() } catch (e: Exception) { logOutput("! Failed to unmount in-memory FS at $inMemoryRoot") e.stackTraceToString().lines().forEach { logOutput(" $it") } } } if (di.direct.instance<CIServer>().isBuildRunningOnCI) { deleteDirectories() } } private fun deleteDirectories() { val toDelete = getDirectoriesToDeleteAfterTest().filter { it.exists() } if (toDelete.isNotEmpty()) { logOutput(buildString { appendLine("Removing directories of $testHome") toDelete.forEach { path -> appendLine(" $path: ${path.getFileOrDirectoryPresentableSize()}") } }) } toDelete.forEach { runCatching { it.toFile().deleteRecursively() } } } private fun getDirectoriesToDeleteAfterTest() = if (testHome.exists()) { Files.list(testHome).use { it.toList() } - setOf(teamCityArtifacts) } else { emptyList() } override fun toString(): String = "IDE Test Paths at $testHome" }
apache-2.0
c6d04c743c2817f835190eb181b001de
32.191011
98
0.703014
4.261183
false
true
false
false
MasoodFallahpoor/InfoCenter
InfoCenter/src/main/java/com/fallahpoor/infocenter/fragments/bluetooth/BluetoothFragment.kt
1
4624
/* Copyright (C) 2014-2016 Masood Fallahpoor This file is part of Info Center. Info Center 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. Info Center 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 Info Center. If not, see <http://www.gnu.org/licenses/>. */ package com.fallahpoor.infocenter.fragments.bluetooth import android.annotation.TargetApi import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothManager import android.content.Context import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import com.fallahpoor.infocenter.R import com.fallahpoor.infocenter.adapters.CustomArrayAdapter import com.fallahpoor.infocenter.adapters.ListItem import com.fallahpoor.infocenter.adapters.OrdinaryListItem import kotlinx.android.synthetic.main.fragment_others.* import java.util.* /** * BluetoothFragment displays some information about the Bluetooth of the * device including its status, name, address and so on. */ class BluetoothFragment : Fragment(), Observer { private lateinit var bluetoothObservable: BluetoothObservable private var hasBluetooth: Boolean = false private val listItems: ArrayList<ListItem> get() { return ArrayList<ListItem>().apply { add( OrdinaryListItem( getString(R.string.item_status), bluetoothObservable.status ) ) add( OrdinaryListItem( getString(R.string.blu_item_address), bluetoothObservable.address ) ) add( OrdinaryListItem( getString(R.string.blu_item_name), bluetoothObservable.name ) ) add( OrdinaryListItem( getString(R.string.blu_item_paired_devices), bluetoothObservable.pairedDevices ) ) } } private val bluetoothAdapter: BluetoothAdapter? @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) get() { return if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1) { BluetoothAdapter.getDefaultAdapter() } else { (activity!!.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) return inflater.inflate(R.layout.fragment_others, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) hasBluetooth = hasBluetoothFeature() populateListView(textView) } private fun populateListView(msgTextView: TextView) { if (hasBluetooth) { bluetoothObservable = BluetoothObservable(activity!!) } else { listView.emptyView = msgTextView } } override fun onResume() { super.onResume() if (hasBluetooth) { bluetoothObservable.addObserver(this) bluetoothObservable.enableBluetoothUpdates() updateListView() } } override fun onPause() { super.onPause() if (hasBluetooth) { bluetoothObservable.disableBluetoothUpdates() bluetoothObservable.deleteObserver(this) } } private fun hasBluetoothFeature(): Boolean { return bluetoothAdapter != null } private fun updateListView() { listView.adapter = CustomArrayAdapter(activity, listItems) } override fun update(observable: Observable, o: Any) { updateListView() } }
gpl-3.0
ffc58b724c5620c61096a859f433006c
30.243243
100
0.634083
5.154961
false
false
false
false
JuliaSoboleva/SmartReceiptsLibrary
automatic_backups/src/notFloss/java/co/smartreceipts/automatic_backups/drive/DriveAccountHelper.kt
2
5136
package co.smartreceipts.automatic_backups.drive import android.content.Context import android.content.Intent import co.smartreceipts.analytics.log.Logger import com.google.android.gms.auth.GoogleAuthUtil import com.google.android.gms.auth.UserRecoverableAuthException import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.api.Scope import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException import com.google.api.client.http.HttpRequest import com.google.api.client.http.HttpRequestInitializer import com.google.api.client.http.javanet.NetHttpTransport import com.google.api.client.json.gson.GsonFactory import com.google.api.services.drive.Drive import com.google.api.services.drive.DriveScopes import com.hadisatrio.optional.Optional import io.reactivex.Single import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import java.util.* import javax.inject.Inject class DriveAccountHelper @Inject constructor() { val signInIntentsSubject: Subject<Intent> = PublishSubject.create() val errorIntentsSubject: Subject<Intent> = PublishSubject.create() fun signIn(context: Context): Single<Optional<DriveServiceHelper>> { val signInAccount = GoogleSignIn.getLastSignedInAccount(context) if (signInAccount == null) { val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .requestScopes( Scope(DriveScopes.DRIVE_FILE), Scope(DriveScopes.DRIVE_APPDATA) ) .build() val googleSignInClient = GoogleSignIn.getClient(context, signInOptions) signInIntentsSubject.onNext(googleSignInClient.signInIntent) return Single.just(Optional.absent()) } else { return onGoogleSignInAccountReady(signInAccount, context) .map { Optional.of(it) } } } private fun onGoogleSignInAccountReady(signInAccount: GoogleSignInAccount, context: Context): Single<DriveServiceHelper> { return Single.fromCallable { val scopes = "oauth2:" + DriveScopes.DRIVE_APPDATA + " " + DriveScopes.DRIVE_FILE GoogleAuthUtil.getToken(context, signInAccount.account, scopes) }.doOnError { throwable -> Logger.error(this@DriveAccountHelper, "Failed to authenticate user with status: {}", throwable.message) when (throwable) { is UserRecoverableAuthException -> errorIntentsSubject.onNext(throwable.intent) is UserRecoverableAuthIOException -> errorIntentsSubject.onNext(throwable.intent) } } .subscribeOn(Schedulers.io()) .map { token -> getDriveServiceHelper(signInAccount, context) } } private fun getDriveServiceHelper(signInAccount: GoogleSignInAccount, context: Context): DriveServiceHelper { val scopes: MutableCollection<String> = ArrayList() scopes.add(DriveScopes.DRIVE_FILE) scopes.add(DriveScopes.DRIVE_APPDATA) // Use the authenticated account to sign in to the Drive service. val credential: GoogleAccountCredential = GoogleAccountCredential.usingOAuth2(context, scopes) credential.selectedAccount = signInAccount.account val googleDriveService = Drive.Builder( NetHttpTransport(), GsonFactory(), setHttpTimeout(credential) ) .setApplicationName("Smart Receipts") .build() // The DriveServiceHelper encapsulates all REST API and SAF functionality. // Its instantiation is required before handling any onClick actions. return DriveServiceHelper(context, googleDriveService) } fun processResultIntent(intent: Intent?, context: Context): Single<DriveServiceHelper> { val signInAccountTask = GoogleSignIn.getSignedInAccountFromIntent(intent) if (signInAccountTask.isSuccessful) { Logger.info(this, "Successfully authorized our Google Drive account") val result = signInAccountTask.result if (result != null) { return onGoogleSignInAccountReady(result, context) } } return Single.error(Exception("Failed to successfully authorize our Google Drive account")) } private fun setHttpTimeout(requestInitializer: HttpRequestInitializer): HttpRequestInitializer? { return HttpRequestInitializer { httpRequest: HttpRequest -> requestInitializer.initialize(httpRequest) httpRequest.connectTimeout = 3 * 60000 // 3 minutes connect timeout httpRequest.readTimeout = 3 * 60000 // 3 minutes read timeout } } }
agpl-3.0
d0177f9479f60e8656c430027a21b862
44.061404
126
0.706776
4.896092
false
false
false
false
MGaetan89/ShowsRage
app/src/androidTest/kotlin/com/mgaetan89/showsrage/extension/realm/RealmExtension_SaveShowTest.kt
1
2807
package com.mgaetan89.showsrage.extension.realm import android.support.test.runner.AndroidJUnit4 import com.mgaetan89.showsrage.extension.getShow import com.mgaetan89.showsrage.extension.getShows import com.mgaetan89.showsrage.extension.saveShow import com.mgaetan89.showsrage.model.Quality import com.mgaetan89.showsrage.model.Show import com.mgaetan89.showsrage.validateRealmList import io.realm.RealmList import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class RealmExtension_SaveShowTest : RealmTest() { @Before fun before() { assertThat(this.getShows()).hasSize(83) } @Test fun saveShow() { val show = Show().apply { this.airs = "Monday 9:00 PM" this.genre = RealmList("Action", "Drama") this.imdbId = "tt123456" this.indexerId = 42 this.location = "/home/videos/Show Name" this.qualityDetails = null this.seasonList = RealmList("2", "1") } this.realm.saveShow(show) this.validateShow(show.airs, show.genre, show.imdbId, show.indexerId, show.location, show.qualityDetails, show.seasonList) } @Test fun saveShow_update() { val show = Show().apply { this.airs = "Thursday 10:00 PM" this.genre = RealmList("Action", "Comedy") this.imdbId = "tt1234567" this.indexerId = 42 this.location = "/home/videos/Show Name" this.qualityDetails = Quality().apply { this.archive = RealmList("fullhdwebdl", "fullhdbluray") this.indexerId = 42 this.initial = RealmList("fullhdtv") } this.seasonList = RealmList("3", "2", "1") } this.realm.saveShow(show) this.validateShow(show.airs, show.genre, show.imdbId, show.indexerId, show.location, show.qualityDetails, show.seasonList) } private fun getShow(indexerId: Int) = this.realm.getShow(indexerId) private fun getShows() = this.realm.getShows(null) private fun validateShow(airs: String?, genre: RealmList<String>?, imdbId: String?, indexerId: Int, location: String?, qualityDetails: Quality?, seasonList: RealmList<String>?) { assertThat(this.getShows()).hasSize(84) val show = this.getShow(indexerId) assertThat(show).isNotNull() assertThat(show!!.airs).isEqualTo(airs) validateRealmList(show.genre, genre) assertThat(show.imdbId).isEqualTo(imdbId) assertThat(show.indexerId).isEqualTo(indexerId) assertThat(show.location).isEqualTo(location) if (qualityDetails == null) { assertThat(show.qualityDetails).isNull() } else { assertThat(show.qualityDetails).isNotNull() show.qualityDetails!!.let { validateRealmList(it.archive, qualityDetails.archive) assertThat(it.indexerId).isEqualTo(indexerId) validateRealmList(it.initial, qualityDetails.initial) } } validateRealmList(show.seasonList, seasonList) } }
apache-2.0
fe3603d7e143b990416ed32ef94f2679
28.547368
179
0.740648
3.394196
false
true
false
false
paplorinc/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/callReferenceImpl.kt
2
2693
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.impl import com.intellij.psi.PsiType import com.intellij.psi.ResolveState import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.resolveKinds import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyMethodCallReference import org.jetbrains.plugins.groovy.lang.resolve.processReceiverType import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyRValueProcessor import org.jetbrains.plugins.groovy.lang.resolve.processors.MethodProcessor fun GroovyMethodCallReference.resolveImpl(incomplete: Boolean): Collection<GroovyResolveResult> { val receiver = receiver ?: TypesUtil.getJavaLangObject(element) val methodName = methodName fun resolveWithArguments(args: List<PsiType?>?): Array<out GroovyResolveResult> { return if (args == null) { ResolveUtil.getMethodCandidates(receiver, methodName, element, incomplete) } else { ResolveUtil.getMethodCandidates(receiver, methodName, element, incomplete, *args.toTypedArray()) } } val arguments = arguments?.map { it?.type } val candidates = resolveWithArguments(arguments) val tupleType = arguments?.singleOrNull() as? GrTupleType if (tupleType == null || candidates.any { it.isValidResult }) { return candidates.toList() } return resolveWithArguments(tupleType.componentTypes).toList() } fun GroovyMethodCallReference.resolveImpl2(incomplete: Boolean): Collection<GroovyResolveResult> { val place = element val receiver = receiver ?: TypesUtil.getJavaLangObject(place) val methodName = methodName val arguments = if (incomplete) null else arguments val state = ResolveState.initial() val methodProcessor = MethodProcessor(methodName, place, arguments, PsiType.EMPTY_ARRAY) receiver.processReceiverType(methodProcessor, state, place) methodProcessor.applicableCandidates?.let { return it } val propertyProcessor = GroovyRValueProcessor(methodName, place, resolveKinds(true)) receiver.processReceiverType(propertyProcessor, state, place) val properties = propertyProcessor.results if (properties.size == 1) { return properties } val methods = filterBySignature(filterByArgumentsCount(methodProcessor.allCandidates, arguments)) return methods + properties }
apache-2.0
986a29d82368360b4f6c352658f0feab
43.147541
140
0.796881
4.510888
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/execution/filters/ShowTextPopupHyperlinkInfo.kt
11
2106
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.filters import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileTypes.FileTypes import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.WindowManager import com.intellij.ui.EditorTextField import java.awt.Dimension import javax.swing.ScrollPaneConstants /** * A console hyperlink, which shows a popup with the given text on a click. * Useful for filters - to create links for viewing contents of argument files. * * @see ArgumentFileFilter */ class ShowTextPopupHyperlinkInfo(private val title: String, private val text: String) : HyperlinkInfo { override fun navigate(project: Project) { ApplicationManager.getApplication().invokeLater { val document = EditorFactory.getInstance().createDocument(StringUtil.convertLineSeparators(text)) val textField = object : EditorTextField(document, project, FileTypes.PLAIN_TEXT, true, false) { override fun createEditor(): EditorEx { val editor = super.createEditor() editor.scrollPane.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED editor.scrollPane.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED editor.settings.isUseSoftWraps = true return editor } } WindowManager.getInstance().getFrame(project)?.size?.let { textField.preferredSize = Dimension(it.width / 2, it.height / 2) } JBPopupFactory.getInstance() .createComponentPopupBuilder(textField, textField) .setTitle(title) .setResizable(true) .setMovable(true) .setRequestFocus(true) .createPopup() .showCenteredInCurrentWindow(project) } } }
apache-2.0
440db223625c01825bfb26719a908554
41.14
140
0.748813
4.764706
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/openapi/util/registry/RegistryToAdvancedSettingsMigration.kt
1
2963
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.util.registry import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.editor.impl.TabCharacterPaintMode import com.intellij.openapi.options.advanced.AdvancedSettingBean import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.project.Project import com.intellij.openapi.startup.ProjectPostStartupActivity private class RegistryToAdvancedSettingsMigration : ProjectPostStartupActivity { override suspend fun execute(project: Project) { val propertyName = "registry.to.advanced.settings.migration.build" val lastMigratedVersion = PropertiesComponent.getInstance().getValue(propertyName) val currentVersion = ApplicationInfo.getInstance().build.asString() if (currentVersion == lastMigratedVersion) { return } val userProperties = Registry.getInstance().userProperties for (setting in AdvancedSettingBean.EP_NAME.extensions) { if (setting.id == "editor.tab.painting") { migrateEditorTabPainting(userProperties, setting) continue } if (setting.id == "vcs.process.ignored") { migrateVcsIgnoreProcessing(userProperties, setting) continue } val userProperty = userProperties[setting.id] ?: continue try { AdvancedSettings.getInstance().setSetting(setting.id, setting.valueFromString(userProperty), setting.type()) userProperties.remove(setting.id) } catch (e: IllegalArgumentException) { continue } } PropertiesComponent.getInstance().setValue(propertyName, currentVersion) } private fun migrateEditorTabPainting(userProperties: MutableMap<String, String>, setting: AdvancedSettingBean) { val mode = if (userProperties["editor.old.tab.painting"] == "true") { userProperties.remove("editor.old.tab.painting") TabCharacterPaintMode.LONG_ARROW } else if (userProperties["editor.arrow.tab.painting"] == "true") { userProperties.remove("editor.arrow.tab.painting") TabCharacterPaintMode.ARROW } else { return } AdvancedSettings.getInstance().setSetting(setting.id, mode, setting.type()) } private fun migrateVcsIgnoreProcessing(userProperties: MutableMap<String, String>, setting: AdvancedSettingBean) { if (userProperties["git.process.ignored"] == "false") { userProperties.remove("git.process.ignored") } else if (userProperties["hg4idea.process.ignored"] == "false") { userProperties.remove("hg4idea.process.ignored") } else if (userProperties["p4.process.ignored"] == "false") { userProperties.remove("p4.process.ignored") } else { return } AdvancedSettings.getInstance().setSetting(setting.id, false, setting.type()) } }
apache-2.0
025460f5ae3f145405634baf2eacc5e2
38.506667
120
0.729328
4.593798
false
false
false
false
apollographql/apollo-android
apollo-http-cache/src/test/kotlin/com/apollographql/apollo3/cache/http/internal/CachingHttpInterceptorTest.kt
1
4943
package com.apollographql.apollo3.cache.http.internal import com.apollographql.apollo3.api.http.HttpMethod import com.apollographql.apollo3.api.http.HttpRequest import com.apollographql.apollo3.api.http.HttpResponse import com.apollographql.apollo3.api.http.valueOf import com.apollographql.apollo3.cache.http.CachingHttpInterceptor import com.apollographql.apollo3.exception.HttpCacheMissException import com.apollographql.apollo3.mockserver.MockResponse import com.apollographql.apollo3.mockserver.MockServer import com.apollographql.apollo3.network.http.DefaultHttpEngine import com.apollographql.apollo3.network.http.HttpInterceptorChain import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import java.io.File import kotlin.test.assertEquals import kotlin.test.assertFailsWith class CachingHttpInterceptorTest { private lateinit var mockServer: MockServer private lateinit var interceptor: CachingHttpInterceptor private lateinit var chain: HttpInterceptorChain @Before fun before() { mockServer = MockServer() val dir = File("build/httpCache") dir.deleteRecursively() interceptor = CachingHttpInterceptor(dir, Long.MAX_VALUE) chain = TestHttpInterceptorChain() } @Test fun successResponsesAreCached() { mockServer.enqueue(MockResponse(statusCode = 200, body = "success")) runBlocking { val request = HttpRequest.Builder( method = HttpMethod.Get, url = mockServer.url(), ).build() var response = interceptor.intercept(request, chain) assertEquals("success", response.body?.readUtf8()) // 2nd request should hit the cache response = interceptor.intercept( request.newBuilder() .addHeader(CachingHttpInterceptor.CACHE_FETCH_POLICY_HEADER, CachingHttpInterceptor.CACHE_ONLY) .build(), chain ) assertEquals("success", response.body?.readUtf8()) assertEquals("true", response.headers.valueOf(CachingHttpInterceptor.FROM_CACHE)) } } @Test fun failureResponsesAreNotCached() { mockServer.enqueue(MockResponse(statusCode = 500, body = "error")) runBlocking { val request = HttpRequest.Builder( method = HttpMethod.Get, url = mockServer.url(), ).build() // Warm the cache val response = interceptor.intercept(request, chain) assertEquals("error", response.body?.readUtf8()) // 2nd request should trigger a cache miss assertFailsWith(HttpCacheMissException::class) { interceptor.intercept( request.newBuilder() .addHeader(CachingHttpInterceptor.CACHE_FETCH_POLICY_HEADER, CachingHttpInterceptor.CACHE_ONLY) .build(), chain ) } } } @Test fun timeoutWorks() { mockServer.enqueue(MockResponse(statusCode = 200, body = "success")) runBlocking { val request = HttpRequest.Builder( method = HttpMethod.Get, url = mockServer.url(), ).build() // Warm the cache var response = interceptor.intercept(request, chain) assertEquals("success", response.body?.readUtf8()) // 2nd request should hit the cache response = interceptor.intercept( request.newBuilder() .addHeader(CachingHttpInterceptor.CACHE_FETCH_POLICY_HEADER, CachingHttpInterceptor.CACHE_ONLY) .build(), chain ) assertEquals("success", response.body?.readUtf8()) delay(1000) // 3rd request with a 500ms timeout should miss assertFailsWith(HttpCacheMissException::class) { interceptor.intercept( request.newBuilder() .addHeader(CachingHttpInterceptor.CACHE_FETCH_POLICY_HEADER, CachingHttpInterceptor.CACHE_ONLY) .addHeader(CachingHttpInterceptor.CACHE_EXPIRE_TIMEOUT_HEADER, "500") .build(), chain ) } } } @Test fun cacheInParallel() { val concurrency = 2 repeat(concurrency) { mockServer.enqueue(MockResponse(statusCode = 200, body = "success")) } val jobs = mutableListOf<Job>() runBlocking { repeat(concurrency) { jobs += launch(Dispatchers.IO) { val request = HttpRequest.Builder( method = HttpMethod.Get, url = mockServer.url(), ).build() val response = interceptor.intercept(request, chain) assertEquals("success", response.body?.readUtf8()) } } jobs.forEach { it.join() } } } } private class TestHttpInterceptorChain : HttpInterceptorChain { val engine = DefaultHttpEngine() override suspend fun proceed(request: HttpRequest): HttpResponse { return engine.execute(request) } }
mit
496d6131351938a657f2f4f643a29592
30.685897
111
0.682177
4.721108
false
true
false
false
aquatir/remember_java_api
code-sample-angular-kotlin/code-sample-jwt-token-example/kotlin-backend/src/main/kotlin/codesample/kotlin/jwtexample/security/entity/User.kt
1
1771
package codesample.kotlin.jwtexample.security.entity import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority import java.util.stream.Collectors import javax.persistence.Column import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.JoinColumn import javax.persistence.JoinTable import javax.persistence.ManyToMany import javax.persistence.Table @Entity @Table(name = "USER") class User ( @Column(name = "USERNAME", length = 50, unique = true, nullable = false) val username: String, @Column(name = "PASSWORD", length = 100, nullable = false) val password: String, @Column(name = "NAME", length = 100) val name: String, @ManyToMany(fetch = FetchType.EAGER) @JoinTable( name = "USER_AUTHORITY", joinColumns = [JoinColumn(name = "USER_ID", referencedColumnName = "ID")], inverseJoinColumns = [JoinColumn(name = "AUTHORITY_ID", referencedColumnName = "ID")]) val authorities: List<Authority> = emptyList(), @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID") var id: Long = 0, @Column(name="REFRESH_TOKEN", length = 200) var refreshToken: String = "" ) { val grantedAuthorities: Collection<GrantedAuthority> get() { return authorities.stream() .map { it -> SimpleGrantedAuthority(it.name.name) } .collect(Collectors.toList()) } }
mit
311deda6e0597b0e28e052e68461d63f
33.076923
102
0.647092
4.685185
false
false
false
false
aohanyao/CodeMall
code/ServerCode/CodeMallServer/src/main/java/com/jjc/mailshop/controller/portal/AddressController.kt
1
3980
package com.jjc.mailshop.controller.portal import com.github.pagehelper.PageInfo import com.jjc.mailshop.common.CheckUserPermissionUtil import com.jjc.mailshop.common.ServerResponse import com.jjc.mailshop.pojo.Shipping import com.jjc.mailshop.service.IAddressService import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.ResponseBody import javax.servlet.http.HttpSession /** * Created by Administrator on 2017/6/15 0015. * <p>收货地址管理的控制器 * //实在是不想写了 */ @Controller @RequestMapping("/shopping/address/") class AddressController { @Autowired var iAddressService: IAddressService? = null /** * 新增地址 * @param shipping 地址对象 */ @ResponseBody @RequestMapping(value = "createAddress.json", method = arrayOf(RequestMethod.POST)) fun createAddress(session: HttpSession, shipping: Shipping): ServerResponse<Shipping>? { //判断用户是否已经登录了 得到用户 val user = CheckUserPermissionUtil.checkUserLoginAndPermission(session).data ?: return ServerResponse.createByErrorMessage("用户未登录") //设置值 shipping.userId = user.id //调用服务 return iAddressService!!.createAddress(shipping) } /** * 修改地址 * @param shipping 地址对象 */ @ResponseBody @RequestMapping(value = "updateAddress.json", method = arrayOf(RequestMethod.POST)) fun updateAddress(session: HttpSession, shipping: Shipping): ServerResponse<Shipping>? { //判断用户是否已经登录了 得到用户 val user = CheckUserPermissionUtil.checkUserLoginAndPermission(session).data ?: return ServerResponse.createByErrorMessage("用户未登录") shipping.id ?: return ServerResponse.createByErrorMessage("id必传") //调用服务 return iAddressService!!.updateAddress(shipping, user.id) } /** * 删除地址 * @param shippingId 地址id */ @ResponseBody @RequestMapping(value = "deleteAddress.json", method = arrayOf(RequestMethod.POST)) fun deleteAddress(session: HttpSession, shippingId: Int): ServerResponse<String>? { //判断用户是否已经登录了 得到用户 val user = CheckUserPermissionUtil.checkUserLoginAndPermission(session).data ?: return ServerResponse.createByErrorMessage("用户未登录") return iAddressService!!.deleteAddress(shippingId, user.id) } /** * 获取单个地址详情 * @param shippingId 地址id */ @ResponseBody @RequestMapping(value = "getAddressDetails.json", method = arrayOf(RequestMethod.POST)) fun getAddressDetails(session: HttpSession, shippingId: Int): ServerResponse<Shipping>? { //判断用户是否已经登录了 得到用户 val user = CheckUserPermissionUtil.checkUserLoginAndPermission(session).data ?: return ServerResponse.createByErrorMessage("用户未登录") return iAddressService!!.getAddressDetails(shippingId, user.id) } /** * 地址列表 * @param userId 用户id */ @ResponseBody @RequestMapping(value = "getAddressList.json", method = arrayOf(RequestMethod.POST)) fun getAddressList(session: HttpSession, userId: String, pageIndex: Int, pageSize: Int): ServerResponse<PageInfo<Shipping>>? { //判断用户是否已经登录了 得到用户 val user = CheckUserPermissionUtil.checkUserLoginAndPermission(session).data ?: return ServerResponse.createByErrorMessage("用户未登录") //调用服务查询 return iAddressService!!.getAddressList(user.id.toString(), pageIndex, pageSize) } }
apache-2.0
543abb34f2bee4164b33326772f22260
33.932692
130
0.707048
4.131968
false
false
false
false
google/oboe
samples/minimaloboe/src/main/java/com/example/minimaloboe/ui/theme/Theme.kt
2
1108
package com.example.minimaloboe.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun SamplesTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
apache-2.0
377a0adee46f5d2cf2c76b7a0df72d45
24.181818
95
0.706679
4.775862
false
false
false
false
JetBrains/teamcity-dnx-plugin
plugin-dotnet-server/src/main/kotlin/jetbrains/buildServer/dotnet/commands/MSBuildCommandType.kt
1
2663
package jetbrains.buildServer.dotnet.commands import jetbrains.buildServer.dotnet.* import jetbrains.buildServer.requirements.Requirement import jetbrains.buildServer.requirements.RequirementQualifier import jetbrains.buildServer.requirements.RequirementType import org.springframework.beans.factory.BeanFactory /** * Provides parameters for dotnet MSBuild command. */ class MSBuildCommandType : CommandType() { override val name: String = DotnetCommandType.MSBuild.id override val editPage: String = "editMSBuildParameters.jsp" override val viewPage: String = "viewMSBuildParameters.jsp" override fun getRequirements(parameters: Map<String, String>, factory: BeanFactory) = sequence { if (isDocker(parameters)) return@sequence var shouldBeWindows = false var hasRequirement = false parameters[DotnetConstants.PARAM_MSBUILD_VERSION]?.let { Tool.tryParse(it)?.let { if (it.type == ToolType.MSBuild) { @Suppress("NON_EXHAUSTIVE_WHEN") when (it.platform) { ToolPlatform.Windows -> { shouldBeWindows = true hasRequirement = when (it.bitness) { ToolBitness.X64 -> { yield(Requirement("MSBuildTools${it.version}.0_x64_Path", null, RequirementType.EXISTS)) true } ToolBitness.X86 -> { yield(Requirement("MSBuildTools${it.version}.0_x86_Path", null, RequirementType.EXISTS)) true } else -> { yield(Requirement(RequirementQualifier.EXISTS_QUALIFIER + "MSBuildTools${it.version}\\.0_.+_Path", null, RequirementType.EXISTS)) true } } } ToolPlatform.Mono -> { yield(Requirement(MonoConstants.CONFIG_PATH, null, RequirementType.EXISTS)) hasRequirement = true } } } } } if (!hasRequirement) { yield(Requirement(DotnetConstants.CONFIG_PATH, null, RequirementType.EXISTS)) } if (shouldBeWindows) { yield(Requirement("teamcity.agent.jvm.os.name", "Windows", RequirementType.STARTS_WITH)) } } }
apache-2.0
2336bea7517408f635c7cf501cca76ce
40.625
165
0.525723
5.594538
false
false
false
false
grover-ws-1/http4k
http4k-core/src/main/kotlin/org/http4k/format/Json.kt
1
3166
package org.http4k.format import org.http4k.asByteBuffer import org.http4k.asString import org.http4k.core.Body import org.http4k.core.ContentType.Companion.APPLICATION_JSON import org.http4k.lens.BiDiBodyLensSpec import org.http4k.lens.BiDiLensSpec import org.http4k.lens.ContentNegotiation import org.http4k.lens.ContentNegotiation.Companion.None import org.http4k.lens.Meta import org.http4k.lens.ParamMeta.ObjectParam import org.http4k.lens.root import java.math.BigDecimal import java.math.BigInteger import java.nio.ByteBuffer /** * This is the contract for all JSON implementations */ interface Json<ROOT : NODE, NODE : Any> { // Contract methods to be implemented fun ROOT.asPrettyJsonString(): String fun ROOT.asCompactJsonString(): String fun String.asJsonObject(): ROOT fun String?.asJsonValue(): NODE fun Int?.asJsonValue(): NODE fun Double?.asJsonValue(): NODE fun Long?.asJsonValue(): NODE fun BigDecimal?.asJsonValue(): NODE fun BigInteger?.asJsonValue(): NODE fun Boolean?.asJsonValue(): NODE fun <T : Iterable<NODE>> T.asJsonArray(): ROOT fun <LIST : Iterable<Pair<String, NODE>>> LIST.asJsonObject(): ROOT fun typeOf(value: NODE): JsonType fun fields(node: NODE): Iterable<Pair<String, NODE>> fun elements(value: NODE): Iterable<NODE> fun text(value: NODE): String // Utility methods - used when we don't know which implementation we are using fun string(value: String): NODE = value.asJsonValue() fun number(value: Int): NODE = value.asJsonValue() fun number(value: Double): NODE = value.asJsonValue() fun number(value: Long): NODE = value.asJsonValue() fun number(value: BigDecimal): NODE = value.asJsonValue() fun number(value: BigInteger): NODE = value.asJsonValue() fun boolean(value: Boolean): NODE = value.asJsonValue() fun <T : NODE> array(value: Iterable<T>): ROOT = value.asJsonArray() fun obj(): ROOT = obj(emptyList()) fun <T : NODE> obj(value: Iterable<Pair<String, T>>): ROOT = value.asJsonObject() fun <T : NODE> obj(vararg fields: Pair<String, T>): ROOT = obj(fields.asIterable()) fun nullNode(): NODE { val i: Int? = null return i.asJsonValue() } fun parse(s: String): ROOT = s.asJsonObject() fun pretty(node: ROOT): String = node.asPrettyJsonString() fun compact(node: ROOT): String = node.asCompactJsonString() fun <IN> lens(spec: BiDiLensSpec<IN, String, String>) = spec.map({ parse(it) }, { compact(it) }) fun <IN> BiDiLensSpec<IN, String, String>.json() = lens(this) fun body(description: String? = null, contentNegotiation: ContentNegotiation = None): BiDiBodyLensSpec<ROOT> = root(listOf(Meta(true, "body", ObjectParam, "body", description)), APPLICATION_JSON, contentNegotiation) .map(ByteBuffer::asString, String::asByteBuffer) .map({ parse(it) }, { compact(it) }) fun Body.Companion.json(description: String? = null, contentNegotiation: ContentNegotiation = None): BiDiBodyLensSpec<ROOT> = body(description, contentNegotiation) } enum class JsonType { Object, Array, String, Integer, Number, Boolean, Null }
apache-2.0
85bef74e47236bd0172869aa78ca6826
41.797297
167
0.706886
3.814458
false
false
false
false
romannurik/muzei
example-unsplash/src/main/java/com/example/muzei/unsplash/UnsplashService.kt
2
2790
/* * Copyright 2018 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.example.muzei.unsplash import androidx.core.net.toUri import okhttp3.OkHttpClient import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.create import retrofit2.http.GET import retrofit2.http.Path import java.io.IOException internal interface UnsplashService { companion object { private fun createService() : UnsplashService { val okHttpClient = OkHttpClient.Builder() .addInterceptor { chain -> var request = chain.request() val url = request.url().newBuilder() .addQueryParameter("client_id", CONSUMER_KEY).build() request = request.newBuilder().url(url).build() chain.proceed(request) } .build() val retrofit = Retrofit.Builder() .baseUrl("https://api.unsplash.com/") .client(okHttpClient) .addConverterFactory(MoshiConverterFactory.create()) .build() return retrofit.create() } @Throws(IOException::class) internal fun popularPhotos(): List<Photo> { return createService().popularPhotos.execute().body() ?: throw IOException("Response was null") } @Throws(IOException::class) internal fun trackDownload(photoId: String) { createService().trackDownload(photoId).execute() } } @get:GET("photos?order_by=popular&per_page=30") val popularPhotos: Call<List<Photo>> @GET("photos/{id}/download") fun trackDownload(@Path("id") photoId: String) : Call<Any> data class Photo( val id: String, val urls: Urls, val description: String?, val user: User, val links: Links) data class Urls(val full: String) data class Links(val html: String) { val webUri get() = "$html$ATTRIBUTION_QUERY_PARAMETERS".toUri() } data class User( val name: String, val links: Links) }
apache-2.0
4d6e530f4f51d38e54ccb57a1c7b6b2a
31.068966
85
0.608961
4.736842
false
false
false
false
zdary/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ModuleVcsDetector.kt
2
4959
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.impl import com.intellij.ProjectTopics import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.ModuleListener import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsDirectoryMapping import com.intellij.openapi.vfs.VirtualFile internal class ModuleVcsDetector(private val project: Project) { private val vcsManager by lazy(LazyThreadSafetyMode.NONE) { (ProjectLevelVcsManager.getInstance(project) as ProjectLevelVcsManagerImpl) } internal class MyPostStartUpActivity : StartupActivity.DumbAware { init { if (ApplicationManager.getApplication().isUnitTestMode) { throw ExtensionNotApplicableException.INSTANCE } } override fun runActivity(project: Project) { val vcsDetector = project.service<ModuleVcsDetector>() val listener = vcsDetector.MyModulesListener() val busConnection = project.messageBus.connect() busConnection.subscribe(ProjectTopics.MODULES, listener) busConnection.subscribe(ProjectTopics.PROJECT_ROOTS, listener) if (vcsDetector.vcsManager.needAutodetectMappings()) { vcsDetector.autoDetectVcsMappings(true) } } } private inner class MyModulesListener : ModuleRootListener, ModuleListener { private val myMappingsForRemovedModules: MutableList<VcsDirectoryMapping> = mutableListOf() override fun beforeRootsChange(event: ModuleRootEvent) { myMappingsForRemovedModules.clear() } override fun rootsChanged(event: ModuleRootEvent) { myMappingsForRemovedModules.forEach { mapping -> vcsManager.removeDirectoryMapping(mapping) } // the check calculates to true only before user has done any change to mappings, i.e. in case modules are detected/added automatically // on start etc (look inside) if (vcsManager.needAutodetectMappings()) { autoDetectVcsMappings(false) } } override fun moduleAdded(project: Project, module: Module) { myMappingsForRemovedModules.removeAll(getMappings(module)) autoDetectModuleVcsMapping(module) } override fun beforeModuleRemoved(project: Project, module: Module) { myMappingsForRemovedModules.addAll(getMappings(module)) } } private fun autoDetectVcsMappings(tryMapPieces: Boolean) { if (vcsManager.haveDefaultMapping() != null) return val usedVcses = mutableSetOf<AbstractVcs?>() val detectedRoots = mutableSetOf<Pair<VirtualFile, AbstractVcs>>() val roots = ModuleManager.getInstance(project).modules.flatMap { it.rootManager.contentRoots.asIterable() }.distinct() for (root in roots) { val moduleVcs = vcsManager.findVersioningVcs(root) if (moduleVcs != null) { detectedRoots.add(Pair(root, moduleVcs)) } usedVcses.add(moduleVcs) // put 'null' for unmapped module } val commonVcs = usedVcses.singleOrNull() if (commonVcs != null) { // Remove existing mappings that will duplicate added <Project> mapping. val rootPaths = roots.map { it.path }.toSet() val additionalMappings = vcsManager.directoryMappings.filter { it.directory !in rootPaths } vcsManager.setAutoDirectoryMappings(additionalMappings + VcsDirectoryMapping.createDefault(commonVcs.name)) } else if (tryMapPieces) { val newMappings = detectedRoots.map { (root, vcs) -> VcsDirectoryMapping(root.path, vcs.name) } vcsManager.setAutoDirectoryMappings(vcsManager.directoryMappings + newMappings) } } private fun autoDetectModuleVcsMapping(module: Module) { if (vcsManager.haveDefaultMapping() != null) return val newMappings = mutableListOf<VcsDirectoryMapping>() for (file in module.rootManager.contentRoots) { val vcs = vcsManager.findVersioningVcs(file) if (vcs != null && vcs !== vcsManager.getVcsFor(file)) { newMappings.add(VcsDirectoryMapping(file.path, vcs.name)) } } if (newMappings.isNotEmpty()) { vcsManager.setAutoDirectoryMappings(vcsManager.directoryMappings + newMappings) } } private fun getMappings(module: Module): List<VcsDirectoryMapping> { return module.rootManager.contentRoots .mapNotNull { root -> vcsManager.directoryMappings.firstOrNull { it.directory == root.path } } } }
apache-2.0
eba5846e99e81de6ed898b11d1d50d8a
39.983471
141
0.752974
4.795938
false
false
false
false
JuliusKunze/kotlin-native
samples/videoplayer/src/main/kotlin/SDLAudio.kt
1
3563
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import kotlinx.cinterop.* import sdl.* import platform.posix.memset import platform.posix.memcpy enum class SampleFormat { INVALID, S16 } data class AudioOutput(val sampleRate: Int, val channels: Int, val sampleFormat: SampleFormat) private fun SampleFormat.toSDLFormat(): SDL_AudioFormat? = when (this) { SampleFormat.S16 -> AUDIO_S16SYS.narrow() SampleFormat.INVALID -> null } class SDLAudio(val player: VideoPlayer) : DisposableContainer() { private val threadData = arena.alloc<IntVar>().ptr private var state = State.STOPPED fun start(audio: AudioOutput) { stop() val audioFormat = audio.sampleFormat.toSDLFormat() ?: return println("SDL Audio: Playing output with ${audio.channels} channels, ${audio.sampleRate} samples per second") memScoped { // TODO: better mechanisms to ensure we have same output format here and in resampler of the decoder. val spec = alloc<SDL_AudioSpec>().apply { freq = audio.sampleRate format = audioFormat channels = audio.channels.narrow() silence = 0 samples = 4096 userdata = threadData callback = staticCFunction(::audioCallback) } threadData.pointed.value = player.workerId val realSpec = alloc<SDL_AudioSpec>() if (SDL_OpenAudio(spec.ptr, realSpec.ptr) < 0) throwSDLError("SDL_OpenAudio") // TODO: ensure real spec matches what we asked for. state = State.PAUSED resume() } } fun pause() { state = state.transition(State.PLAYING, State.PAUSED) { SDL_PauseAudio(1) } } fun resume() { state = state.transition(State.PAUSED, State.PLAYING) { SDL_PauseAudio(0) } } fun stop() { pause() state = state.transition(State.PAUSED, State.STOPPED) { SDL_CloseAudio() } } } // Only set in the audio thread private var decoder: DecoderWorker? = null private fun audioCallback(userdata: COpaquePointer?, buffer: CPointer<Uint8Var>?, length: Int) { // This handler will be invoked in the audio thread, so reinit runtime. konan.initRuntimeIfNeeded() val decoder = decoder ?: DecoderWorker(userdata!!.reinterpret<IntVar>().pointed.value).also { decoder = it } var outPosition = 0 while (outPosition < length) { val frame = decoder.nextAudioFrame(length - outPosition) if (frame != null) { val toCopy = min(length - outPosition, frame.size - frame.position) memcpy(buffer + outPosition, frame.buffer.pointed.data + frame.position, toCopy.signExtend()) frame.unref() outPosition += toCopy } else { // println("Decoder returned nothing!") memset(buffer + outPosition, 0, (length - outPosition).signExtend()) break } } }
apache-2.0
95b0e4fe1e2f2f75d2c2b364aad828f9
34.64
116
0.641033
4.287605
false
false
false
false
InventiDevelopment/AndroidSkeleton
app/src/main/java/cz/inventi/inventiskeleton/domain/post/AddPostUseCase.kt
1
1535
package cz.inventi.inventiskeleton.domain.post import cz.inventi.inventiskeleton.data.post.Post import cz.inventi.inventiskeleton.domain.common.PostExecutionThread import cz.inventi.inventiskeleton.domain.common.ThreadExecutor import cz.inventi.inventiskeleton.domain.common.UseCase import io.reactivex.Observable import javax.inject.Inject /** * Created by tomas.valenta on 6/15/2017. */ class AddPostUseCase @Inject constructor(val repository: PostRepository, threadExecutor: ThreadExecutor, postExecutionThread: PostExecutionThread) : UseCase<PostAddViewState, AddPostUseCase.Params>(threadExecutor, postExecutionThread) { override fun buildUseCaseObservable(params: AddPostUseCase.Params): Observable<PostAddViewState> { // val error = PostAddViewState.ValidationError(isTitleValid(params), isBodyValid(params)) // // if (error.bodyError || error.titleError) { // return Observable.just(error) // } else { // return repository.savePost(params.title, params.body).map { PostAddViewState.Success(it) } // } return Observable.empty() } private fun isTitleValid(params: Params) = params.title.length >= 3 private fun isBodyValid(params: Params) = params.body.length >= 10 data class Params(val title: String, val body: String) } sealed class PostAddViewState data class Success(val post: Post) : PostAddViewState() data class ValidationError(val titleError: Boolean, val bodyError: Boolean) : PostAddViewState() object Loading: PostAddViewState()
apache-2.0
8749c7277cd964bc4710e68594e1d98e
40.486486
236
0.762215
4.22865
false
false
false
false
AndroidX/androidx
annotation/annotation/src/commonMain/kotlin/androidx/annotation/IntDef.kt
3
2263
/* * Copyright (C) 2014 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.annotation /** * Denotes that the annotated element of integer type, represents * a logical type and that its value should be one of the explicitly * named constants. If the IntDef#flag() attribute is set to true, * multiple constants can be combined. * * Example: * ``` * @Retention(SOURCE) * @IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS}) * public @interface NavigationMode {} * public static final int NAVIGATION_MODE_STANDARD = 0; * public static final int NAVIGATION_MODE_LIST = 1; * public static final int NAVIGATION_MODE_TABS = 2; * ... * public abstract void setNavigationMode(@NavigationMode int mode); * * @NavigationMode * public abstract int getNavigationMode(); * ``` * * For a flag, set the flag attribute: * ``` * @IntDef( * flag = true, * value = {NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS} * ) * ``` * * @see LongDef */ @Retention(AnnotationRetention.SOURCE) @Target(AnnotationTarget.ANNOTATION_CLASS) public annotation class IntDef( /** Defines the allowed constants for this element */ vararg val value: Int = [], /** Defines whether the constants can be used as a flag, or just as an enum (the default) */ val flag: Boolean = false, /** * Whether any other values are allowed. Normally this is * not the case, but this allows you to specify a set of * expected constants, which helps code completion in the IDE * and documentation generation and so on, but without * flagging compilation warnings if other values are specified. */ val open: Boolean = false )
apache-2.0
d8ead2175c23c49aa8b7b82cd1a68bf9
34.375
97
0.711445
4.099638
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/ErrorReportConfigurable.kt
9
2593
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.diagnostic import com.intellij.credentialStore.CredentialAttributes import com.intellij.credentialStore.Credentials import com.intellij.credentialStore.SERVICE_NAME_PREFIX import com.intellij.credentialStore.isFulfilled import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.openapi.components.* import com.intellij.openapi.util.SimpleModificationTracker import kotlinx.serialization.Serializable @State(name = "ErrorReportConfigurable", storages = [Storage(StoragePathMacros.CACHE_FILE)]) internal class ErrorReportConfigurable : PersistentStateComponent<DeveloperList>, SimpleModificationTracker() { companion object { @JvmStatic private val SERVICE_NAME = "$SERVICE_NAME_PREFIX — JetBrains Account" @JvmStatic fun getInstance() = service<ErrorReportConfigurable>() @JvmStatic fun getCredentials() = PasswordSafe.instance.get(CredentialAttributes(SERVICE_NAME)) @JvmStatic fun saveCredentials(userName: String?, password: CharArray?) { val credentials = Credentials(userName, password) PasswordSafe.instance.set(CredentialAttributes(SERVICE_NAME, userName), credentials) lastCredentialsState = credentialsState(credentials) } val userName: String? get() = getCredentialsState().userName val credentialsFulfilled: Boolean get() = getCredentialsState().isFulfilled private var lastCredentialsState: CredentialsState? = null private fun getCredentialsState(): CredentialsState = lastCredentialsState ?: credentialsState(getCredentials()) } var developerList = DeveloperList() set(value) { field = value incModificationCount() } override fun getState() = developerList override fun loadState(value: DeveloperList) { developerList = value } } private data class CredentialsState(val userName: String?, val isFulfilled: Boolean) private fun credentialsState(credentials: Credentials?) = CredentialsState(credentials?.userName ?: "", credentials.isFulfilled()) // 24 hours private const val UPDATE_INTERVAL = 24L * 60 * 60 * 1000 @Serializable internal data class DeveloperList(val developers: List<Developer> = emptyList(), val timestamp: Long = 0) { fun isUpToDateAt() = timestamp != 0L && (System.currentTimeMillis() - timestamp) < UPDATE_INTERVAL } @Serializable internal data class Developer(val id: Int, val displayText: String) { companion object { val NULL = Developer(-1, "<none>") } }
apache-2.0
4af09ee678e7e22e4d42442c5fc9aec5
34.506849
130
0.763412
4.780443
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/java/testSources/execution/GradleDebuggingIntegrationTest.kt
2
12069
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.execution import com.intellij.openapi.util.io.systemIndependentPath import org.assertj.core.api.Assertions.assertThat import org.jetbrains.plugins.gradle.importing.createBuildFile import org.jetbrains.plugins.gradle.importing.createSettingsFile import org.jetbrains.plugins.gradle.importing.importProject import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions import org.junit.Test import java.io.File class GradleDebuggingIntegrationTest : GradleDebuggingIntegrationTestCase() { @Test fun `daemon is started with debug flags only if script debugging is enabled`() { val argsFile = File(projectPath, "args.txt") importProject { withMavenCentral() applyPlugin("'java'") addPostfix(""" import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; task myTask { doFirst { RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); List<String> arguments = runtimeMxBean.getInputArguments(); File file = new File("${argsFile.systemIndependentPath}") file.write(arguments.toString()) } } """.trimIndent()) } ensureDeleted(argsFile) executeRunConfiguration("myTask", isScriptDebugEnabled = true) assertDebugJvmArgs(":myTask", argsFile) ensureDeleted(argsFile) executeRunConfiguration("myTask", isScriptDebugEnabled = false) assertDebugJvmArgs(":myTask", argsFile, shouldBeDebugged = false) } @Test fun `test tasks debugging for modules`() { createPrintArgsClass() createPrintArgsClass("module") val projectArgsFile = createArgsFile() val moduleArgsFile = createArgsFile("module") createSettingsFile { include("module") } createBuildFile("module") { withPrintArgsTask(moduleArgsFile) } importProject { withPrintArgsTask(projectArgsFile) } ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration(":printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration(":module:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("module:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration(":printArgs", modulePath = "module") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("printArgs", modulePath = "module") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) } @Test fun `test tasks debugging for module with dependent tasks`() { createPrintArgsClass() val implicitArgsFile = createArgsFile(name = "implicit-args.txt") val explicitArgsFile = createArgsFile(name = "explicit-args.txt") importProject { withPrintArgsTask(implicitArgsFile, "implicitTask") withPrintArgsTask(explicitArgsFile, "explicitTask", dependsOn = ":implicitTask") } ensureDeleted(implicitArgsFile, explicitArgsFile) executeRunConfiguration("explicitTask") assertDebugJvmArgs(":implicitTask", implicitArgsFile, shouldBeDebugged = false) assertDebugJvmArgs(":explicitTask", explicitArgsFile) ensureDeleted(implicitArgsFile, explicitArgsFile) executeRunConfiguration("explicitTask", isDebugAllEnabled = true) assertDebugJvmArgs(":implicitTask", implicitArgsFile) assertDebugJvmArgs(":explicitTask", explicitArgsFile) } @Test fun `test tasks debugging for module with dependent tasks with same name`() { createPrintArgsClass() createPrintArgsClass("module") val projectArgsFile = createArgsFile() val moduleArgsFile = createArgsFile("module") createSettingsFile { include("module") } createBuildFile("module") { withPrintArgsTask(moduleArgsFile, dependsOn = ":printArgs") } importProject { withPrintArgsTask(projectArgsFile) } ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration(":module:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeDebugged = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("module:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeDebugged = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration(":printArgs", modulePath = "module") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("printArgs", modulePath = "module") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeDebugged = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) } @Test fun `test tasks debugging for partial matched tasks`() { createPrintArgsClass() val projectArgsFile = createArgsFile() importProject { withPrintArgsTask(projectArgsFile) } ensureDeleted(projectArgsFile, projectArgsFile) executeRunConfiguration("print") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile, projectArgsFile) executeRunConfiguration(":print") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile, projectArgsFile) executeRunConfiguration("printArgs") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile, projectArgsFile) executeRunConfiguration(":printArgs") assertDebugJvmArgs("printArgs", projectArgsFile) } @Test fun `test tasks debugging for tasks that defined in script parameters`() { createPrintArgsClass() val projectArgsFile = createArgsFile() importProject { withPrintArgsTask(projectArgsFile) } ensureDeleted(projectArgsFile) executeRunConfiguration("printArgs", scriptParameters = "print") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile) executeRunConfiguration("printArgs", scriptParameters = ":print") assertDebugJvmArgs("printArgs", projectArgsFile) } @Test @TargetVersions("4.9+") fun `test tasks configuration avoidance during debug`() { createPrintArgsClass() val projectArgsFile = createArgsFile() importProject { withPrintArgsTask(projectArgsFile) registerTask("bomb") { call("println", "BOOM!") } } ensureDeleted(projectArgsFile) assertThat(executeRunConfiguration("printArgs")) .doesNotContain("BOOM!") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile) assertThat(executeRunConfiguration(":printArgs")) .doesNotContain("BOOM!") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile) assertThat(executeRunConfiguration("bomb")) .contains("BOOM!") assertDebugJvmArgs("printArgs", projectArgsFile, shouldBeStarted = false) } @Test @TargetVersions("3.1+") fun `test tasks debugging for composite build`() { createPrintArgsClass() createPrintArgsClass("module") createPrintArgsClass("composite") createPrintArgsClass("composite/module") val projectArgsFile = createArgsFile() val moduleArgsFile = createArgsFile("module") val compositeArgsFile = createArgsFile("composite") val compositeModuleArgsFile = createArgsFile("composite/module") createSettingsFile("composite") { include("module") } createBuildFile("composite") { withPrintArgsTask(compositeArgsFile) } createBuildFile("composite/module") { withPrintArgsTask(compositeModuleArgsFile) } createSettingsFile { include("module") includeBuild("composite") } createBuildFile("module") { withPrintArgsTask(moduleArgsFile) } importProject { withPrintArgsTask(projectArgsFile) } ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration("printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile, shouldBeStarted = false) if (isGradleNewerOrSameAs("6.9")) { ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration(":composite:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile, shouldBeStarted = false) ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration(":composite:module:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile) } ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration("printArgs", modulePath = "composite") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration(":printArgs", modulePath = "composite") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile, shouldBeStarted = false) ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration(":module:printArgs", modulePath = "composite") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile) } }
apache-2.0
4be89180ad0fa1d68118c993870d511a
41.055749
140
0.762946
4.645497
false
true
false
false
tensorflow/examples
lite/examples/pose_estimation/android/app/src/androidTest/java/org/tensorflow/lite/examples/poseestimation/ml/PosenetTest.kt
1
2511
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================== */ package org.tensorflow.lite.examples.poseestimation.ml import android.content.Context import android.graphics.PointF import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.tensorflow.lite.examples.poseestimation.data.BodyPart import org.tensorflow.lite.examples.poseestimation.data.Device @RunWith(AndroidJUnit4::class) class PosenetTest { companion object { private const val TEST_INPUT_IMAGE1 = "image1.png" private const val TEST_INPUT_IMAGE2 = "image2.jpg" private const val ACCEPTABLE_ERROR = 37f } private lateinit var poseDetector: PoseDetector private lateinit var appContext: Context private lateinit var expectedDetectionResult: List<Map<BodyPart, PointF>> @Before fun setup() { appContext = InstrumentationRegistry.getInstrumentation().targetContext poseDetector = PoseNet.create(appContext, Device.CPU) expectedDetectionResult = EvaluationUtils.loadCSVAsset("pose_landmark_truth.csv") } @Test fun testPoseEstimationResultWithImage1() { val input = EvaluationUtils.loadBitmapAssetByName(TEST_INPUT_IMAGE1) val person = poseDetector.estimatePoses(input)[0] EvaluationUtils.assertPoseDetectionResult( person, expectedDetectionResult[0], ACCEPTABLE_ERROR ) } @Test fun testPoseEstimationResultWithImage2() { val input = EvaluationUtils.loadBitmapAssetByName(TEST_INPUT_IMAGE2) val person = poseDetector.estimatePoses(input)[0] EvaluationUtils.assertPoseDetectionResult( person, expectedDetectionResult[1], ACCEPTABLE_ERROR ) } }
apache-2.0
bb87ac3cf95e6321184394de75b19849
34.380282
79
0.713262
4.57377
false
true
false
false
Flank/flank
flank-scripts/src/main/kotlin/flank/scripts/utils/ShellExecute.kt
1
2501
package flank.scripts.utils import java.io.File fun List<String>.runCommand( retryCount: Int = 0, fileForOutput: File? = null, environmentVariables: Map<String, String> = mapOf(), executionDirectory: File? = null ) = ProcessBuilder(this).apply { environment().putAll(environmentVariables) if (executionDirectory != null) directory(executionDirectory) if (fileForOutput != null) { redirectOutput(fileForOutput) redirectError(fileForOutput) } else { redirectOutput(ProcessBuilder.Redirect.INHERIT) redirectError(ProcessBuilder.Redirect.INHERIT) } }.startWithRetry(retryCount) fun String.runCommand( retryCount: Int = 0, fileForOutput: File? = null, environmentVariables: Map<String, String> = mapOf(), executionDirectory: File? = null ) = split(" ").toList().runCommand(retryCount, fileForOutput, environmentVariables, executionDirectory) fun String.runForOutput(retryCount: Int = 0): String = File .createTempFile(hashCode().toString(), "") .let { file -> runCommand(retryCount, file) file.readText() } fun String.checkCommandExists() = (if (isWindows) "where " else "command -v ").plus(this).runCommand() == 0 fun String.checkAndInstallIfNeed(installCommand: String) = checkCommandExists().takeUnless { it }?.let { installCommand.runCommand() } fun String.commandInstalledOr(orAction: () -> Unit) = checkCommandExists().takeUnless { it }?.let { orAction() } infix fun String.pipe(command: String) { if (isWindows) { listOf("cmd", "/C", "$this | $command").runCommand() } else { listOf("/bin/bash", "-c", "$this | $command").runCommand() } } internal fun ProcessBuilder.startWithRetry(retryCount: Int): Int { var retryTries = 0 var processResponse: Int do { processResponse = try { start().waitFor() } catch (e: Exception) { println("Error when making shell command ${e.message}, cannot try again") EXCEPTION_WHEN_CALLING_COMMAND_CODE } retryTries++ } while (shouldRetry(processResponse, retryCount, retryTries)) return processResponse } private fun shouldRetry( processResponse: Int, retryCount: Int, retryTries: Int ) = processResponse != 0 && processResponse != EXCEPTION_WHEN_CALLING_COMMAND_CODE && retryTries < retryCount const val SUCCESS = 0 const val ERROR_WHEN_RUNNING = 1 private const val EXCEPTION_WHEN_CALLING_COMMAND_CODE = -1
apache-2.0
9e865fe92a4257edb4127e288c8240df
31.064103
109
0.677329
4.120264
false
false
false
false
vanniktech/lint-rules
lint-rules-android-lint/src/main/java/com/vanniktech/lintrules/android/AlertDialogUsageDetector.kt
1
2064
@file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final. package com.vanniktech.lintrules.android import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope.JAVA_FILE import com.android.tools.lint.detector.api.Severity.WARNING import com.intellij.psi.PsiType import org.jetbrains.uast.UClass import org.jetbrains.uast.UElement import org.jetbrains.uast.UVariable import java.util.EnumSet val ISSUE_ALERT_DIALOG_USAGE = Issue.create( "AlertDialogUsage", "Use the support library AlertDialog instead of android.app.AlertDialog.", "Support library AlertDialog is much more powerful and plays better together with the new theming / styling than the AlertDialog built into the framework.", CORRECTNESS, PRIORITY, WARNING, Implementation(AlertDialogUsageDetector::class.java, EnumSet.of(JAVA_FILE)), ) private const val FQDN_ANDROID_ALERT_DIALOG = "android.app.AlertDialog" class AlertDialogUsageDetector : Detector(), Detector.UastScanner { override fun getApplicableUastTypes() = listOf<Class<out UElement>>(UVariable::class.java, UClass::class.java) override fun createUastHandler(context: JavaContext) = AlertDialogUsageHandler(context) class AlertDialogUsageHandler( private val context: JavaContext, ) : UElementHandler() { override fun visitVariable(node: UVariable) = process(node.type, node) override fun visitClass(node: UClass) = node.uastSuperTypes.forEach { process(it.type, it) } private fun process(type: PsiType, node: UElement) { if (context.evaluator.typeMatches(type, FQDN_ANDROID_ALERT_DIALOG)) { context.report(ISSUE_ALERT_DIALOG_USAGE, node, context.getLocation(node), "Should not be using `android.app.AlertDialog`") } } } }
apache-2.0
0c8cde82ee57eaf16e285a52a9c3dea0
42.914894
158
0.785853
4.087129
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/project/IProgramState.kt
1
1215
package com.cout970.modeler.core.project import com.cout970.modeler.api.animation.IAnimation import com.cout970.modeler.api.animation.IAnimationRef import com.cout970.modeler.api.model.IModel import com.cout970.modeler.api.model.`object`.IGroupRef import com.cout970.modeler.api.model.material.IMaterial import com.cout970.modeler.api.model.material.IMaterialRef import com.cout970.modeler.api.model.selection.ISelection import com.cout970.modeler.core.model.selection.SelectionHandler import com.cout970.modeler.util.Nullable /** * Created by cout970 on 2017/09/27. */ interface IProgramState { val model: IModel val material: IMaterial val animation: IAnimation val selectedGroup: IGroupRef val selectedMaterial: IMaterialRef val selectedAnimation: IAnimationRef val modelSelectionHandler: SelectionHandler val textureSelectionHandler: SelectionHandler val modelSelection: Nullable<ISelection> get() = modelSelectionHandler.getSelection() val textureSelection: Nullable<ISelection> get() = textureSelectionHandler.getSelection() operator fun component1() = model operator fun component2() = modelSelection operator fun component3() = textureSelection }
gpl-3.0
8ce25e7e8db9c5ec87d7d9a4bf908a81
33.742857
93
0.799177
4.21875
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/viewholders/CreatorDashboardRewardStatsRowViewHolder.kt
1
2523
package com.kickstarter.ui.viewholders import android.util.Pair import com.kickstarter.R import com.kickstarter.databinding.DashboardRewardStatsRowViewBinding import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.extensions.isZero import com.kickstarter.models.Project import com.kickstarter.services.apiresponses.ProjectStatsEnvelope.RewardStats import com.kickstarter.viewmodels.DashboardRewardStatsRowHolderViewModel class CreatorDashboardRewardStatsRowViewHolder(private val binding: DashboardRewardStatsRowViewBinding) : KSViewHolder(binding.root) { private val viewModel = DashboardRewardStatsRowHolderViewModel.ViewModel(environment()) private val ksCurrency = requireNotNull(environment().ksCurrency()) init { viewModel.outputs.percentageOfTotalPledged() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { binding.percentagePledgedForTextView.text = it } viewModel.outputs.projectAndRewardPledged() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { setPledgedColumnValue(it) } viewModel.outputs.rewardBackerCount() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { binding.rewardBackerCountTextView.text = it } viewModel.outputs.projectAndRewardMinimum() .compose(bindToLifecycle()) .compose(Transformers.observeForUI()) .subscribe { setRewardMinimumText(it) } } @Throws(Exception::class) override fun bindData(data: Any?) { val projectAndRewardStats = ObjectUtils.requireNonNull(data as Pair<Project, RewardStats>?) viewModel.inputs.projectAndRewardStats(projectAndRewardStats) } private fun setPledgedColumnValue(projectAndPledgedForReward: Pair<Project, Float>) { binding.amountPledgedForRewardTextView.text = ksCurrency.format(projectAndPledgedForReward.second.toDouble(), projectAndPledgedForReward.first) } private fun setRewardMinimumText(projectAndMinimumForReward: Pair<Project, Int>) { binding.rewardMinimumTextView.text = if (projectAndMinimumForReward.second.isZero()) context().getString(R.string.dashboard_graphs_rewards_no_reward) else ksCurrency.format(projectAndMinimumForReward.second.toDouble(), projectAndMinimumForReward.first) } }
apache-2.0
fc5f9645d0304243d16855b778ffbc18
47.519231
151
0.750297
4.833333
false
false
false
false
Flank/flank
tool/instrument/command/src/test/kotlin/flank/instrument/command/FormatAmInstrumentCommandKtTest.kt
1
1037
package flank.instrument.command import org.junit.Assert.assertEquals import org.junit.Test class FormatAmInstrumentCommandKtTest { @Test fun test() { val expected = "am instrument -r -w" + " --no-window-animation" + " -e class com.package.Test1#testMethod1,com.package.Test2#testMethod1,com.package.Test2#testMethod2" + " -e package com.package.nested1,com.package.nested2 com.package/AnyRunner" val actual = formatAmInstrumentCommand( packageName = "com.package", testRunner = "AnyRunner", testCases = listOf( "class com.package.Test1#testMethod1", "class com.package.Test2#testMethod1", "class com.package.Test2#testMethod2", "package com.package.nested1", "package com.package.nested2", ), // noWindowAnimation = true, // No window animation should be disable by default ) assertEquals(expected, actual) } }
apache-2.0
17a09b65265e1b18658f35cfed037327
33.566667
115
0.608486
4.232653
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FilterTransformation.kt
6
17029
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.idea.intentions.loopToCallChain.* import org.jetbrains.kotlin.idea.intentions.loopToCallChain.result.FindTransformationMatcher import org.jetbrains.kotlin.idea.intentions.loopToCallChain.result.MaxOrMinTransformation import org.jetbrains.kotlin.idea.intentions.negate import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode abstract class FilterTransformationBase : SequenceTransformation { abstract val effectiveCondition: Condition abstract val inputVariable: KtCallableDeclaration abstract val indexVariable: KtCallableDeclaration? override val affectsIndex: Boolean get() = true /** * Matches: * for (...) { * if (<condition>) { * ... * } * } * * or * * for (...) { * if (<condition>) continue * ... * } * or * * for (...) { * if (<condition>) break * ... * } * * plus optionally consequent find operation (assignment or return) */ object Matcher : TransformationMatcher { override val indexVariableAllowed: Boolean get() = true override fun match(state: MatchingState): TransformationMatch? { // we merge filter transformations here instead of FilterTransformation.mergeWithPrevious() because of filterIndexed that won't merge otherwise var (transformation, currentState) = matchOneTransformation(state) ?: return null assert(currentState.indexVariable == state.indexVariable) // indexVariable should not change if (transformation !is FilterTransformationBase) { return TransformationMatch.Sequence(transformation, currentState) } val atomicConditions = transformation.effectiveCondition.toAtomicConditions().toMutableList() while (true) { currentState = currentState.unwrapBlock() // do not take 'if' which is required for min/max matcher if (MaxOrMinTransformation.Matcher.match(currentState) != null) break val (nextTransformation, nextState) = matchOneTransformation(currentState) ?: break if (nextTransformation !is FilterTransformationBase) break assert(nextState.indexVariable == currentState.indexVariable) // indexVariable should not change atomicConditions.addAll(nextTransformation.effectiveCondition.toAtomicConditions()) currentState = nextState } val transformations = createTransformationsByAtomicConditions( currentState.outerLoop, currentState.inputVariable, currentState.indexVariable, atomicConditions, currentState.statements, currentState.reformat ) assert(transformations.isNotEmpty()) val findTransformationMatch = FindTransformationMatcher.matchWithFilterBefore(currentState, transformations.last()) return if (findTransformationMatch != null) { TransformationMatch.Result( findTransformationMatch.resultTransformation, transformations.dropLast(1) + findTransformationMatch.sequenceTransformations ) } else { TransformationMatch.Sequence(transformations, currentState) } } private fun createTransformationsByAtomicConditions( loop: KtForExpression, inputVariable: KtCallableDeclaration, indexVariable: KtCallableDeclaration?, conditions: List<AtomicCondition>, restStatements: List<KtExpression>, reformat: Boolean ): List<FilterTransformationBase> { if (conditions.size == 1) { return listOf(createFilterTransformation(loop, inputVariable, indexVariable, conditions.single(), reformat = reformat)) } var transformations = conditions.map { createFilterTransformation(loop, inputVariable, indexVariable, it, reformat = reformat) } val resultTransformations = ArrayList<FilterTransformationBase>() val lastUseOfIndex = transformations.lastOrNull { it.indexVariable != null } if (lastUseOfIndex != null) { val index = transformations.indexOf(lastUseOfIndex) val condition = CompositeCondition.create(conditions.take(index + 1)) resultTransformations.add(createFilterTransformation(loop, inputVariable, indexVariable, condition, reformat = reformat)) transformations = transformations.drop(index + 1) } for ((transformation, condition) in transformations.zip(conditions)) { if (transformation !is FilterTransformation && isSmartCastUsed( inputVariable, restStatements ) ) { // filterIsInstance of filterNotNull resultTransformations.add(transformation) } else { val prevFilter = resultTransformations.lastOrNull() as? FilterTransformation if (prevFilter != null) { val mergedCondition = CompositeCondition.create( prevFilter.effectiveCondition.toAtomicConditions() + transformation.effectiveCondition.toAtomicConditions() ) val mergedTransformation = createFilterTransformation( loop, inputVariable, indexVariable, mergedCondition, onlyFilterOrFilterNot = true, reformat = reformat ) resultTransformations[resultTransformations.lastIndex] = mergedTransformation } else { resultTransformations.add( createFilterTransformation( loop, inputVariable, indexVariable, condition, onlyFilterOrFilterNot = true, reformat = reformat ) ) } } } return resultTransformations } private fun matchOneTransformation(state: MatchingState): Pair<SequenceTransformation, MatchingState>? { val ifStatement = state.statements.firstOrNull() as? KtIfExpression ?: return null val condition = ifStatement.condition ?: return null val thenBranch = ifStatement.then ?: return null val elseBranch = ifStatement.`else` if (elseBranch == null) { return matchOneTransformation(state, condition, false, thenBranch, state.statements.drop(1)) } else if (state.statements.size == 1) { val thenStatement = thenBranch.blockExpressionsOrSingle().singleOrNull() if (thenStatement is KtBreakExpression || thenStatement is KtContinueExpression) { return matchOneTransformation(state, condition, false, thenBranch, listOf(elseBranch)) } val elseStatement = elseBranch.blockExpressionsOrSingle().singleOrNull() if (elseStatement is KtBreakExpression || elseStatement is KtContinueExpression) { return matchOneTransformation(state, condition, true, elseBranch, listOf(thenBranch)) } } return null } private fun matchOneTransformation( state: MatchingState, condition: KtExpression, negateCondition: Boolean, then: KtExpression, restStatements: List<KtExpression> ): Pair<SequenceTransformation, MatchingState>? { // we do not allow filter() which uses neither input variable nor index variable (though is technically possible but looks confusing) // shouldUseInputVariables = false does not work for us because we sometimes return Result match in this matcher if (!state.inputVariable.hasUsages(condition) && (state.indexVariable == null || !state.indexVariable.hasUsages(condition)) ) return null if (restStatements.isEmpty()) { val transformation = createFilterTransformation( state.outerLoop, state.inputVariable, state.indexVariable, Condition.create(condition, negateCondition), reformat = state.reformat ) val newState = state.copy(statements = listOf(then)) return transformation to newState } else { val statement = then.blockExpressionsOrSingle().singleOrNull() ?: return null when (statement) { is KtContinueExpression -> { if (statement.targetLoop() != state.innerLoop) return null val transformation = createFilterTransformation( state.outerLoop, state.inputVariable, state.indexVariable, Condition.create(condition, !negateCondition), reformat = state.reformat ) val newState = state.copy(statements = restStatements) return transformation to newState } is KtBreakExpression -> { if (statement.targetLoop() != state.outerLoop) return null val transformation = TakeWhileTransformation( state.outerLoop, state.inputVariable, if (negateCondition) condition else condition.negate(reformat = state.reformat) ) val newState = state.copy(statements = restStatements) return transformation to newState } else -> return null } } } private fun createFilterTransformation( loop: KtForExpression, inputVariable: KtCallableDeclaration, indexVariable: KtCallableDeclaration?, condition: Condition, onlyFilterOrFilterNot: Boolean = false, reformat: Boolean ): FilterTransformationBase { if (indexVariable != null && condition.hasUsagesOf(indexVariable)) { return FilterTransformation(loop, inputVariable, indexVariable, condition, isFilterNot = false) } val conditionAsExpression = condition.asExpression(reformat) if (!onlyFilterOrFilterNot) { if (conditionAsExpression is KtIsExpression && !conditionAsExpression.isNegated // we cannot use isVariableReference here because expression can be non-physical && conditionAsExpression.leftHandSide.isSimpleName(inputVariable.nameAsSafeName) ) { val typeRef = conditionAsExpression.typeReference if (typeRef != null) { return FilterIsInstanceTransformation(loop, inputVariable, typeRef, condition) } } if (conditionAsExpression is KtBinaryExpression && conditionAsExpression.operationToken == KtTokens.EXCLEQ && conditionAsExpression.right.isNullExpression() && conditionAsExpression.left.isSimpleName(inputVariable.nameAsSafeName) ) { return FilterNotNullTransformation(loop, inputVariable, condition) } } if (conditionAsExpression is KtPrefixExpression && conditionAsExpression.operationToken == KtTokens.EXCL) { return FilterTransformation(loop, inputVariable, null, condition, isFilterNot = true) } return FilterTransformation(loop, inputVariable, null, condition, isFilterNot = false) } private fun isSmartCastUsed(inputVariable: KtCallableDeclaration, statements: List<KtExpression>): Boolean { return statements.any { statement -> statement.anyDescendantOfType<KtNameReferenceExpression> { it.mainReference.resolve() == inputVariable && it.analyze(BodyResolveMode.PARTIAL)[BindingContext.SMARTCAST, it] != null } } } } } class FilterTransformation( override val loop: KtForExpression, override val inputVariable: KtCallableDeclaration, override val indexVariable: KtCallableDeclaration?, override val effectiveCondition: Condition, val isFilterNot: Boolean ) : FilterTransformationBase() { init { if (isFilterNot) { assert(indexVariable == null) } } private val functionName = when { indexVariable != null -> "filterIndexed" isFilterNot -> "filterNot" else -> "filter" } override val presentation: String get() = "$functionName{}" override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { val reformat = chainedCallGenerator.reformat val lambda = if (indexVariable != null) generateLambda(inputVariable, indexVariable, effectiveCondition.asExpression(reformat), reformat) else generateLambda( inputVariable, if (isFilterNot) effectiveCondition.asNegatedExpression(reformat) else effectiveCondition.asExpression(reformat), reformat ) return chainedCallGenerator.generate("$0$1:'{}'", functionName, lambda) } } class FilterIsInstanceTransformation( override val loop: KtForExpression, override val inputVariable: KtCallableDeclaration, private val type: KtTypeReference, override val effectiveCondition: Condition ) : FilterTransformationBase() { override val indexVariable: KtCallableDeclaration? get() = null override val presentation: String get() = "filterIsInstance<>()" override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { return chainedCallGenerator.generate("filterIsInstance<$0>()", type) } } class FilterNotNullTransformation( override val loop: KtForExpression, override val inputVariable: KtCallableDeclaration, override val effectiveCondition: Condition ) : FilterTransformationBase() { override val indexVariable: KtCallableDeclaration? get() = null override fun mergeWithPrevious(previousTransformation: SequenceTransformation, reformat: Boolean): SequenceTransformation? { if (previousTransformation is MapTransformation) { return MapTransformation( loop, previousTransformation.inputVariable, previousTransformation.indexVariable, previousTransformation.mapping, mapNotNull = true ) } return null } override val presentation: String get() = "filterNotNull()" override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { return chainedCallGenerator.generate("filterNotNull()") } } class TakeWhileTransformation( override val loop: KtForExpression, val inputVariable: KtCallableDeclaration, val condition: KtExpression ) : SequenceTransformation { //TODO: merge multiple override val affectsIndex: Boolean get() = false override val presentation: String get() = "takeWhile{}" override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { val lambda = generateLambda(inputVariable, condition, chainedCallGenerator.reformat) return chainedCallGenerator.generate("takeWhile$0:'{}'", lambda) } }
apache-2.0
d31258c2901831ad29471747dd939fe2
42.77635
158
0.618298
6.276815
false
false
false
false
SkyTreasure/Kotlin-Firebase-Group-Chat
app/src/main/java/io/skytreasure/kotlingroupchat/chat/ui/GroupDetailsActivity.kt
1
17699
package io.skytreasure.kotlingroupchat.chat.ui import android.Manifest import android.content.ContentResolver import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.provider.MediaStore import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.text.format.DateFormat import android.util.Base64 import android.util.Log import android.view.View import android.webkit.MimeTypeMap import android.widget.Toast import com.google.android.gms.tasks.OnFailureListener import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference import com.google.firebase.storage.UploadTask import com.theartofdev.edmodo.cropper.CropImage import com.theartofdev.edmodo.cropper.CropImageView import io.skytreasure.kotlingroupchat.MainActivity import kotlinx.android.synthetic.main.activity_new_group.* import io.skytreasure.kotlingroupchat.R import io.skytreasure.kotlingroupchat.chat.MyChatManager import io.skytreasure.kotlingroupchat.chat.model.FileModel import io.skytreasure.kotlingroupchat.chat.model.GroupModel import io.skytreasure.kotlingroupchat.chat.model.MessageModel import io.skytreasure.kotlingroupchat.chat.model.UserModel import io.skytreasure.kotlingroupchat.chat.ui.adapter.ParticipantsAdapter import io.skytreasure.kotlingroupchat.common.constants.AppConstants import io.skytreasure.kotlingroupchat.common.constants.DataConstants import io.skytreasure.kotlingroupchat.common.constants.DataConstants.Companion.sMyGroups import io.skytreasure.kotlingroupchat.common.constants.DataConstants.Companion.selectedUserList import io.skytreasure.kotlingroupchat.common.constants.FirebaseConstants import io.skytreasure.kotlingroupchat.common.constants.NetworkConstants import io.skytreasure.kotlingroupchat.common.controller.NotifyMeInterface import io.skytreasure.kotlingroupchat.common.util.SharedPrefManager import io.skytreasure.kotlingroupchat.common.util.loadRoundImage import java.io.ByteArrayOutputStream import java.io.File import java.io.IOException import java.util.* class GroupDetailsActivity : AppCompatActivity(), View.OnClickListener { var adapter: ParticipantsAdapter? = null private var mCropImageUri: Uri? = null private var resultUri: Uri? = null var storage = FirebaseStorage.getInstance() var groupId: String? = "" var storageRef: StorageReference? = null companion object { private const val ASK_MULTIPLE_PERMISSION_REQUEST_CODE: Int = 100 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_new_group) storageRef = storage.getReferenceFromUrl(NetworkConstants.URL_STORAGE_REFERENCE).child(NetworkConstants.FOLDER_STORAGE_IMG) rv_main.layoutManager = LinearLayoutManager(this@GroupDetailsActivity) as RecyclerView.LayoutManager? groupId = intent.getStringExtra(AppConstants.GROUP_ID) if (groupId != null) { //Group Details page btn_creategroup.text = "Update Group Name" selectedUserList?.clear() et_groupname.setText(DataConstants.sGroupMap?.get(groupId!!)?.name!!.toString()) DataConstants.sGroupMap?.get(groupId!!)?.members?.forEach { member -> DataConstants.userMap?.get(member.value.uid)!!.admin = member.value.admin DataConstants.userMap?.get(member.value.uid)!!.delete_till = member.value.delete_till DataConstants.userMap?.get(member.value.uid)!!.unread_group_count = member.value.unread_group_count selectedUserList?.add(DataConstants.userMap?.get(member.value.uid)!!) } loadRoundImage(iv_profile, DataConstants.sGroupMap?.get(groupId!!)?.image_url!!) adapter = ParticipantsAdapter(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { tv_no_of_participants.setText("" + selectedUserList?.size!! + " Participants") } }, AppConstants.DETAILS, groupId!!) rv_main.adapter = adapter tv_exit_group.visibility = View.VISIBLE tv_exit_group.setOnClickListener(this@GroupDetailsActivity) } else { // Group Creation Page btn_creategroup.text = "Create Group" adapter = ParticipantsAdapter(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { tv_no_of_participants.setText("" + selectedUserList?.size!! + " Participants") } }, AppConstants.CREATION, "23") rv_main.adapter = adapter tv_exit_group.visibility = View.GONE } iv_profile.setOnClickListener(this@GroupDetailsActivity) iv_back.setOnClickListener(this@GroupDetailsActivity) btn_creategroup.setOnClickListener(this@GroupDetailsActivity) tv_no_of_participants.setText("" + selectedUserList?.size!! + " Participants") label_hint.setOnClickListener(this@GroupDetailsActivity) label_hint.setText("Add [email protected] to the group") } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { CropImage.startPickImageActivity(this) } else { Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show() } } if (requestCode == CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE) { if (mCropImageUri != null && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // mCurrentFragment.setImageUri(mCropImageUri); } else { Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show() } } if (requestCode == ASK_MULTIPLE_PERMISSION_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == AppCompatActivity.RESULT_OK) { val imageUri = CropImage.getPickImageResultUri(this, data) // For API >= 23 we need to check specifically that we have permissions to read external storage, // but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error. var requirePermissions = false if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) { // request permissions and handle the result in onRequestPermissionsResult() requirePermissions = true mCropImageUri = imageUri if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE) } } else { CropImage.activity(imageUri) .setGuidelines(CropImageView.Guidelines.ON) .setCropShape(CropImageView.CropShape.RECTANGLE) .setAspectRatio(1, 1) .setInitialCropWindowPaddingRatio(0f) .start(this) } } if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { val result = CropImage.getActivityResult(data) if (resultCode == RESULT_OK) { resultUri = result.uri val img = "data:" val mimeType = getMimeType(resultUri, this) + ";base64,"//data:image/jpeg;base64, val s = img + mimeType + getBase64EncodedImage(resultUri, this) as String //callProfilePictureApi(s) if (groupId != null) { sendFileFirebase(storageRef, resultUri!!, groupId!!) } iv_profile.setImageURI(resultUri) } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { result.error } } } private fun getBase64EncodedImage(uri: Uri?, context: Context): String? { return try { val bmp = MediaStore.Images.Media.getBitmap(context.contentResolver, uri) val nh = (bmp.height * (512.0 / bmp.width)).toInt() val scaledBmp = Bitmap.createScaledBitmap(bmp, 512, nh, true) val baos = ByteArrayOutputStream() scaledBmp.compress(Bitmap.CompressFormat.JPEG, 100, baos) val imageBytes = baos.toByteArray() Base64.encodeToString(imageBytes, Base64.DEFAULT) } catch (exception: IOException) { Toast.makeText(context, "Image not found", Toast.LENGTH_LONG).show() null } } private fun getMimeType(uri: Uri?, context: Context): String { return if (uri?.scheme == ContentResolver.SCHEME_CONTENT) { val cr = context.contentResolver cr.getType(uri) } else { val fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri .toString()) MimeTypeMap.getSingleton().getMimeTypeFromExtension( fileExtension.toLowerCase()) } } /* * Call from fragment to crop image **/ fun cropImage() { if (CropImage.isExplicitCameraPermissionRequired(this@GroupDetailsActivity)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(arrayOf(Manifest.permission.CAMERA), CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE) } } else { //CropImage.getPickImageChooserIntent(this) CropImage.startPickImageActivity(this@GroupDetailsActivity) } } override fun onClick(v: View?) { when (v?.id) { R.id.iv_profile -> { cropImage() } R.id.btn_creategroup -> { if (btn_creategroup.text.equals("Create Group")) { createGroup() } else { updateName() } } R.id.iv_back -> { finish() } R.id.label_hint -> { if (!DataConstants.sGroupMap?.get(groupId!!)?.members?.containsKey("9f19bxizDuYx95PfkBe3N7uamu92")!!) { MyChatManager.addMemberToAGroup(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { selectedUserList?.add(DataConstants.userMap?.get("9f19bxizDuYx95PfkBe3N7uamu92")!!) /* adapter = ParticipantsAdapter(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { tv_no_of_participants.setText("" + selectedUserList?.size!! + " Participants") } }, AppConstants.CREATION, groupId!!)*/ adapter?.notifyDataSetChanged() } }, groupId, DataConstants.userMap?.get("9f19bxizDuYx95PfkBe3N7uamu92")) } else { Toast.makeText(this@GroupDetailsActivity, "Akash is already in the group", Toast.LENGTH_LONG).show() } } R.id.tv_exit_group -> { MyChatManager.setmContext(this@GroupDetailsActivity) MyChatManager.removeMemberFromGroup(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { DataConstants.sGroupMap?.get(groupId)?.members?.remove(DataConstants.sCurrentUser?.uid) Toast.makeText(this@GroupDetailsActivity, "You have been exited from group", Toast.LENGTH_LONG).show() val intent = Intent(this@GroupDetailsActivity, ViewGroupsActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) finish() } }, groupId, DataConstants.sCurrentUser?.uid) } } } private fun updateName() { if (!et_groupname.text.isBlank() && et_groupname.text.length > 2) { var mFirebaseDatabaseReference: DatabaseReference? = FirebaseDatabase.getInstance().reference.child(FirebaseConstants.GROUP).child(groupId) mFirebaseDatabaseReference?.child(FirebaseConstants.NAME)?.setValue(et_groupname.text.toString()) Toast.makeText(this@GroupDetailsActivity, "Name Updated successful", Toast.LENGTH_LONG).show() } } private fun createGroup() { var isValid: Boolean = true var errorMessage: String = "Validation Error" var groupName: String = et_groupname.text.toString() if (groupName.isBlank()) { isValid = false errorMessage = "Group name is blank" } if (groupName.length!! < 3) { isValid = false errorMessage = "Group name should be more than 2 characters" } var groupImage: String = "https://cdn1.iconfinder.com/data/icons/google_jfk_icons_by_carlosjj/128/groups.png" var newGroup: GroupModel = GroupModel(groupName, groupImage, group_deleted = false, group = true) var adminUserModel: UserModel? = SharedPrefManager.getInstance(this@GroupDetailsActivity).savedUserModel adminUserModel?.admin = true var groupMembers: HashMap<String, UserModel> = hashMapOf() for (user in selectedUserList!!) { groupMembers.put(user.uid!!, user) } groupMembers.put(adminUserModel?.uid!!, adminUserModel) newGroup.members = groupMembers MyChatManager.setmContext(this@GroupDetailsActivity) if (isValid) { //sendFileFirebase(storageRef, resultUri!!, groupId!!) MyChatManager.createGroup(object : NotifyMeInterface { override fun handleData(`object`: Any, requestCode: Int?) { Toast.makeText(this@GroupDetailsActivity, "Group has been created successful", Toast.LENGTH_SHORT).show() val intent = Intent(this@GroupDetailsActivity, MainActivity::class.java) startActivity(intent) finish() } }, newGroup, NetworkConstants.CREATE_GROUP) } else { Toast.makeText(this@GroupDetailsActivity, errorMessage, Toast.LENGTH_SHORT).show() } } private fun sendFileFirebase(storageReference: StorageReference?, file: File, groupId: String) { if (storageReference != null) { var mFirebaseDatabaseReference: DatabaseReference? = FirebaseDatabase.getInstance().reference.child(FirebaseConstants.GROUP).child(groupId) val uploadTask = storageReference.putFile(Uri.fromFile(file)) uploadTask.addOnFailureListener { e -> Log.e("", "onFailure sendFileFirebase " + e.message) }.addOnSuccessListener { taskSnapshot -> Log.i("", "onSuccess sendFileFirebase") val downloadUrl = taskSnapshot.downloadUrl mFirebaseDatabaseReference?.child(FirebaseConstants.IMAGE_URL)?.setValue(downloadUrl) } } else { //IS NULL } } fun sendFileFirebase(storageReference: StorageReference?, file: Uri, groupId: String) { if (storageReference != null) { val name = DateFormat.format("yyyy-MM-dd_hhmmss", Date()).toString() val imageGalleryRef = storageReference.child(name + "_gallery") val uploadTask = imageGalleryRef.putFile(file) uploadTask.addOnFailureListener { e -> Log.e("", "onFailure sendFileFirebase " + e.message) }.addOnSuccessListener { taskSnapshot -> Log.i("", "onSuccess sendFileFirebase") val downloadUrl = taskSnapshot.downloadUrl val fileModel = FileModel("img", downloadUrl!!.toString(), name, "") // val chatModel = MessageModel(tfUserModel.getUserId(), ffUserModel.getUserId(), ffUserModel, Calendar.getInstance().time.time.toString() + "", fileModel) FirebaseDatabase.getInstance().reference.child(FirebaseConstants.GROUP). child(groupId).child(FirebaseConstants.IMAGE_URL)?.setValue(downloadUrl.toString()) Toast.makeText(this@GroupDetailsActivity, "Group Image Updated successful", Toast.LENGTH_LONG).show() } } else { //IS NULL } } }
mit
dfbaa72a8f9991d79298d10c89261860
42.701235
171
0.640488
4.859692
false
false
false
false
leafclick/intellij-community
platform/testFramework/src/com/intellij/testFramework/ServiceContainerUtil.kt
1
3156
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("ServiceContainerUtil") package com.intellij.testFramework import com.intellij.openapi.Disposable import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.extensions.BaseExtensionPointName import com.intellij.openapi.extensions.DefaultPluginDescriptor import com.intellij.openapi.util.Disposer import com.intellij.serviceContainer.PlatformComponentManagerImpl import com.intellij.util.messages.ListenerDescriptor import com.intellij.util.messages.MessageBusOwner import org.jetbrains.annotations.TestOnly @TestOnly fun <T : Any> ComponentManager.registerServiceInstance(serviceInterface: Class<T>, instance: T) { (this as PlatformComponentManagerImpl).registerServiceInstance(serviceInterface, instance, DefaultPluginDescriptor("test")) } @TestOnly fun <T : Any> ComponentManager.replaceService(serviceInterface: Class<T>, instance: T, parentDisposable: Disposable) { val serviceContainer = this as PlatformComponentManagerImpl if (PlatformComponentManagerImpl.isLightService(serviceInterface)) { serviceContainer.registerServiceInstance(serviceInterface, instance) Disposer.register(parentDisposable, Disposable { serviceContainer.picoContainer.unregisterComponent(serviceInterface) }) } else { serviceContainer.replaceServiceInstance(serviceInterface, instance, parentDisposable) } } /** * Returns old instance. */ @TestOnly fun <T : Any> ComponentManager.registerComponentInstance(componentInterface: Class<T>, instance: T, parentDisposable: Disposable?): T? { return (this as PlatformComponentManagerImpl).replaceComponentInstance(componentInterface, instance, parentDisposable) } @Suppress("DeprecatedCallableAddReplaceWith") @TestOnly @Deprecated("Pass parentDisposable") fun <T : Any> ComponentManager.registerComponentInstance(componentInterface: Class<T>, instance: T): T? { return (this as PlatformComponentManagerImpl).replaceComponentInstance(componentInterface, instance, null) } @TestOnly @JvmOverloads fun ComponentManager.registerComponentImplementation(componentInterface: Class<*>, componentImplementation: Class<*>, shouldBeRegistered: Boolean = false) { (this as PlatformComponentManagerImpl).registerComponentImplementation(componentInterface, componentImplementation, shouldBeRegistered) } @TestOnly fun <T : Any> ComponentManager.registerExtension(name: BaseExtensionPointName<*>, instance: T, parentDisposable: Disposable) { extensionArea.getExtensionPoint<T>(name.name).registerExtension(instance, parentDisposable) } @TestOnly fun ComponentManager.getServiceImplementationClassNames(prefix: String): List<String> { return (this as PlatformComponentManagerImpl).getServiceImplementationClassNames(prefix) } fun createSimpleMessageBusOwner(owner: String): MessageBusOwner { return object : MessageBusOwner { override fun createListener(descriptor: ListenerDescriptor) = throw UnsupportedOperationException() override fun isDisposed() = false override fun toString() = owner } }
apache-2.0
6daed2e5d484a97e86890b40453fda17
42.246575
156
0.821293
5.199341
false
true
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/ui/AutoFixTextureView.kt
1
1320
package com.zhou.android.ui import android.content.Context import android.util.AttributeSet import android.view.TextureView /** * Created by mxz on 2019/11/1. */ class AutoFixTextureView : TextureView { private var mRatioWidth = 0 private var mRatioHeight = 0 @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : super(context, attrs, defStyle) fun setAspectRatio(width: Int, height: Int) { if (width < 0 || height < 0) { throw IllegalArgumentException("Size cannot be negative.") } mRatioWidth = width mRatioHeight = height requestLayout() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val width = MeasureSpec.getSize(widthMeasureSpec) val height = MeasureSpec.getSize(heightMeasureSpec) if (0 == mRatioWidth || 0 == mRatioHeight) { setMeasuredDimension(width, height) } else { if (width < height * mRatioWidth / mRatioHeight) { setMeasuredDimension(width, width * mRatioHeight / mRatioWidth) } else { setMeasuredDimension(height * mRatioWidth / mRatioHeight, height) } } } }
mit
f5408b12e04dd3a554342d839a165258
29.72093
115
0.643182
4.631579
false
false
false
false
jwren/intellij-community
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfile.kt
1
4758
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection.ex import com.intellij.codeInspection.InspectionProfile import com.intellij.codeInspection.ex.InspectionProfileImpl.INIT_INSPECTIONS import com.intellij.configurationStore.SerializableScheme import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PathMacroManager import com.intellij.openapi.options.SchemeState import com.intellij.openapi.project.Project import com.intellij.profile.ProfileEx import com.intellij.profile.codeInspection.BaseInspectionProfileManager import com.intellij.profile.codeInspection.InspectionProfileManager import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import com.intellij.util.xmlb.annotations.Transient import org.jdom.Element const val DEFAULT_PROFILE_NAME: String = "Default" val BASE_PROFILE: InspectionProfileImpl by lazy { InspectionProfileImpl(DEFAULT_PROFILE_NAME) } abstract class NewInspectionProfile(name: String, private var profileManager: BaseInspectionProfileManager) : ProfileEx(name), InspectionProfile, SerializableScheme { @Volatile @JvmField protected var initialized: Boolean = false @JvmField protected val lock: Any = Any() private var isProjectLevel: Boolean = false @JvmField @Transient internal var schemeState: SchemeState? = null override fun getSchemeState(): SchemeState? = schemeState @Transient fun isProjectLevel(): Boolean = isProjectLevel fun setProjectLevel(value: Boolean) { isProjectLevel = value } @Transient fun getProfileManager() = profileManager fun setProfileManager(value: BaseInspectionProfileManager) { profileManager = value } fun wasInitialized(): Boolean { return initialized } override abstract fun getDisplayName(): String protected val pathMacroManager: PathMacroManager get() { val profileManager = profileManager return PathMacroManager.getInstance((profileManager as? ProjectInspectionProfileManager)?.project ?: ApplicationManager.getApplication()) } override fun toString(): String = name override fun equals(other: Any?): Boolean = super.equals(other) && (other as NewInspectionProfile).profileManager === profileManager override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + profileManager.hashCode() return result } /** * If you need to enable multiple tools, please use [InspectionProfileImpl.modifyProfile]. */ @JvmOverloads fun setToolEnabled(toolShortName: String, enabled: Boolean, project: Project? = null, fireEvents: Boolean = true) { val tools = getTools(toolShortName, project ?: (profileManager as? ProjectInspectionProfileManager)?.project) if (enabled) { if (tools.isEnabled && tools.defaultState.isEnabled) { return } tools.isEnabled = true tools.defaultState.isEnabled = true schemeState = SchemeState.POSSIBLY_CHANGED } else { tools.isEnabled = false if (tools.nonDefaultTools == null) { tools.defaultState.isEnabled = false } schemeState = SchemeState.POSSIBLY_CHANGED } if (fireEvents) { profileManager.fireProfileChanged(this as InspectionProfileImpl) } } fun getTools(name: String, project: Project?): ToolsImpl = getToolsOrNull(name, project) ?: throw AssertionError("Can't find tools for \"$name\" in the profile \"${this.name}\"") abstract fun getToolsOrNull(name: String, project: Project?): ToolsImpl? @JvmOverloads fun initInspectionTools(project: Project? = (profileManager as? ProjectInspectionProfileManager)?.project) { if (initialized || !forceInitInspectionTools()) { return } synchronized(lock) { if (!initialized) { initialize(project) } } } protected open fun forceInitInspectionTools(): Boolean = !ApplicationManager.getApplication().isUnitTestMode || INIT_INSPECTIONS protected abstract fun initialize(project: Project?) fun copyFrom(profile: InspectionProfileImpl) { var element = profile.writeScheme() if (element.name == "component") { element = element.getChild("profile") } readExternal(element) } abstract fun readExternal(element: Element) } fun createSimple(name: String, project: Project, toolWrappers: List<InspectionToolWrapper<*, *>>): InspectionProfileImpl { val profile = InspectionProfileImpl(name, InspectionToolsSupplier.Simple(toolWrappers), InspectionProfileManager.getInstance() as BaseInspectionProfileManager) for (toolWrapper in toolWrappers) { profile.enableTool(toolWrapper.shortName, project) } return profile }
apache-2.0
e7f123ef68eb32354f1389249d0a7c28
33.485507
180
0.753888
5.067093
false
false
false
false
Automattic/Automattic-Tracks-Android
AutomatticTracks/src/main/java/com/automattic/android/tracks/crashlogging/internal/SentryCrashLogging.kt
1
5379
package com.automattic.android.tracks.crashlogging.internal import android.app.Application import com.automattic.android.tracks.crashlogging.CrashLogging import com.automattic.android.tracks.crashlogging.CrashLoggingDataProvider import com.automattic.android.tracks.crashlogging.CrashLoggingUser import com.automattic.android.tracks.crashlogging.ExtraKnownKey import com.automattic.android.tracks.crashlogging.PerformanceMonitoringConfig.Disabled import com.automattic.android.tracks.crashlogging.PerformanceMonitoringConfig.Enabled import com.automattic.android.tracks.crashlogging.eventLevel import io.sentry.Breadcrumb import io.sentry.SentryEvent import io.sentry.SentryLevel import io.sentry.SentryOptions import io.sentry.android.fragment.FragmentLifecycleIntegration import io.sentry.protocol.Message import io.sentry.protocol.User import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch internal class SentryCrashLogging constructor( application: Application, private val dataProvider: CrashLoggingDataProvider, private val sentryWrapper: SentryErrorTrackerWrapper, applicationScope: CoroutineScope ) : CrashLogging { init { sentryWrapper.initialize(application) { options -> options.apply { dsn = dataProvider.sentryDSN environment = dataProvider.buildType release = dataProvider.releaseName tracesSampleRate = when (val perfConfig = dataProvider.performanceMonitoringConfig) { Disabled -> null is Enabled -> perfConfig.sampleRate } isDebug = dataProvider.enableCrashLoggingLogs setTag("locale", dataProvider.locale?.language ?: "unknown") setBeforeBreadcrumb { breadcrumb, _ -> if (breadcrumb.type == "http") null else breadcrumb } addIntegration( FragmentLifecycleIntegration( application, enableFragmentLifecycleBreadcrumbs = false, enableAutoFragmentLifecycleTracing = true ) ) isEnableAutoSessionTracking = true beforeSend = SentryOptions.BeforeSendCallback { event, _ -> if (!dataProvider.crashLoggingEnabled()) return@BeforeSendCallback null dropExceptionIfRequired(event) appendExtra(event) event } } } applicationScope.launch { dataProvider.user.collect { sentryWrapper.setUser(it?.toSentryUser()) } } applicationScope.launch { dataProvider.applicationContextProvider.collect { sentryWrapper.setTags(it) } } } private fun appendExtra(event: SentryEvent) { event.setExtras( dataProvider.provideExtrasForEvent( currentExtras = mergeKnownKeysWithValues(event), eventLevel = event.eventLevel ) ) } private fun mergeKnownKeysWithValues(event: SentryEvent): Map<ExtraKnownKey, String> = dataProvider.extraKnownKeys() .associateWith { knownKey -> event.getExtra(knownKey) } .filterValues { it != null } .mapValues(Any::toString) private fun dropExceptionIfRequired(event: SentryEvent) { event.exceptions?.lastOrNull()?.let { lastException -> if (dataProvider.shouldDropWrappingException( lastException.module.orEmpty(), lastException.type.orEmpty(), lastException.value.orEmpty() ) ) { event.exceptions?.remove(lastException) } } } override fun recordEvent(message: String, category: String?) { val breadcrumb = Breadcrumb().apply { this.category = category this.type = "default" this.message = message this.level = SentryLevel.INFO } sentryWrapper.addBreadcrumb(breadcrumb) } override fun recordException(exception: Throwable, category: String?) { val breadcrumb = Breadcrumb().apply { this.category = category this.type = "error" this.message = exception.toString() this.level = SentryLevel.ERROR } sentryWrapper.addBreadcrumb(breadcrumb) } override fun sendReport(exception: Throwable?, tags: Map<String, String>, message: String?) { val event = SentryEvent(exception).apply { this.message = Message().apply { this.message = message } this.level = if (exception != null) SentryLevel.ERROR else SentryLevel.INFO this.appendTags(tags) } sentryWrapper.captureEvent(event) } private fun SentryEvent.appendTags(tags: Map<String, String>) { for ((key, value) in tags) { this.setTag(key, value) } } private fun CrashLoggingUser.toSentryUser(): User = User().let { sentryUser -> sentryUser.email = email sentryUser.username = username sentryUser.id = userID sentryUser } }
gpl-2.0
5fd2aafeff1616db21de84ddc6a51534
36.354167
97
0.621305
5.373626
false
false
false
false