repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
stripe/stripe-android
wechatpay/src/main/java/com/stripe/android/payments/wechatpay/WeChatPayAuthActivity.kt
1
4959
package com.stripe.android.payments.wechatpay import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import androidx.annotation.VisibleForTesting import androidx.appcompat.app.AppCompatActivity import com.stripe.android.StripeIntentResult import com.stripe.android.core.exception.StripeException import com.stripe.android.model.WeChat import com.stripe.android.payments.PaymentFlowResult import com.stripe.android.payments.wechatpay.reflection.DefaultWeChatPayReflectionHelper import com.stripe.android.payments.wechatpay.reflection.WeChatPayReflectionHelper import java.lang.reflect.InvocationHandler import java.lang.reflect.Method internal class WeChatPayAuthActivity : AppCompatActivity(), InvocationHandler { // TODO(ccen): inject reflectionHelper as a singleton @VisibleForTesting internal var reflectionHelperProvider: () -> WeChatPayReflectionHelper = { DefaultWeChatPayReflectionHelper() } private val reflectionHelper by lazy { reflectionHelperProvider() } private val weChatApi by lazy { reflectionHelper.createWXAPI(this) } private val iWXAPIEventHandler by lazy { reflectionHelper.createIWXAPIEventHandler(this) } private var clientSecret: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) runCatching { requireNotNull( WeChatPayAuthContract.Args.fromIntent(intent), { NULL_ARG_MSG } ).let { clientSecret = it.clientSecret launchWeChat( it.weChat ) } }.onFailure { Log.d(TAG, "incorrect Intent") finishWithResult(StripeIntentResult.Outcome.FAILED, it) } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) reflectionHelper.handleIntent(weChatApi, intent, iWXAPIEventHandler) Log.d(TAG, "onNewIntent - callback from IWXAPI") } override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? { // IWXAPIEventHandler.onReq(BaseReq var1) if (method?.name == "onReq") { // no-op } // IWXAPIEventHandler.onResp(BaseResp var1) else if (method?.name == "onResp") { val resp = args?.get(0) resp?.let { val errorCode = reflectionHelper.getRespErrorCode(resp) Log.d(TAG, "onResp with errCode: $errorCode") when (errorCode) { WECHAT_PAY_ERR_OK -> { finishWithResult(StripeIntentResult.Outcome.SUCCEEDED) } WECHAT_PAY_ERR_USER_CANCEL -> { finishWithResult(StripeIntentResult.Outcome.CANCELED) } else -> { finishWithResult( StripeIntentResult.Outcome.FAILED, IllegalStateException("$FAILS_WITH_CODE $errorCode") ) } } } ?: run { finishWithResult( StripeIntentResult.Outcome.FAILED, IllegalStateException(NULL_RESP) ) } } return null } private fun launchWeChat(weChat: WeChat) { if (reflectionHelper.registerApp(weChatApi, weChat.appId)) { Log.d(TAG, "registerApp success") reflectionHelper.sendReq(weChatApi, reflectionHelper.createPayReq(weChat)) } else { Log.d(TAG, "registerApp failure") finishWithResult( StripeIntentResult.Outcome.FAILED, IllegalStateException(REGISTRATION_FAIL) ) } } private fun finishWithResult( @StripeIntentResult.Outcome flowOutcome: Int, exception: Throwable? = null ) { Log.d(TAG, "finishWithResult with flowOutcome: $flowOutcome") val paymentFlowResult = PaymentFlowResult.Unvalidated( clientSecret = clientSecret, flowOutcome = flowOutcome, exception = exception?.let { StripeException.create(exception) } ) setResult( Activity.RESULT_OK, Intent() .putExtras(paymentFlowResult.toBundle()) ) finish() } companion object { const val TAG = "WeChatPayAuthActivity" const val NULL_ARG_MSG = "WeChatPayAuthContract.Args is null" const val FAILS_WITH_CODE = "WeChatPay fails with errorCode:" const val NULL_RESP = "WeChatPay BaseResp is PayResp" const val REGISTRATION_FAIL = "WeChatPay registerApp fails" const val WECHAT_PAY_ERR_OK = 0 // BaseResp.ErrCode.ERR_OK const val WECHAT_PAY_ERR_USER_CANCEL = -2 // BaseResp.ErrCode.ERR_USER_CANCEL } }
mit
51e3b9b8b9f4d25cb3950a8640dd918a
38.047244
94
0.616253
4.876106
false
false
false
false
vanniktech/gradle-code-quality-tools-plugin
src/main/kotlin/com/vanniktech/code/quality/tools/CpdExtension.kt
1
695
package com.vanniktech.code.quality.tools open class CpdExtension { /** * Ability to enable or disable only cpd for every subproject that is not ignored. * @since 0.6.0 */ var enabled: Boolean = true /** @since 0.6.0 */ var source: String = "src" /** @since 0.6.0 */ var language: String = "java" /** * If set to false or true it overrides {@link CodeQualityToolsPluginExtension#failEarly}. * @since 0.6.0 */ var ignoreFailures: Boolean? = null /** * A positive integer indicating the minimum token count to trigger a CPD match. * @since 0.6.0 */ @Suppress("Detekt.MagicNumber") // Will be fixed with RC12. var minimumTokenCount: Int = 50 }
apache-2.0
361d1b7d6d275fdbd00d39d925451dc2
23.821429
92
0.656115
3.601036
false
false
false
false
QingMings/flashair
src/main/kotlin/com/iezview/model/Camera.kt
1
2517
package com.iezview.model import tornadofx.* import java.util.* import java.util.concurrent.LinkedBlockingDeque import javax.json.JsonObject /** * Created by shishifanbuxie on 2017/4/11. * 相机 model */ class Camera():JsonModel{ var id =UUID.randomUUID() // fun idProperty() = getProperty(Camera::id) var name by property<String>() fun nameProperty() =getProperty(Camera::name) var ip by property<String>() fun ipProperty() =getProperty(Camera::ip) var online by property<Int>() fun onlineProperty()=getProperty(Camera::online) var currimg by property<String>() fun currimgProperty()=getProperty(Camera::currimg) var currpath by property<String>() fun currpathProperty()=getProperty(Camera::currpath) var lastwrite by property<String>() fun lastwriteProperty()=getProperty(Camera::lastwrite) var queue by property(LinkedBlockingDeque<JsonObject>(1))//提供一个容量为150的阻塞队列 fun queueProperty()=getProperty(Camera::queue) var photosize by property("0") fun photosizeProperty()=getProperty(Camera::photosize) var filemap by property<HashMap<String,String>>() override fun updateModel(json: JsonObject) { super.updateModel(json) with(json){ id=uuid("id") name=string("name") ip=string("ip") online=int("online") currimg=string("currimg") currpath=string("currpath") lastwrite=string("lastwrite") photosize=string("photosize") } } override fun toJSON(json: JsonBuilder) { with(json){ add("id",id) add("name",name) add("ip",ip) // add("online",online) // add("currimg",currimg) // add("currpath",currpath) } } override fun toString(): String { return "Camera(id=$id,name=$name,ip=$ip,online=$online,currimg=$currimg,currpath=$currpath,lastwrite=$lastwrite,photosize=$photosize)" } } class CameraModel() : ItemViewModel<Camera>(Camera()) { // val id = bind { item?.idProperty() } val name = bind(Camera::nameProperty,true) val ip = bind (Camera::ipProperty,true) val online = bind (Camera::onlineProperty,true) val currimg = bind (Camera::currimgProperty,true) val currpath = bind (Camera::currpathProperty,true) } /** * */ class CameraState() { companion object { val onLine = 1 val offLine = 0 val errorConn = -1 } }
mit
55ec31642811c39816781f14e16057f6
28.987952
142
0.635195
3.817485
false
false
false
false
sksamuel/scrimage
scrimage-format-png/src/main/kotlin/com/sksamuel/scrimage/format/png/PaethPredictor.kt
1
507
package com.sksamuel.scrimage.format.png import kotlin.math.abs object PaethPredictor { fun predict(left: Int, up: Int, upleft: Int): Int { val p = left + up - upleft // initial estimate val pa = abs(p - left) // distances to a, b, c val pb = abs(p - up) val pc = abs(p - upleft) // return nearest of a, b, c // breaking ties in order a, b, c return when { pa <= pb && pa <= pc -> left pb <= pc -> up else -> upleft } } }
apache-2.0
3b57c15a4b7fe6f4b6b2b4eb4b707f0e
25.684211
54
0.532544
3.335526
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/game/GameManager.kt
1
5134
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * 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 de.sudoq.model.game import de.sudoq.model.persistence.IRepo import de.sudoq.model.persistence.xml.game.IGamesListRepo import de.sudoq.model.persistence.xml.sudoku.ISudokuRepoProvider import de.sudoq.model.profile.ProfileManager import de.sudoq.model.sudoku.SudokuManager import de.sudoq.model.sudoku.complexity.Complexity import de.sudoq.model.sudoku.sudokuTypes.SudokuType import de.sudoq.model.sudoku.sudokuTypes.SudokuTypes import java.io.File import java.util.* /** * Singleton for creating and loading sudoku games. */ class GameManager(private var profile: ProfileManager, private var gameRepo: IRepo<Game>, private var gamesListRepo: IGamesListRepo, val sudokuTypeRepo: IRepo<SudokuType>) { private var games: MutableList<GameData> /** * Creates a new gam and sets up the necessary files. * * @param type The type of the [Sudoku] * @param complexity The complexity of the Sudoku * @param assistsances The available assistances for the game * @return The new [Game] * */ fun newGame( type: SudokuTypes, complexity: Complexity, assistances: GameSettings, sudokuDir: File, sudokuRepoProvider: ISudokuRepoProvider ): Game { val sm = SudokuManager(sudokuTypeRepo, sudokuRepoProvider) val sudoku = sm.getNewSudoku(type, complexity) sm.usedSudoku(sudoku) //TODO warum instanziierung, wenn laut doc singleton? val newGameID = gameRepo.create().id //due to interface we cannot pass sudoku to the new game val game = Game(newGameID, sudoku) game.setAssistances(assistances) gameRepo.update(game) val gameData = GameData( game.id, Date(), game.isFinished(), game.sudoku!!.sudokuType?.enumType!!, game.sudoku!!.complexity!! ) games.add(gameData) gamesListRepo.saveGamesFile(games) return game } /** * Loads an existing [Game] of the current player by id. * * @param id die Id des zu ladenden Spiels * @return Das geladene Spiel, null falls kein Spiel zur angegebenen id existiert * @throws IllegalArgumentException if there is no game with that id or if id is not positive. */ fun load(id: Int): Game { require(id > 0) { "invalid id" } return gameRepo.read(id) } /** * Save a Game to XML. * * @param game [Game] to save */ fun save(game: Game) { gameRepo.update(game) updateGameInList(game) profile.saveChanges() gamesListRepo.saveGamesFile(games) } private fun updateGameInList(game: Game) { val oldGameData = games.find { it.id == game.id }!! val newGameData = GameData( oldGameData.id, Date(), game.isFinished(), oldGameData.type, oldGameData.complexity ) games.remove(oldGameData) games.add(newGameData) games = games.sortedDescending().toMutableList() } /** * Deletes a [Game] by id from memory and the list. * If no game is found, nothing happens. * * @param id ID of the game to remove */ fun deleteGame(id: Int) { if (id == profile.currentGame) { profile.currentGame = ProfileManager.NO_GAME profile.saveChanges() //save 'currentGameID' in xml (otherwise menu will offer 'continue') } gameRepo.delete(id) updateGamesList() } /** * A list data of all games of a player. * Sorted by unfinished first then by most recently played //TODO confirm with test * * @return the list */ val gameList: List<GameData> get() = games /** * Deletes no longer existing [Game]s from the list. * */ fun updateGamesList() { gamesListRepo.saveGamesFile(games.filter { gamesListRepo.fileExists(it.id) }) } /** * Deletes all finished [Games] from storage and the current list */ fun deleteFinishedGames() { games.filter { it.isFinished } .forEach { gameRepo.delete(it.id) } updateGamesList() } init{ this.games = gamesListRepo.load() } }
gpl-3.0
dca7b9b58dc47d19a4653b8c69137256
31.0875
243
0.645821
4.242149
false
false
false
false
AndroidX/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/codegen/kotlin/KotlinCodeBlock.kt
3
5307
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.codegen.kotlin import androidx.room.compiler.codegen.CodeLanguage import androidx.room.compiler.codegen.KCodeBlock import androidx.room.compiler.codegen.KCodeBlockBuilder import androidx.room.compiler.codegen.TargetLanguage import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.codegen.XFunSpec import androidx.room.compiler.codegen.XMemberName import androidx.room.compiler.codegen.XPropertySpec import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.codegen.XTypeSpec internal class KotlinCodeBlock( internal val actual: KCodeBlock ) : KotlinLang(), XCodeBlock { override fun toString() = actual.toString() internal class Builder : KotlinLang(), XCodeBlock.Builder { internal val actual = KCodeBlockBuilder() override fun add(code: XCodeBlock) = apply { require(code is KotlinCodeBlock) actual.add(code.actual) } override fun add(format: String, vararg args: Any?) = apply { val processedFormat = processFormatString(format) val processedArgs = processArgs(args) actual.add(processedFormat, *processedArgs) } override fun addStatement(format: String, vararg args: Any?) = apply { val processedFormat = processFormatString(format) val processedArgs = processArgs(args) actual.addStatement(processedFormat, *processedArgs) } override fun addLocalVariable( name: String, typeName: XTypeName, isMutable: Boolean, assignExpr: XCodeBlock? ) = apply { val varOrVal = if (isMutable) "var" else "val" if (assignExpr != null) { require(assignExpr is KotlinCodeBlock) actual.addStatement( "$varOrVal %L: %T = %L", name, typeName.kotlin, assignExpr.actual ) } else { actual.addStatement( "$varOrVal %L: %T", name, typeName.kotlin, ) } } override fun beginControlFlow(controlFlow: String, vararg args: Any?) = apply { val processedControlFlow = processFormatString(controlFlow) val processedArgs = processArgs(args) actual.beginControlFlow(processedControlFlow, *processedArgs) } override fun nextControlFlow(controlFlow: String, vararg args: Any?) = apply { val processedControlFlow = processFormatString(controlFlow) val processedArgs = processArgs(args) actual.nextControlFlow(processedControlFlow, *processedArgs) } override fun endControlFlow() = apply { actual.endControlFlow() } override fun indent() = apply { actual.indent() } override fun unindent() = apply { actual.unindent() } override fun build(): XCodeBlock { return KotlinCodeBlock(actual.build()) } // No need to really process 'format' since we use '%' as placeholders, but check for // JavaPoet placeholders to hunt down bad migrations to XPoet. private fun processFormatString(format: String): String { JAVA_POET_PLACEHOLDER_REGEX.find(format)?.let { error("Bad JavaPoet placeholder in XPoet at range ${it.range} of input: '$format'") } return format } // Unwraps room.compiler.codegen types to their KotlinPoet actual // TODO(b/247242375): Consider improving by wrapping args. private fun processArgs(args: Array<out Any?>): Array<Any?> { return Array(args.size) { index -> val arg = args[index] if (arg is TargetLanguage) { check(arg.language == CodeLanguage.KOTLIN) { "$arg is not KotlinCode" } } when (arg) { is XTypeName -> arg.kotlin is XMemberName -> arg.kotlin is XTypeSpec -> (arg as KotlinTypeSpec).actual is XPropertySpec -> (arg as KotlinPropertySpec).actual is XFunSpec -> (arg as KotlinFunSpec).actual is XCodeBlock -> (arg as KotlinCodeBlock).actual else -> arg } } } } companion object { private val JAVA_POET_PLACEHOLDER_REGEX = "(\\\$L)|(\\\$T)|(\\\$N)|(\\\$S)|(\\\$W)".toRegex() } }
apache-2.0
5edfd20bda39ddea0f56cfad6815d191
36.111888
99
0.602789
4.88674
false
false
false
false
Jay-Goo/RangeSeekBar
app/src/main/java/com/jaygoo/demo/fragments/VerticalSeekBarFragment.kt
1
4642
package com.jaygoo.demo.fragments import android.graphics.Color import android.view.View import com.jaygoo.demo.R import com.jaygoo.widget.* import kotlinx.android.synthetic.main.fragment_range.* import kotlinx.android.synthetic.main.fragment_step.* import kotlinx.android.synthetic.main.fragment_vertical.* import java.util.ArrayList /** // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ______`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖保佑 永无BUG * ===================================================== * 作 者:JayGoo * 创建日期:2019-06-13 * 描 述: * ===================================================== */ class VerticalSeekBarFragment: BaseFragment() { override fun getLayoutId(): Int { return R.layout.fragment_vertical } override fun initView(view: View) { sb_vertical_2?.setIndicatorTextDecimalFormat("0.0") sb_vertical_2?.setProgress(0f, 100f) changeSeekBarThumb(sb_vertical_2.leftSeekBar, sb_vertical_2.leftSeekBar.progress) changeSeekBarThumb(sb_vertical_2.rightSeekBar, sb_vertical_2.rightSeekBar.progress) sb_vertical_2?.setOnRangeChangedListener(object : OnRangeChangedListener { override fun onRangeChanged(rangeSeekBar: RangeSeekBar, leftValue: Float, rightValue: Float, isFromUser: Boolean) { changeSeekBarThumb(rangeSeekBar.leftSeekBar, leftValue) changeSeekBarThumb(rangeSeekBar.rightSeekBar, rightValue) } override fun onStartTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) { } override fun onStopTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) { } }) sb_vertical_3?.setIndicatorTextDecimalFormat("0") sb_vertical_4?.setIndicatorTextDecimalFormat("0") sb_vertical_4?.setIndicatorTextStringFormat("%s%%") sb_vertical_4?.setProgress(30f, 60.6f) sb_vertical_6?.setProgress(30f) sb_vertical_7?.setProgress(40f, 80f) sb_vertical_8?.setIndicatorTextDecimalFormat("0.0") val stepsDrawables = ArrayList<Int>() stepsDrawables.add(R.drawable.step_1) stepsDrawables.add(R.drawable.step_2) stepsDrawables.add(R.drawable.step_3) stepsDrawables.add(R.drawable.step_1) sb_vertical_9?.setStepsDrawable(stepsDrawables) changeSeekBarIndicator(sb_vertical_9.leftSeekBar, sb_vertical_9.leftSeekBar.progress) changeSeekBarIndicator(sb_vertical_9.rightSeekBar, sb_vertical_9.rightSeekBar.progress) sb_vertical_9?.setOnRangeChangedListener(object : OnRangeChangedListener { override fun onRangeChanged(rangeSeekBar: RangeSeekBar, leftValue: Float, rightValue: Float, isFromUser: Boolean) { changeSeekBarIndicator(rangeSeekBar.leftSeekBar, leftValue) changeSeekBarIndicator(rangeSeekBar.rightSeekBar, rightValue) } override fun onStartTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) { } override fun onStopTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) { } }) } private fun changeSeekBarThumb(seekbar: SeekBar, value: Float){ if (value < 33){ seekbar.indicatorBackgroundColor = Utils.getColor(activity, R.color.colorAccent) seekbar.setThumbDrawableId(R.drawable.thumb_green, seekbar.thumbWidth, seekbar.thumbHeight) }else if (value < 66){ seekbar.indicatorBackgroundColor = Utils.getColor(activity, R.color.colorProgress) seekbar.setThumbDrawableId(R.drawable.thumb_yellow, seekbar.thumbWidth, seekbar.thumbHeight) }else{ seekbar.indicatorBackgroundColor = Utils.getColor(activity, R.color.colorRed) seekbar.setThumbDrawableId(R.drawable.thumb_red, seekbar.thumbWidth, seekbar.thumbHeight) } } private fun changeSeekBarIndicator(seekbar: SeekBar, value: Float){ seekbar.showIndicator(true) if (Utils.compareFloat(value, 0f, 3) == 0 || Utils.compareFloat(value, 100f, 3) == 0){ seekbar.setIndicatorText("smile") }else if (Utils.compareFloat(value, 100/3f, 3) == 0){ seekbar.setIndicatorText("naughty") }else if (Utils.compareFloat(value, 200/3f, 3) == 0){ seekbar.setIndicatorText("lovely") }else{ seekbar.showIndicator(false) } } }
apache-2.0
10a7e20d7d54ef57f155d73c18660f71
34.744186
118
0.621258
3.471386
false
false
false
false
Dr-Horv/Advent-of-Code-2017
src/main/kotlin/solutions/day25/Day25.kt
1
2362
package solutions.day25 import solutions.Solver import utils.splitAtWhitespace import java.lang.RuntimeException import java.util.regex.Pattern enum class Direction { LEFT, RIGHT } fun Int.move(direction: Direction) = when(direction) { Direction.LEFT -> this - 1 Direction.RIGHT -> this + 1 } fun String.toDirection(): Direction = when(this) { "left" -> Direction.LEFT "right" -> Direction.RIGHT else -> throw RuntimeException("Unparsable direction $this") } data class State(val onZero: Triple<Int, Direction, String>, val onOne: Triple<Int, Direction, String>) class Day25: Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val inputAsOneString = input.joinToString("\n") val regex = "in state (\\w):\\s+if the current value is (\\d):\\s+- write the value (\\d)\\.\\s+- Move one slot to the (\\w+)\\.\\s+- Continue with state (\\w)\\.\\s+if the current value is (\\d):\\s+- write the value (\\d)\\.\\s+- Move one slot to the (\\w+)\\.\\s+- Continue with state (\\w)\\." val pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE) val matcher = pattern.matcher(inputAsOneString) val states = mutableMapOf<String, State>() while (matcher.find()) { val name = matcher.group(1) states.put(name, State( Triple(matcher.group(3).toInt(), matcher.group(4).toDirection(), matcher.group(5)), Triple(matcher.group(7).toInt(), matcher.group(8).toDirection(), matcher.group(9)) )) } val firstLine = input[0] val secondLine = input[1] var next = firstLine[firstLine.lastIndex-1].toString() var position = 0 var iterationsLeft = secondLine.splitAtWhitespace()[5].toInt() val values = mutableMapOf<Int, Int>().withDefault { 0 } while (iterationsLeft > 0) { val s = states.getValue(next) val value = values.getValue(position) val (write, direction, nextState) = if(value == 0) { s.onZero } else { s.onOne } values[position] = write position = position.move(direction) next = nextState iterationsLeft-- } return values.values.sum().toString() } }
mit
29b588fe901c763c996f03f4467af352
30.078947
305
0.594412
4.100694
false
false
false
false
satamas/fortran-plugin
src/test/kotlin/org/jetbrains/fortran/lang/resolve/FortranResolveTest.kt
1
11154
package org.jetbrains.fortran.lang.resolve import com.intellij.psi.util.PsiTreeUtil import com.intellij.testFramework.fixtures.BasePlatformTestCase import org.jetbrains.fortran.lang.psi.FortranDataPath import org.jetbrains.fortran.lang.psi.FortranEntityDecl import org.jetbrains.fortran.lang.psi.FortranStmt import org.jetbrains.fortran.lang.psi.impl.FortranConstructNameDeclImpl import org.jetbrains.fortran.lang.psi.impl.FortranLabelDeclImpl import org.jetbrains.fortran.lang.psi.impl.FortranUnitDeclImpl import org.jetbrains.fortran.lang.psi.impl.FortranWriteStmtImpl import org.junit.Test class FortranResolveTest : BasePlatformTestCase() { override fun getTestDataPath() = "src/test/resources/resolve" // Labels @Test fun testFindLabelUsages() { val usageInfos = myFixture.testFindUsages("Label.f") assertEquals(3, usageInfos.size) } @Test fun testLabelReference() { myFixture.configureByFiles("Label.f") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent assertEquals(10, (element.references[0].resolve() as FortranLabelDeclImpl).getLabelValue()) } @Test fun testFindLabelUsagesInSpecification() { val usageInfos = myFixture.testFindUsages("LabelsInSpecifications.f95") assertEquals(1, usageInfos.size) } @Test fun testLabelReferenceInSpecification() { myFixture.configureByFiles("LabelsInSpecifications.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent assertEquals(1, (element.references[0].resolve() as FortranLabelDeclImpl).getLabelValue()) } // Construct Names @Test fun testConstructNameUsages() { val usageInfos = myFixture.testFindUsages("ConstructName.f95") assertEquals(2, usageInfos.size) } @Test fun testConstructNameReference() { myFixture.configureByFiles("ConstructName.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent assertEquals("ifconstruct", (element.references[0].resolve() as FortranConstructNameDeclImpl).getLabelValue()) } // Name references (variables and fields) @Test fun testUseOnlyAvailable() { myFixture.configureByFiles("UseOnlyAvailable.f95", "Module.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranEntityDecl assertEquals("x", declaration.name) assertEquals("Module.f95", declaration.containingFile.name) } @Test fun testUseOnlyNotAvailable() { myFixture.configureByFiles("UseOnlyNotAvailable.f95", "Module.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent assertNull(element.reference?.resolve()) } @Test fun testComponents() { myFixture.configureByFiles("Components.f95", "Module.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranEntityDecl assertEquals("x", declaration.name) assertEquals("Module.f95", declaration.containingFile.name) } @Test fun testNoExcessiveUsages() { val usageInfos = myFixture.testFindUsages("Components.f95", "Module.f95") assertEquals(3, usageInfos.size) } @Test fun testRenamedType() { myFixture.configureByFiles("RenamedType.f95", "Module.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranEntityDecl assertEquals("x", declaration.name) assertEquals("Module.f95", declaration.containingFile.name) } @Test fun testRenamedIsNotAvailable() { myFixture.configureByFiles("RenamedIsNotAvailable.f95", "FarAwayModule.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranDataPath assertEquals("pi", declaration.name) assertEquals(FortranWriteStmtImpl::class.java, PsiTreeUtil.getParentOfType(declaration, FortranStmt::class.java)!!::class.java) } @Test fun testRenamedIsNotAvailable2() { myFixture.configureByFiles("RenamedIsNotAvailable2.f95", "FarAwayModule.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranDataPath assertEquals("pi", declaration.name) assertEquals(FortranWriteStmtImpl::class.java, PsiTreeUtil.getParentOfType(declaration, FortranStmt::class.java)!!::class.java) } @Test fun testDeepUsage() { myFixture.configureByFiles("DeepUsage.f95", "CloseModule.f95", "AwayModule.f95", "FarAwayModule.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranEntityDecl assertEquals("data", declaration.name) assertEquals("FarAwayModule.f95", declaration.containingFile.name) } @Test fun testDeepPiUsage() { myFixture.configureByFiles("DeepPiUsage.f95", "CloseModule.f95", "AwayModule.f95", "FarAwayModule.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranEntityDecl assertEquals("renamed_pi", declaration.name) assertEquals("AwayModule.f95", declaration.containingFile.name) } @Test fun testDeepEUsage() { myFixture.configureByFiles("DeepEUsage.f95", "CloseModule.f95", "AwayModule.f95", "FarAwayModule.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranEntityDecl assertEquals("E", declaration.name) assertEquals("FarAwayModule.f95", declaration.containingFile.name) } @Test fun testFunction() { val usageInfos = myFixture.testFindUsages("Function.f95") assertEquals(2, usageInfos.size) } @Test fun testSpecificationStmts() { val usageInfos = myFixture.testFindUsages("SpecificationStmts.f95") assertEquals(11, usageInfos.size) } @Test fun testTypeSearch() { myFixture.configureByFiles("typeSearch.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent assertEquals("x", (element.reference?.resolve() as FortranEntityDecl).name) } @Test fun testNoLoops() { myFixture.configureByFiles("TwinOne.f95", "TwinTwo.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent assertNull(element.reference?.resolve()) } @Test fun testSubmodule() { myFixture.configureByFiles("ProgramWithSubmodule.f95", "ModuleWithSubmodule.f95", "SubmoduleWithSubmodule.f95", "Submodule.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranEntityDecl assertEquals("needle", declaration.name) assertEquals("Submodule.f95", declaration.containingFile.name) } @Test fun testSubmoduleType() { myFixture.configureByFiles("ProgramWithSubmoduleType.f95", "ModuleWithSubmodule.f95", "SubmoduleWithSubmodule.f95", "Submodule.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranEntityDecl assertEquals("subtype", declaration.name) assertEquals("Submodule.f95", declaration.containingFile.name) } @Test fun testMethod() { myFixture.configureByFiles("Method.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent assertEquals("print", (element.reference?.resolve() as FortranEntityDecl).name) } // Common block @Test fun testCommonBlocks() { // Here we find all N usages of the common block. In IDE only N-1 usage will be shown // The block where we use find usages is not shown in IDE val usageInfos = myFixture.testFindUsages("CommonBlocksA.f95", "CommonBlocksB.f95") assertEquals(3, usageInfos.size) } // Implicit @Test fun testImplicitUsages() { val usageInfos = myFixture.testFindUsages("Implicit.f95", "CommonBlocksB.f95", "TwinOne.f95") assertEquals(14, usageInfos.size) } @Test fun testImplicit() { myFixture.configureByFiles("Implicit.f95", "CommonBlocksB.f95", "TwinTwo.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent val declaration = element.reference?.resolve() as FortranDataPath assertEquals("X", declaration.name) assertEquals("Implicit.f95", declaration.containingFile.name) } @Test fun testImplicit2Usages() { val usageInfos = myFixture.testFindUsages("Implicit2.f95") assertEquals(3, usageInfos.size) } @Test fun testNoImplicitStructures() { val usageInfos = myFixture.testFindUsages("Implicit3.f95") assertEquals(1, usageInfos.size) } // Interface @Test fun testInterface() { myFixture.configureByFiles("Interface.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent assertEquals("F", ((element.reference as FortranPathReferenceImpl?)?.multiResolve()?.firstOrNull() as FortranEntityDecl).name) } @Test fun testInterfaceUsages() { val usageInfos = myFixture.testFindUsages("Interface2.f95") assertEquals(6, usageInfos.size) } @Test fun testNamedInterfaceUsages() { val usageInfos = myFixture.testFindUsages("NamedInterface.f95", "ProgramWithNamedInterface.f95") assertEquals(3, usageInfos.size) } @Test fun testNamedInterfaceUsages2() { val usageInfos = myFixture.testFindUsages("ProgramWithNamedInterface2.f95", "NamedInterface2.f95") assertEquals(0, usageInfos.size) } // enum @Test fun testEnum() { myFixture.configureByFiles("Enum.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent assertEquals("RED", ((element.reference as FortranPathReferenceImpl?)?.multiResolve()?.firstOrNull() as FortranEntityDecl).name) } // file-unit-number @Test fun testFileUnitNumber() { myFixture.configureByFiles("testFileUnitNumber.f95") val element = myFixture.file.findElementAt(myFixture.caretOffset)!!.parent assertEquals(1, ((element.reference as FortranUnitReferenceImpl?)?.multiResolve()?.firstOrNull() as FortranUnitDeclImpl).getUnitValue()) } @Test fun testFindFileUnitNumberUsages() { val usageInfos = myFixture.testFindUsages("testFileUnitNumberUsages.f95") assertEquals(2, usageInfos.size) } }
apache-2.0
088049e54f978c1f6fc89e45921135cd
38.140351
144
0.700914
4.622462
false
true
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/HabitResetStreakButtons.kt
1
3398
package com.habitrpg.android.habitica.ui.views.tasks.form import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import android.view.Gravity import android.view.View import android.view.accessibility.AccessibilityEvent import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.ContextCompat import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.dpToPx import com.habitrpg.android.habitica.models.tasks.HabitResetOption class HabitResetStreakButtons @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { var tintColor: Int = ContextCompat.getColor(context, R.color.brand_300) var selectedResetOption: HabitResetOption = HabitResetOption.DAILY set(value) { field = value removeAllViews() addAllButtons() selectedButton.sendAccessibilityEvent( AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION ) } private lateinit var selectedButton: TextView init { addAllButtons() } private fun addAllButtons() { val lastResetOption = HabitResetOption.values().last() val margin = 16.dpToPx(context) val height = 28.dpToPx(context) for (resetOption in HabitResetOption.values()) { val button = createButton(resetOption) val layoutParams = LayoutParams(0, height) layoutParams.weight = 1f if (resetOption != lastResetOption) { layoutParams.marginEnd = margin } button.textAlignment = View.TEXT_ALIGNMENT_GRAVITY button.gravity = Gravity.CENTER button.layoutParams = layoutParams addView(button) if (resetOption == selectedResetOption) { selectedButton = button } } } private fun createButton(resetOption: HabitResetOption): TextView { val isActive = selectedResetOption == resetOption val button = TextView(context) val buttonText = context.getString(resetOption.nameRes) button.text = buttonText button.contentDescription = toContentDescription(buttonText, isActive) button.background = ContextCompat.getDrawable(context, R.drawable.layout_rounded_bg_content) if (isActive) { button.background.setTint(tintColor) button.setTextColor(ContextCompat.getColor(context, R.color.white)) button.typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) } else { button.background.setTint(ContextCompat.getColor(context, R.color.taskform_gray)) button.setTextColor(ContextCompat.getColor(context, R.color.text_secondary)) button.typeface = Typeface.create("sans-serif", Typeface.NORMAL) } button.setOnClickListener { selectedResetOption = resetOption } return button } private fun toContentDescription(buttonText: CharSequence, isActive: Boolean): String { val statusString = if (isActive) { context.getString(R.string.selected) } else context.getString(R.string.not_selected) return "$buttonText, $statusString" } }
gpl-3.0
d59198aebb0802f1235e755f1f77f466
36.340659
100
0.677163
5.086826
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/liteloader/creator/LiteLoaderTemplate.kt
1
3097
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.liteloader.creator import com.demonwav.mcdev.creator.buildsystem.BuildSystem import com.demonwav.mcdev.platform.BaseTemplate import com.demonwav.mcdev.platform.forge.ForgeModuleType import com.demonwav.mcdev.util.MinecraftTemplates.Companion.LITELOADER_BUILD_GRADLE_TEMPLATE import com.demonwav.mcdev.util.MinecraftTemplates.Companion.LITELOADER_GRADLE_PROPERTIES_TEMPLATE import com.demonwav.mcdev.util.MinecraftTemplates.Companion.LITELOADER_MAIN_CLASS_TEMPLATE import com.demonwav.mcdev.util.MinecraftTemplates.Companion.LITELOADER_SETTINGS_GRADLE_TEMPLATE import com.demonwav.mcdev.util.MinecraftTemplates.Companion.LITELOADER_SUBMODULE_BUILD_GRADLE_TEMPLATE import com.demonwav.mcdev.util.SemanticVersion import com.intellij.openapi.project.Project object LiteLoaderTemplate : BaseTemplate() { fun applyMainClass( project: Project, packageName: String, className: String, modName: String, modVersion: String ): String { val props = mapOf( "PACKAGE_NAME" to packageName, "CLASS_NAME" to className, "MOD_NAME" to modName, "MOD_VERSION" to modVersion ) return project.applyTemplate(LITELOADER_MAIN_CLASS_TEMPLATE, props) } fun applyBuildGradle(project: Project, buildSystem: BuildSystem, mcVersion: SemanticVersion): String { val props = mapOf( "FORGEGRADLE_VERSION" to fgVersion(mcVersion), "GROUP_ID" to buildSystem.groupId, "ARTIFACT_ID" to buildSystem.artifactId, "VERSION" to buildSystem.version ) return project.applyTemplate(LITELOADER_BUILD_GRADLE_TEMPLATE, props) } fun applyGradleProp(project: Project, config: LiteLoaderProjectConfig): String { val props = mapOf( "MC_VERSION" to config.mcVersion.toString(), "MCP_MAPPINGS" to config.mcpVersion.mcpVersion ) return project.applyTemplate(LITELOADER_GRADLE_PROPERTIES_TEMPLATE, props) } fun applySettingsGradle(project: Project, artifactId: String): String { val props = mapOf( "ARTIFACT_ID" to artifactId ) return project.applyTemplate(LITELOADER_SETTINGS_GRADLE_TEMPLATE, props) } fun applySubBuildGradle(project: Project, buildSystem: BuildSystem, mcVersion: SemanticVersion): String { val props = mapOf( "COMMON_PROJECT_NAME" to buildSystem.commonModuleName, "FORGEGRADLE_VERSION" to fgVersion(mcVersion), "ARTIFACT_ID" to buildSystem.artifactId ) return project.applyTemplate(LITELOADER_SUBMODULE_BUILD_GRADLE_TEMPLATE, props) } private fun fgVersion(mcVersion: SemanticVersion): String { // Fixes builds for MC1.12+, requires FG 2.3 return if (mcVersion >= ForgeModuleType.FG23_MC_VERSION) { "2.3" } else { "2.2" } } }
mit
26d9f3d563ef126e085361f94131d5dd
33.797753
109
0.690345
4.399148
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/profile/ProfileViewModel.kt
1
1305
package me.proxer.app.profile import com.gojuno.koptional.None import io.reactivex.Single import io.reactivex.rxkotlin.plusAssign import me.proxer.app.base.BaseViewModel import me.proxer.app.profile.ProfileViewModel.UserInfoWrapper import me.proxer.app.util.extension.buildOptionalSingle import me.proxer.app.util.extension.buildSingle import me.proxer.library.entity.user.UserInfo /** * @author Ruben Gees */ class ProfileViewModel( private val userId: String?, private val username: String? ) : BaseViewModel<UserInfoWrapper>() { override val dataSingle: Single<UserInfoWrapper> get() = Single.fromCallable { validate() } .flatMap { api.user.info(userId, username).buildSingle() } .flatMap { userInfo -> val maybeUcpSingle = when (storageHelper.user?.matches(userId, username) == true) { true -> api.ucp.watchedEpisodes().buildOptionalSingle() false -> Single.just(None) } maybeUcpSingle.map { watchedEpisodes -> UserInfoWrapper(userInfo, watchedEpisodes.toNullable()) } } init { disposables += storageHelper.isLoggedInObservable.subscribe { reload() } } data class UserInfoWrapper(val info: UserInfo, val watchedEpisodes: Int?) }
gpl-3.0
76334e3415ffa2ae17e854948b6f7909
34.27027
113
0.687356
4.438776
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/codeInsight/intention/SetVisibilityIntention.kt
2
2808
/* * 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.codeInsight.intention import com.intellij.codeInsight.template.TemplateManager import com.intellij.codeInsight.template.impl.MacroCallNode import com.intellij.codeInsight.template.impl.TextExpression import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.tang.intellij.lua.codeInsight.template.macro.NamesMacro import com.tang.intellij.lua.comment.psi.LuaDocAccessModifier import com.tang.intellij.lua.psi.LuaClassMethodDef import com.tang.intellij.lua.psi.LuaCommentOwner import com.tang.intellij.lua.psi.LuaFuncBodyOwner class SetVisibilityIntention : FunctionIntention() { override fun isAvailable(bodyOwner: LuaFuncBodyOwner, editor: Editor): Boolean { if (bodyOwner is LuaClassMethodDef) { return bodyOwner.comment?.findTag(LuaDocAccessModifier::class.java) == null } return false } override fun invoke(bodyOwner: LuaFuncBodyOwner, editor: Editor) { if (bodyOwner is LuaCommentOwner) { val comment = bodyOwner.comment val funcBody = bodyOwner.funcBody if (funcBody != null) { val templateManager = TemplateManager.getInstance(editor.project) val template = templateManager.createTemplate("", "") if (comment != null) template.addTextSegment("\n") template.addTextSegment("---@") val typeSuggest = MacroCallNode(NamesMacro("public", "protected", "private")) template.addVariable("visibility", typeSuggest, TextExpression("private"), false) template.addEndVariable() if (comment != null) { editor.caretModel.moveToOffset(comment.textOffset + comment.textLength) } else { template.addTextSegment("\n") val e: PsiElement = bodyOwner editor.caretModel.moveToOffset(e.node.startOffset) } templateManager.startTemplate(editor, template) } } } override fun getFamilyName() = text override fun getText() = "Set Visibility (public/protected/private)" }
apache-2.0
5cf47c292db63bf017f94a7b60bb4b47
41.560606
97
0.683048
4.62603
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/debugger/utils/UIUtils.kt
1
1749
package org.jetbrains.haskell.debugger.utils import com.intellij.notification.Notifications import com.intellij.notification.Notification import com.intellij.notification.NotificationType import javax.swing.JPanel import javax.swing.JComponent import org.jetbrains.haskell.util.gridBagConstraints import java.awt.Insets import javax.swing.JLabel import org.jetbrains.haskell.util.setConstraints import java.awt.GridBagConstraints import javax.swing.Box /** * @author Habibullin Marat */ public class UIUtils { companion object { public fun addLabeledControl(panel: JPanel, row: Int, label: String, component: JComponent, isFill : Boolean = true) { val base = gridBagConstraints { insets = Insets(2, 0, 2, 3) } panel.add(JLabel(label), base.setConstraints { anchor = GridBagConstraints.LINE_START gridx = 0 gridy = row }) panel.add(component, base.setConstraints { gridx = 1 gridy = row fill = if (isFill) GridBagConstraints.HORIZONTAL else GridBagConstraints.NONE weightx = 1.0 }) panel.add(Box.createHorizontalStrut(1), base.setConstraints { gridx = 2 gridy = row weightx = 0.1 }) } public fun notifyCommandInProgress() { val msg = "Some command is in progress, it must finish first" Notifications.Bus.notify(Notification("", "Can't perform action", msg, NotificationType.WARNING)) } } }
apache-2.0
1e78f7bc9090dee0ed4bc5431ffa63c4
34.714286
109
0.582047
5.174556
false
false
false
false
dataloom/datastore
src/main/java/com/openlattice/datastore/search/controllers/GeocodingController.kt
1
3094
package com.openlattice.datastore.search.controllers import com.google.maps.GeoApiContext import com.google.maps.PlaceAutocompleteRequest import com.google.maps.PlacesApi import com.google.maps.model.AutocompletePrediction import com.google.maps.model.GeocodingResult import com.openlattice.geocoding.AutocompleteRequest import com.openlattice.geocoding.GeocodingApi import com.openlattice.geocoding.GeocodingApi.Companion.AUTOCOMPLETE import com.openlattice.geocoding.GeocodingApi.Companion.CONTROLLER import com.openlattice.geocoding.GeocodingApi.Companion.GEOCODE import com.openlattice.geocoding.GeocodingApi.Companion.ID import com.openlattice.geocoding.GeocodingApi.Companion.ID_PATH import com.openlattice.geocoding.GeocodingApi.Companion.PLACE import com.openlattice.geocoding.GeocodingRequest import org.springframework.web.bind.annotation.* import java.util.* import javax.inject.Inject /** * * @author Matthew Tamayo-Rios &lt;[email protected]&gt; */ @RestController @RequestMapping(CONTROLLER) class GeocodingController : GeocodingApi { @Inject private lateinit var geoApiContext: GeoApiContext @PostMapping(value = [AUTOCOMPLETE]) override fun autocomplete(@RequestBody request: AutocompleteRequest): Array<out AutocompletePrediction> { val st = request.sessionToken.orElseGet(UUID::randomUUID) val autocompleteRequest = PlacesApi.placeAutocomplete( geoApiContext, request.input, PlaceAutocompleteRequest.SessionToken(st) ) request.offset.ifPresent { autocompleteRequest.offset(it) } request.location.ifPresent { autocompleteRequest.location(it) } request.radius.ifPresent { autocompleteRequest.radius(it) } request.types.ifPresent { autocompleteRequest.types(it) } request.components.ifPresent { autocompleteRequest.components(*it) } return autocompleteRequest.await() } @GetMapping(value = [PLACE + ID_PATH]) override fun geocodePlace(@PathVariable(ID) placeId: String): Array<out GeocodingResult> { return geocode( GeocodingRequest( Optional.of(""), Optional.of(placeId), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty() ) ) } @PostMapping(value = [GEOCODE]) override fun geocode(@RequestBody request: GeocodingRequest): Array<out GeocodingResult> { val req = if (request.address.isPresent) { com.google.maps.GeocodingApi.geocode(geoApiContext, request.address.get()) } else { com.google.maps.GeocodingApi.reverseGeocode(geoApiContext, request.location.get()) } request.placeId.ifPresent { req.place(it) } request.resultType.ifPresent { req.resultType(*it) } request.locationType.ifPresent { req.locationType(*it) } request.components.ifPresent { req.components(*it) } return req.await() } }
gpl-3.0
87cc6b09b6937ac4b612f4d44f2f6f8a
37.209877
109
0.700711
4.510204
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/webtoons/webtoons/src/WebtoonsFactory.kt
1
2579
package eu.kanade.tachiyomi.extension.all.webtoons import eu.kanade.tachiyomi.multisrc.webtoons.Webtoons import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceFactory import java.text.SimpleDateFormat import java.util.GregorianCalendar import java.util.Locale import java.util.Calendar class WebtoonsFactory : SourceFactory { override fun createSources(): List<Source> = listOf( WebtoonsEN(), WebtoonsID(), WebtoonsTH(), WebtoonsES(), WebtoonsFR(), WebtoonsZH(), ) } class WebtoonsEN : Webtoons("Webtoons.com", "https://www.webtoons.com", "en") class WebtoonsID : Webtoons("Webtoons.com", "https://www.webtoons.com", "id") { // Override ID as part of the name was removed to be more consiten with other enteries override val id: Long = 8749627068478740298 // Android seems to be unable to parse Indonesian dates; we'll use a short hard-coded table // instead. private val dateMap: Array<String> = arrayOf( "Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agu", "Sep", "Okt", "Nov", "Des" ) override fun chapterParseDate(date: String): Long { val expr = Regex("""(\d{4}) ([A-Z][a-z]{2}) (\d+)""").find(date) ?: return 0 val (_, year, monthString, day) = expr.groupValues val monthIndex = dateMap.indexOf(monthString) return GregorianCalendar(year.toInt(), monthIndex, day.toInt()).time.time } } class WebtoonsTH : Webtoons("Webtoons.com", "https://www.webtoons.com", "th", dateFormat = SimpleDateFormat("d MMM yyyy", Locale("th"))) class WebtoonsES : Webtoons("Webtoons.com", "https://www.webtoons.com", "es") { // Android seems to be unable to parse es dates like Indonesian; we'll use a short hard-coded table // instead. private val dateMap: Array<String> = arrayOf( "Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic" ) override fun chapterParseDate(date: String): Long { val expr = Regex("""(\d+)-([a-z]{3})-(\d{4})""").find(date) ?: return 0 val (_, day, monthString, year) = expr.groupValues val monthIndex = dateMap.indexOf(monthString) return GregorianCalendar(year.toInt(), monthIndex, day.toInt()).time.time } } class WebtoonsFR : Webtoons("Webtoons.com", "https://www.webtoons.com", "fr", dateFormat = SimpleDateFormat("d MMM yyyy", Locale.FRENCH)) class WebtoonsZH : Webtoons("Webtoons.com", "https://www.webtoons.com", "zh", "zh-hant", "zh_TW", SimpleDateFormat("yyyy/MM/dd", Locale.TRADITIONAL_CHINESE))
apache-2.0
0874d9b6df994982d1dd0a22044e75a3
45.053571
157
0.659946
3.557241
false
false
false
false
moallemi/gradle-advanced-build-version
src/test/kotlin/me/moallemi/gradle/advancedbuildversion/AdvancedBuildVersionPluginTest.kt
1
6082
/* * Copyright 2020 Reza Moallemi * * 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 me.moallemi.gradle.advancedbuildversion import com.android.build.gradle.AppExtension import com.android.build.gradle.AppPlugin import com.android.build.gradle.FeaturePlugin import com.android.build.gradle.LibraryPlugin import io.mockk.clearAllMocks import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.runs import io.mockk.slot import io.mockk.verifyOrder import me.moallemi.gradle.advancedbuildversion.AdvancedBuildVersionPlugin.Companion.EXTENSION_NAME import me.moallemi.gradle.advancedbuildversion.gradleextensions.AdvancedBuildVersionConfig import me.moallemi.gradle.advancedbuildversion.utils.ANDROID_GRADLE_PLUGIN_ATTRIBUTE_ID import me.moallemi.gradle.advancedbuildversion.utils.ANDROID_GRADLE_PLUGIN_GROUP import me.moallemi.gradle.advancedbuildversion.utils.checkAndroidGradleVersion import me.moallemi.gradle.advancedbuildversion.utils.checkMinimumGradleVersion import org.gradle.api.Action import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.internal.impldep.org.eclipse.jgit.errors.NotSupportedException import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertThrows import org.junit.Before import org.junit.Test class AdvancedBuildVersionPluginTest { private val project: Project = mockk() private lateinit var plugin: AdvancedBuildVersionPlugin @Before fun setUp() { mockkStatic("me.moallemi.gradle.advancedbuildversion.utils.CompatibilityManagerKt") every { checkAndroidGradleVersion(any()) } just runs every { project.extensions } returns mockk() every { project.extensions.create( any(), AdvancedBuildVersionConfig::class.java, any<Project>() ) } returns mockk() val afterEvaluateSlot = slot<Action<in Project>>() every { project.afterEvaluate(capture(afterEvaluateSlot)) } answers { afterEvaluateSlot.captured.execute(project) } plugin = AdvancedBuildVersionPlugin() } @After fun tearDown() { clearAllMocks() } @Test fun `plugin applies successfully on Android Application module`() { val applicationPlugin = mockk<AppPlugin>() val pluginsSlot = slot<Action<in Plugin<*>>>() every { project.plugins.all(capture(pluginsSlot)) } answers { pluginsSlot.captured.execute(applicationPlugin) } every { project.extensions.create( EXTENSION_NAME, AdvancedBuildVersionConfig::class.java, project ) } returns mockk(relaxUnitFun = true) every { project.extensions.getByType(AppExtension::class.java) } returns mockk { every { applicationVariants } returns mockk() } mockGetAndroidPlugin() plugin.apply(project) verifyOrder { checkMinimumGradleVersion() checkAndroidGradleVersion(project) } } @Test fun `fails on applying to Android Library module`() { val libraryPlugin = mockk<LibraryPlugin>() val pluginsSlot = slot<Action<in Plugin<*>>>() every { project.plugins.all(capture(pluginsSlot)) } answers { pluginsSlot.captured.execute(libraryPlugin) } val exception = assertThrows(NotSupportedException::class.java) { plugin.apply(project) } assertEquals(exception.message, "Library module is not supported yet") verifyOrder { checkMinimumGradleVersion() checkAndroidGradleVersion(project) } } @Test fun `fails on applying to Android Feature module`() { val featurePlugin = mockk<FeaturePlugin>() val pluginsSlot = slot<Action<in Plugin<*>>>() every { project.plugins.all(capture(pluginsSlot)) } answers { pluginsSlot.captured.execute(featurePlugin) } val exception = assertThrows(NotSupportedException::class.java) { plugin.apply(project) } assertEquals(exception.message, "Feature module is not supported") verifyOrder { checkMinimumGradleVersion() checkAndroidGradleVersion(project) } } private fun mockGetAndroidPlugin() { every { project.rootProject } returns mockk { every { buildscript } returns mockk { every { configurations } returns mockk { every { getByName("classpath").dependencies } returns mockk { every { iterator() } returns mockk() every { iterator().hasNext() } returns true every { iterator().next() } returns mockk { every { group } returns ANDROID_GRADLE_PLUGIN_GROUP every { name } returns ANDROID_GRADLE_PLUGIN_ATTRIBUTE_ID every { version } returns "3.0.1" } } } } } every { project.buildscript.configurations.getByName("classpath").dependencies } returns mockk { every { iterator() } returns mockk() every { iterator().hasNext() } returns false } every { project.plugins.hasPlugin(any<String>()) } returns true } }
apache-2.0
c99f5e182977c0f7a53b5e02add43694
33.168539
98
0.650444
4.823156
false
false
false
false
InsertKoinIO/koin
core/koin-core/src/commonMain/kotlin/org/koin/core/definition/BeanDefinition.kt
1
3769
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.core.definition import org.koin.core.parameter.ParametersHolder import org.koin.core.qualifier.Qualifier import org.koin.core.registry.ScopeRegistry.Companion.rootScopeQualifier import org.koin.core.scope.Scope import org.koin.ext.getFullName import kotlin.reflect.KClass /** * Koin bean definition * main structure to make definition in Koin * * @author Arnaud Giuliani */ data class BeanDefinition<T>( val scopeQualifier: Qualifier, val primaryType: KClass<*>, var qualifier: Qualifier? = null, val definition: Definition<T>, val kind: Kind, var secondaryTypes: List<KClass<*>> = listOf(), ) { var callbacks: Callbacks<T> = Callbacks() @PublishedApi internal var _createdAtStart = false override fun toString(): String { val defKind = kind.toString() val defType = "'${primaryType.getFullName()}'" val defName = qualifier?.let { ",qualifier:$qualifier" } ?: "" val defScope = scopeQualifier.let { if (it == rootScopeQualifier) "" else ",scope:${scopeQualifier}" } val defOtherTypes = if (secondaryTypes.isNotEmpty()) { val typesAsString = secondaryTypes.joinToString(",") { it.getFullName() } ",binds:$typesAsString" } else "" return "[$defKind:$defType$defName$defScope$defOtherTypes]" } override fun equals(other: Any?): Boolean { if (this === other) return true other as BeanDefinition<*> if (primaryType != other.primaryType) return false if (qualifier != other.qualifier) return false if (scopeQualifier != other.scopeQualifier) return false return true } fun hasType(clazz: KClass<*>): Boolean { return primaryType == clazz || secondaryTypes.contains(clazz) } fun `is`(clazz: KClass<*>, qualifier: Qualifier?, scopeDefinition: Qualifier): Boolean { return hasType(clazz) && this.qualifier == qualifier && this.scopeQualifier == scopeDefinition } // fun canBind(primary: KClass<*>, secondary: KClass<*>): Boolean { // return primaryType == primary && secondaryTypes.contains(secondary) // } override fun hashCode(): Int { var result = qualifier?.hashCode() ?: 0 result = 31 * result + primaryType.hashCode() result = 31 * result + scopeQualifier.hashCode() return result } } fun indexKey(clazz: KClass<*>, typeQualifier: Qualifier?, scopeQualifier: Qualifier): String { val tq = typeQualifier?.value ?: "" return "${clazz.getFullName()}:$tq:$scopeQualifier" } enum class Kind { Singleton, Factory, Scoped } typealias IndexKey = String typealias Definition<T> = Scope.(ParametersHolder) -> T inline fun <reified T> _createDefinition( kind: Kind = Kind.Singleton, qualifier: Qualifier? = null, noinline definition: Definition<T>, secondaryTypes: List<KClass<*>> = emptyList(), scopeQualifier: Qualifier ): BeanDefinition<T> { return BeanDefinition( scopeQualifier, T::class, qualifier, definition, kind, secondaryTypes = secondaryTypes ) }
apache-2.0
ea155d9ccff7e1788c04efaafd34bc1a
31.222222
102
0.670735
4.486905
false
false
false
false
da1z/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/IconsClassGenerator.kt
1
10168
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.intellij.build.images import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.util.containers.ContainerUtil import org.jetbrains.jps.model.JpsSimpleElement import org.jetbrains.jps.model.java.JavaSourceRootProperties import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.util.JpsPathUtil import java.io.File import java.util.* class IconsClassGenerator(val projectHome: File, val util: JpsModule) { private var processedClasses = 0 private var processedIcons = 0 fun processModule(module: JpsModule) { val customLoad: Boolean val packageName: String val className: String val outFile: File if ("icons" == module.name) { customLoad = false packageName = "com.intellij.icons" className = "AllIcons" val dir = util.getSourceRoots(JavaSourceRootType.SOURCE).first().file.absolutePath + "/com/intellij/icons" outFile = File(dir, "AllIcons.java") } else { customLoad = true packageName = "icons" val firstRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).firstOrNull() if (firstRoot == null) return val generatedRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).find { it.properties.isForGeneratedSources } val targetRoot = File((generatedRoot ?: firstRoot).file, "icons") val firstRootDir = File(firstRoot.file, "icons") if (firstRootDir.isDirectory && firstRootDir.list().isEmpty()) { //this is added to remove unneeded empty directories created by previous version of this script println("deleting empty directory ${firstRootDir.absolutePath}") firstRootDir.delete() } var oldClassName = findIconClass(firstRootDir) if (generatedRoot != null && oldClassName != null) { val oldFile = File(firstRootDir, "${oldClassName}.java") println("deleting $oldFile from source root which isn't marked as 'generated'") oldFile.delete() } if (oldClassName == null) { oldClassName = findIconClass(targetRoot) } className = oldClassName ?: directoryName(module) + "Icons" outFile = File(targetRoot, "${className}.java") } val copyrightComment = getCopyrightComment(outFile) val text = generate(module, className, packageName, customLoad, copyrightComment) if (text != null) { processedClasses++ if (!outFile.exists() || outFile.readText().lines() != text.lines()) { outFile.parentFile.mkdirs() outFile.writeText(text) println("Updated icons class: ${outFile.name}") } } } fun printStats() { println() println("Generated classes: $processedClasses. Processed icons: $processedIcons") } private fun findIconClass(dir: File): String? { var className: String? = null dir.children.forEach { if (it.name.endsWith("Icons.java")) { className = it.name.substring(0, it.name.length - ".java".length) } } return className } private fun getCopyrightComment(file: File): String { if (!file.isFile) return "" val text = file.readText() val i = text.indexOf("package ") if (i == -1) return "" val comment = text.substring(0, i) return if (comment.trim().endsWith("*/") || comment.trim().startsWith("//")) comment else "" } private fun generate(module: JpsModule, className: String, packageName: String, customLoad: Boolean, copyrightComment: String): String? { val answer = StringBuilder() answer.append(copyrightComment) append(answer, "package $packageName;\n", 0) append(answer, "import com.intellij.openapi.util.IconLoader;", 0) append(answer, "", 0) append(answer, "import javax.swing.*;", 0) append(answer, "", 0) // IconsGeneratedSourcesFilter depends on following comment, if you going to change the text // please do corresponding changes in IconsGeneratedSourcesFilter as well append(answer, "/**", 0) append(answer, " * NOTE THIS FILE IS AUTO-GENERATED", 0) append(answer, " * DO NOT EDIT IT BY HAND, run \"Generate icon classes\" configuration instead", 0) append(answer, " */", 0) append(answer, "public class $className {", 0) if (customLoad) { append(answer, "private static Icon load(String path) {", 1) append(answer, "return IconLoader.getIcon(path, ${className}.class);", 2) append(answer, "}", 1) append(answer, "", 0) } val imageCollector = ImageCollector(projectHome, true) val images = imageCollector.collect(module) imageCollector.printUsedIconRobots() val inners = StringBuilder() processIcons(images, inners, customLoad, 0) if (inners.isEmpty()) return null answer.append(inners) append(answer, "}", 0) return answer.toString() } private fun processIcons(images: List<ImagePaths>, answer: StringBuilder, customLoad: Boolean, depth: Int) { val level = depth + 1 val (nodes, leafs) = images.partition { getImageId(it, depth).contains('/') } val nodeMap = nodes.groupBy { getImageId(it, depth).substringBefore('/') } val leafMap = ContainerUtil.newMapFromValues(leafs.iterator(), { getImageId(it, depth) }) val sortedKeys = (nodeMap.keys + leafMap.keys).sortedWith(NAME_COMPARATOR) sortedKeys.forEach { key -> val group = nodeMap[key] val image = leafMap[key] assert(group == null || image == null) if (group != null) { val inners = StringBuilder() processIcons(group, inners, customLoad, depth + 1) if (inners.isNotEmpty()) { append(answer, "", level) append(answer, "public static class " + className(key) + " {", level) append(answer, inners.toString(), 0) append(answer, "}", level) } } if (image != null) { val file = image.file if (file != null) { val name = file.name val used = image.used val deprecated = image.deprecated if (isIcon(file)) { processedIcons++ if (used || deprecated) { append(answer, "", level) append(answer, "@SuppressWarnings(\"unused\")", level) } if (deprecated) { append(answer, "@Deprecated", level) } val sourceRoot = image.sourceRoot var root_prefix: String = "" if (sourceRoot.rootType == JavaSourceRootType.SOURCE) { @Suppress("UNCHECKED_CAST") val packagePrefix = (sourceRoot.properties as JpsSimpleElement<JavaSourceRootProperties>).data.packagePrefix if (!packagePrefix.isEmpty()) root_prefix = "/" + packagePrefix.replace('.', '/') } val size = imageSize(file) ?: error("Can't get icon size: $file") val method = if (customLoad) "load" else "IconLoader.getIcon" val relativePath = root_prefix + "/" + FileUtil.getRelativePath(sourceRoot.file, file)!!.replace('\\', '/') append(answer, "public static final Icon ${iconName(name)} = $method(\"$relativePath\"); // ${size.width}x${size.height}", level) } } } } } private fun append(answer: StringBuilder, text: String, level: Int) { answer.append(" ".repeat(level)) answer.append(text).append("\n") } private fun getImageId(image: ImagePaths, depth: Int): String { val path = StringUtil.trimStart(image.id, "/").split("/") if (path.size < depth) throw IllegalArgumentException("Can't get image ID - ${image.id}, $depth") return path.drop(depth).joinToString("/") } private fun directoryName(module: JpsModule): String { return directoryNameFromConfig(module) ?: className(module.name) } private fun directoryNameFromConfig(module: JpsModule): String? { val rootUrl = getFirstContentRootUrl(module) ?: return null val rootDir = File(JpsPathUtil.urlToPath(rootUrl)) if (!rootDir.isDirectory) return null val file = File(rootDir, "icon-robots.txt") if (!file.exists()) return null val prefix = "name:" var moduleName: String? = null file.forEachLine { if (it.startsWith(prefix)) { val name = it.substring(prefix.length).trim() if (name.isNotEmpty()) moduleName = name } } return moduleName } private fun getFirstContentRootUrl(module: JpsModule): String? { return module.contentRootsList.urls.firstOrNull() } private fun className(name: String): String { val answer = StringBuilder() name.split("-", "_").forEach { answer.append(capitalize(it)) } return toJavaIdentifier(answer.toString()) } private fun iconName(name: String): String { val id = capitalize(name.substring(0, name.lastIndexOf('.'))) return toJavaIdentifier(id) } private fun toJavaIdentifier(id: String): String { val sb = StringBuilder() id.forEach { if (Character.isJavaIdentifierPart(it)) { sb.append(it) } else { sb.append('_') } } if (Character.isJavaIdentifierStart(sb.first())) { return sb.toString() } else { return "_" + sb.toString() } } private fun capitalize(name: String): String { if (name.length == 2) return name.toUpperCase() return name.capitalize() } // legacy ordering private val NAME_COMPARATOR: Comparator<String> = compareBy { it.toLowerCase() + "." } }
apache-2.0
3032626fb61dcd6c5800a066532ef504
33.941581
139
0.648505
4.341588
false
false
false
false
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingReportPacket.kt
1
1303
package info.nightscout.androidaps.diaconn.packet import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject /** * BolusSpeedSettingReportPacket */ class BolusSpeedSettingReportPacket( injector: HasAndroidInjector ) : DiaconnG8Packet(injector ) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var sp: SP init { msgType = 0xC5.toByte() aapsLogger.debug(LTag.PUMPCOMM, "BolusSpeedSettingReportPacket init ") } override fun handleMessage(data: ByteArray?) { val defectCheck = defect(data) if (defectCheck != 0) { aapsLogger.debug(LTag.PUMPCOMM, "BolusSpeedSettingReportPacket Report Packet Got some Error") failed = true return } else failed = false val bufferData = prefixDecode(data) diaconnG8Pump.speed = getByteToInt(bufferData) // speed result sp.putBoolean("diaconn_g8_isbolusspeedsync", true) aapsLogger.debug(LTag.PUMPCOMM, "bolusSpeed --> ${diaconnG8Pump.speed }") } override fun getFriendlyName(): String { return "PUMP_BOLUS_SPEED_SETTING_REPORT" } }
agpl-3.0
0c7c9ca838931fe4f5ff49f8cc796c93
31.6
105
0.706063
4.328904
false
false
false
false
Heiner1/AndroidAPS
wear/src/main/java/info/nightscout/androidaps/comm/ExceptionHandlerWear.kt
1
2343
package info.nightscout.androidaps.comm import android.os.Build import android.util.Log import info.nightscout.androidaps.events.EventWearToMobile import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.shared.weardata.EventData import java.io.ByteArrayOutputStream import java.io.IOException import java.io.ObjectOutputStream import javax.inject.Inject class ExceptionHandlerWear @Inject constructor( private val rxBus: RxBus, ) { private var mDefaultUEH: Thread.UncaughtExceptionHandler? = null private val mWearUEH = Thread.UncaughtExceptionHandler { thread, ex -> Log.d("WEAR", "uncaughtException :" + ex.message) // Pass the exception to the bus which will send the data upstream to your Smartphone/Tablet val wearException = EventData.WearException( timeStamp = System.currentTimeMillis(), exception = exceptionToByteArray(ex), board = Build.BOARD, sdk = Build.VERSION.SDK_INT.toString(), fingerprint = Build.FINGERPRINT, model = Build.MODEL, manufacturer = Build.MANUFACTURER, product = Build.PRODUCT ) rxBus.send(EventWearToMobile(wearException)) // Let the default UncaughtExceptionHandler take it from here mDefaultUEH?.uncaughtException(thread, ex) } fun register() { mDefaultUEH = Thread.getDefaultUncaughtExceptionHandler() Thread.setDefaultUncaughtExceptionHandler(mWearUEH) } private fun exceptionToByteArray(ex: Throwable): ByteArray { ex.stackTrace // Make sure the stacktrace gets built up val bos = ByteArrayOutputStream() var oos: ObjectOutputStream? = null try { oos = ObjectOutputStream(bos) oos.writeObject(ex) return bos.toByteArray() } catch (e: IOException) { e.printStackTrace() } finally { try { oos?.close() } catch (exx: IOException) { // Ignore close exception } try { bos.close() } catch (exx: IOException) { // Ignore close exception } } return byteArrayOf() } }
agpl-3.0
e77ede292ffbad0c30b9d25a44513eb7
31.471429
100
0.617157
5.08243
false
false
false
false
Adventech/sabbath-school-android-2
features/media/src/main/kotlin/app/ss/media/playback/ui/video/player/VideoPlayerActivity.kt
1
10299
/* * Copyright (c) 2021. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.media.playback.ui.video.player import android.app.PendingIntent import android.app.PictureInPictureParams import android.app.RemoteAction import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.content.res.Configuration import android.graphics.Rect import android.graphics.drawable.Icon import android.os.Build import android.os.Bundle import android.util.Rational import android.view.View import androidx.annotation.DrawableRes import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.compose.ui.platform.ComposeView import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat.Type.systemBars import androidx.core.view.WindowInsetsControllerCompat import app.ss.design.compose.theme.SsTheme import app.ss.media.R import app.ss.media.playback.BACKWARD import app.ss.media.playback.FORWARD import app.ss.media.playback.PLAY_PAUSE import app.ss.media.playback.players.SSVideoPlayer import app.ss.media.playback.players.SSVideoPlayerImpl import app.ss.media.playback.players.hasEnded import app.ss.models.media.SSVideo import com.cryart.sabbathschool.core.extensions.coroutines.flow.collectIn import com.cryart.sabbathschool.core.extensions.sdk.isAtLeastApi import com.cryart.sabbathschool.core.extensions.view.fadeTo import com.google.android.exoplayer2.ui.StyledPlayerView class VideoPlayerActivity : AppCompatActivity(R.layout.activity_video_player) { private lateinit var exoPlayerView: StyledPlayerView private lateinit var composeView: ComposeView private val videoPlayer: SSVideoPlayer by lazy { SSVideoPlayerImpl(this) } private var systemUiVisible: Boolean = true private val pictureInPictureEnabled: Boolean get() { return if (supportsPiP) { isInPictureInPictureMode } else { false } } private val broadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.getStringExtra(ACTION_TYPE)) { PLAY_PAUSE -> videoPlayer.playPause() BACKWARD -> videoPlayer.rewind() FORWARD -> videoPlayer.fastForward() } } } private var onStopCalled = false override fun onCreate(savedInstanceState: Bundle?) { WindowCompat.setDecorFitsSystemWindows(window, false) super.onCreate(savedInstanceState) exoPlayerView = findViewById(R.id.playerView) composeView = findViewById(R.id.composeView) exoPlayerView.overlayFrameLayout?.setOnClickListener { if (systemUiVisible) { hideSystemUI() } else { showSystemUI() } } composeView.setContent { val onEnterPiP: () -> Unit = { enterPiP() } SsTheme { VideoPlayerControls( videoPlayer = videoPlayer, onClose = { finish() }, onEnterPiP = if (supportsPiP) onEnterPiP else null ) } } @Suppress("DEPRECATION") val video = intent.getParcelableExtra<SSVideo>(ARG_VIDEO) ?: run { finish() return } videoPlayer.playVideo(video, exoPlayerView) videoPlayer.playbackState.collectIn(this) { state -> if (state.isPlaying && systemUiVisible) { exoPlayerView.postDelayed( { hideSystemUI() }, HIDE_DELAY ) } else if (state.hasEnded) { showSystemUI(false) } if (supportsPiP && pictureInPictureEnabled) { setPictureInPictureParams(pictureInPictureParams(state.isPlaying)) } } registerReceiver(broadcastReceiver, IntentFilter(ACTION_PIP_CONTROLS)) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) @Suppress("DEPRECATION") val video = intent?.getParcelableExtra<SSVideo>(ARG_VIDEO) ?: return videoPlayer.playVideo(video, exoPlayerView) } private fun hideSystemUI() { composeView.fadeTo(false) val view: View = findViewById(R.id.root) WindowInsetsControllerCompat(window, view).run { hide(systemBars()) systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } systemUiVisible = false } private fun showSystemUI(autoHide: Boolean = true) { if (pictureInPictureEnabled) return val view: View = findViewById(R.id.root) WindowInsetsControllerCompat(window, view).show(systemBars()) composeView.fadeTo(true) if (autoHide) { view.postDelayed( { if (videoPlayer.playbackState.value.isPlaying) { hideSystemUI() } }, HIDE_DELAY ) } systemUiVisible = true } override fun onPause() { super.onPause() if (pictureInPictureEnabled.not()) { videoPlayer.onPause() } } override fun onStop() { super.onStop() if (videoPlayer.playbackState.value.isPlaying) { videoPlayer.playPause() } onStopCalled = true } override fun onResume() { super.onResume() videoPlayer.onResume() onStopCalled = false } override fun onDestroy() { videoPlayer.release() super.onDestroy() } override fun onUserLeaveHint() { super.onUserLeaveHint() if (videoPlayer.playbackState.value.isPlaying) { enterPiP() } } private fun enterPiP() { if (supportsPiP) { hideSystemUI() val params = pictureInPictureParams(videoPlayer.playbackState.value.isPlaying) enterPictureInPictureMode(params) } } @RequiresApi(api = Build.VERSION_CODES.O) override fun onPictureInPictureModeChanged( isInPictureInPictureMode: Boolean, newConfig: Configuration ) { super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) if (isInPictureInPictureMode.not() && onStopCalled) { finish() } } @RequiresApi(Build.VERSION_CODES.O) private fun pictureInPictureParams(isPlaying: Boolean): PictureInPictureParams { val visibleRect = Rect() findViewById<View>(R.id.root).getGlobalVisibleRect(visibleRect) return PictureInPictureParams.Builder() .setActions( listOf( createRemoteAction( R.drawable.ic_audio_icon_backward, "Rewind", BACKWARD, 1 ), createRemoteAction( if (isPlaying) R.drawable.ic_audio_icon_pause else R.drawable.ic_audio_icon_play, "Play/Pause", PLAY_PAUSE, 2 ), createRemoteAction( R.drawable.ic_audio_icon_forward, "Forward", FORWARD, 3 ) ) ) .setAspectRatio(Rational(16, 9)) .setSourceRectHint(visibleRect) .build() } @RequiresApi(Build.VERSION_CODES.O) private fun createRemoteAction( @DrawableRes iconResId: Int, title: String, action: String, requestCode: Int ): RemoteAction { return RemoteAction( Icon.createWithResource(this, iconResId), title, title, PendingIntent.getBroadcast( this, requestCode, Intent(ACTION_PIP_CONTROLS) .putExtra(ACTION_TYPE, action), PendingIntent.FLAG_IMMUTABLE ) ) } companion object { private const val HIDE_DELAY = 3500L private const val ARG_VIDEO = "arg:video" private const val ACTION_PIP_CONTROLS = "pip_media_controls" private const val ACTION_TYPE = "pip_media_action_type" fun launchIntent( context: Context, video: SSVideo ): Intent = Intent( context, VideoPlayerActivity::class.java ).apply { putExtra(ARG_VIDEO, video) } } } private val Context.supportsPiP: Boolean get() { return isAtLeastApi(Build.VERSION_CODES.O) && packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE) }
mit
2e91da27e216dcd478daeac9e960c3ff
31.488959
105
0.611321
5.028809
false
false
false
false
PolymerLabs/arcs
java/arcs/tools/DecodeVersionMap.kt
1
823
package arcs.tools import arcs.android.crdt.VersionMapProto import arcs.android.crdt.fromProto import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.options.required import java.util.Base64 class DecodeVersionMap : CliktCommand( name = "decode_version_map", help = "Decodes a base64-encoded version map proto (e.g. as stored in the SQLite database)." ) { private val encoding by option("-e", help = "The base64 string to decode").required() override fun run() { val decoder = Base64.getDecoder() val bytes = decoder.decode(encoding) val proto = VersionMapProto.parseFrom(bytes) val versionMap = fromProto(proto) println(versionMap) } } fun main(args: Array<String>) = DecodeVersionMap().main(args)
bsd-3-clause
50f61008e2e571a6166e2c909d6acd2c
31.92
94
0.754557
3.792627
false
false
false
false
PolymerLabs/arcs
java/arcs/android/devtools/StoreOperationMessage.kt
1
5501
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.android.devtools import arcs.android.devtools.DevToolsMessage.Companion.ACTOR import arcs.android.devtools.DevToolsMessage.Companion.ADDED import arcs.android.devtools.DevToolsMessage.Companion.ADD_TYPE import arcs.android.devtools.DevToolsMessage.Companion.CLEAR_ALL_TYPE import arcs.android.devtools.DevToolsMessage.Companion.CLEAR_TYPE import arcs.android.devtools.DevToolsMessage.Companion.FAST_FORWARD_TYPE import arcs.android.devtools.DevToolsMessage.Companion.OLD_VERSION_MAP import arcs.android.devtools.DevToolsMessage.Companion.OPERATIONS import arcs.android.devtools.DevToolsMessage.Companion.REMOVED import arcs.android.devtools.DevToolsMessage.Companion.REMOVE_TYPE import arcs.android.devtools.DevToolsMessage.Companion.STORAGE_KEY import arcs.android.devtools.DevToolsMessage.Companion.STORE_ID import arcs.android.devtools.DevToolsMessage.Companion.STORE_OP_MESSAGE import arcs.android.devtools.DevToolsMessage.Companion.STORE_TYPE import arcs.android.devtools.DevToolsMessage.Companion.TYPE import arcs.android.devtools.DevToolsMessage.Companion.UPDATE_TYPE import arcs.android.devtools.DevToolsMessage.Companion.VALUE import arcs.android.devtools.DevToolsMessage.Companion.VERSION_MAP import arcs.core.common.Referencable import arcs.core.crdt.CrdtData import arcs.core.crdt.CrdtEntity import arcs.core.crdt.CrdtOperation import arcs.core.crdt.CrdtSet import arcs.core.crdt.CrdtSingleton import arcs.core.storage.ProxyMessage import arcs.core.util.JsonValue /** * An implementation of [StoreMessage] to inform DevTools that a [Store] received a * [CrdtOperation]. */ class StoreOperationMessage( private val actualMessage: ProxyMessage.Operations<CrdtData, CrdtOperation, Any?>, private val storeType: String, private val storageKey: String ) : DevToolsMessage { override val kind: String = STORE_OP_MESSAGE override val message: JsonValue<*> get() = JsonValue.JsonObject( STORE_ID to JsonValue.JsonNumber(actualMessage.id?.toDouble() ?: 0.0), STORE_TYPE to JsonValue.JsonString(storeType), STORAGE_KEY to JsonValue.JsonString(storageKey), OPERATIONS to actualMessage.toJson() ) /** * Turn the ProxyMessage into a List of JsonValues. */ private fun ProxyMessage.Operations<CrdtData, CrdtOperation, Any?>.toJson() = JsonValue.JsonArray( operations.map { op -> when (op) { is CrdtSingleton.Operation.Update<*> -> { JsonValue.JsonObject( TYPE to JsonValue.JsonString(UPDATE_TYPE), VALUE to op.value.toJson(), ACTOR to JsonValue.JsonString(op.actor), VERSION_MAP to op.versionMap.toJson() ) } is CrdtSingleton.Operation.Clear<*> -> { JsonValue.JsonObject( TYPE to JsonValue.JsonString(CLEAR_TYPE), ACTOR to JsonValue.JsonString(op.actor), VERSION_MAP to op.versionMap.toJson() ) } is CrdtSet.Operation.Add<*> -> { JsonValue.JsonObject( TYPE to JsonValue.JsonString(ADD_TYPE), ADDED to op.added.toJson(), ACTOR to JsonValue.JsonString(op.actor), VERSION_MAP to op.versionMap.toJson() ) } is CrdtSet.Operation.Clear<*> -> { JsonValue.JsonObject( TYPE to JsonValue.JsonString(CLEAR_TYPE), ACTOR to JsonValue.JsonString(op.actor), VERSION_MAP to op.versionMap.toJson() ) } is CrdtSet.Operation.Remove<*> -> { JsonValue.JsonObject( TYPE to JsonValue.JsonString(REMOVE_TYPE), REMOVED to JsonValue.JsonString(op.removed), ACTOR to JsonValue.JsonString(op.actor), VERSION_MAP to op.versionMap.toJson() ) } is CrdtSet.Operation.FastForward<*> -> { JsonValue.JsonObject( TYPE to JsonValue.JsonString(FAST_FORWARD_TYPE), ADDED to getAddedListValue(op.added), REMOVED to getRemovedListValue(op.removed), OLD_VERSION_MAP to JsonValue.JsonString(op.oldVersionMap.toString()), VERSION_MAP to op.versionMap.toJson() ) } is CrdtEntity.Operation.ClearAll -> { JsonValue.JsonObject( TYPE to JsonValue.JsonString(CLEAR_ALL_TYPE), ACTOR to JsonValue.JsonString(op.actor), VERSION_MAP to op.versionMap.toJson() ) } else -> JsonValue.JsonString(op.toString()) } } ) /** * Return the items in the removed list as a JsonArray */ private fun getRemovedListValue(list: MutableList<out Referencable>): JsonValue.JsonArray { val array = list.map { it.toJson() } return JsonValue.JsonArray(array) } /** * Return the items in the added list as a JsonArray */ private fun getAddedListValue( list: MutableList<out CrdtSet.DataValue<out Referencable>> ): JsonValue.JsonArray { val array = list.map { it.value.toJson() } return JsonValue.JsonArray(array) } }
bsd-3-clause
7e05ba7db50623052e2f59f7fa178b2a
36.678082
96
0.676422
4.475997
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/leftright/MotionLeftAction.kt
1
2149
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.motion.leftright import com.maddyhome.idea.vim.action.ComplicatedKeysAction import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.MotionType import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.Motion import com.maddyhome.idea.vim.handler.MotionActionHandler import java.awt.event.KeyEvent import javax.swing.KeyStroke class MotionLeftAction : MotionActionHandler.ForEachCaret() { override val motionType: MotionType = MotionType.EXCLUSIVE override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { val offsetOfHorizontalMotion = injector.motion.getOffsetOfHorizontalMotion(editor, caret, -operatorArguments.count1, false) return if (offsetOfHorizontalMotion < 0) Motion.Error else Motion.AbsoluteOffset(offsetOfHorizontalMotion) } } class MotionLeftInsertModeAction : MotionActionHandler.ForEachCaret(), ComplicatedKeysAction { override val motionType: MotionType = MotionType.EXCLUSIVE override val keyStrokesSet: Set<List<KeyStroke>> = setOf( listOf(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)), listOf(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, 0)) ) override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { val offsetOfHorizontalMotion = injector.motion.getOffsetOfHorizontalMotion(editor, caret, -operatorArguments.count1, false) return if (offsetOfHorizontalMotion < 0) Motion.Error else Motion.AbsoluteOffset(offsetOfHorizontalMotion) } }
mit
7c488f5ec7192c0b27e9cccb66e1b074
35.423729
110
0.785947
4.222004
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/conversation/mutiselect/MultiselectItemDecoration.kt
1
10225
package org.thoughtcrime.securesms.conversation.mutiselect import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.graphics.Rect import android.graphics.Region import android.view.View import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.ContextCompat import androidx.core.view.children import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.RecyclerView import com.airbnb.lottie.SimpleColorFilter import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.conversation.ConversationAdapter import org.thoughtcrime.securesms.util.Projection import org.thoughtcrime.securesms.util.SetUtil import org.thoughtcrime.securesms.util.ThemeUtil import org.thoughtcrime.securesms.util.ViewUtil import org.thoughtcrime.securesms.wallpaper.ChatWallpaper import java.lang.Integer.max /** * Decoration which renders the background shade and selection bubble for a {@link Multiselectable} item. */ class MultiselectItemDecoration( context: Context, private val chatWallpaperProvider: () -> ChatWallpaper?, private val selectedAnimationProgressProvider: (MultiselectPart) -> Float, private val isInitialAnimation: () -> Boolean ) : RecyclerView.ItemDecoration(), DefaultLifecycleObserver { private val path = Path() private val rect = Rect() private val gutter = ViewUtil.dpToPx(48) private val paddingStart = ViewUtil.dpToPx(17) private val circleRadius = ViewUtil.dpToPx(11) private val checkDrawable = requireNotNull(AppCompatResources.getDrawable(context, R.drawable.ic_check_circle_solid_24)).apply { setBounds(0, 0, circleRadius * 2, circleRadius * 2) } private val photoCircleRadius = ViewUtil.dpToPx(12) private val photoCirclePaddingStart = ViewUtil.dpToPx(16) private val transparentBlack20 = ContextCompat.getColor(context, R.color.transparent_black_20) private val transparentWhite20 = ContextCompat.getColor(context, R.color.transparent_white_20) private val transparentWhite60 = ContextCompat.getColor(context, R.color.transparent_white_60) private val ultramarine30 = ContextCompat.getColor(context, R.color.core_ultramarine_33) private val ultramarine = ContextCompat.getColor(context, R.color.signal_accent_primary) private var checkedBitmap: Bitmap? = null override fun onCreate(owner: LifecycleOwner) { val bitmap = Bitmap.createBitmap(circleRadius * 2, circleRadius * 2, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) checkDrawable.draw(canvas) checkedBitmap = bitmap } override fun onDestroy(owner: LifecycleOwner) { checkedBitmap?.recycle() checkedBitmap = null } private val unselectedPaint = Paint().apply { isAntiAlias = true strokeWidth = 1.5f style = Paint.Style.STROKE } private val shadePaint = Paint().apply { isAntiAlias = true style = Paint.Style.FILL } private val photoCirclePaint = Paint().apply { isAntiAlias = true style = Paint.Style.FILL color = transparentBlack20 } private val checkPaint = Paint().apply { isAntiAlias = true style = Paint.Style.FILL } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { outRect.setEmpty() updateChildOffsets(parent, view) } /** * Draws the background shade. */ @Suppress("DEPRECATION") override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { val adapter = parent.adapter as ConversationAdapter if (adapter.selectedItems.isEmpty()) { return } shadePaint.color = when { chatWallpaperProvider() != null -> transparentBlack20 ThemeUtil.isDarkTheme(parent.context) -> transparentWhite20 else -> ultramarine30 } parent.children.filterIsInstance(Multiselectable::class.java).forEach { child -> updateChildOffsets(parent, child as View) val parts: MultiselectCollection = child.conversationMessage.multiselectCollection val projections: List<Projection> = child.colorizerProjections path.reset() projections.forEach { it.applyToPath(path) } canvas.save() canvas.clipPath(path, Region.Op.DIFFERENCE) val selectedParts: Set<MultiselectPart> = SetUtil.intersection(parts.toSet(), adapter.selectedItems) if (selectedParts.isNotEmpty()) { val selectedPart: MultiselectPart = selectedParts.first() val shadeAll = selectedParts.size == parts.size || (selectedPart is MultiselectPart.Text && child.hasNonSelectableMedia()) if (shadeAll) { rect.set(0, child.top, child.right, child.bottom) } else { rect.set(0, child.getTopBoundaryOfMultiselectPart(selectedPart), parent.right, child.getBottomBoundaryOfMultiselectPart(selectedPart)) } canvas.drawRect(rect, shadePaint) } canvas.restore() } } /** * Draws the selected check or empty circle. */ override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { val adapter = parent.adapter as ConversationAdapter if (adapter.selectedItems.isEmpty()) { return } val drawCircleBehindSelector = chatWallpaperProvider()?.isPhoto == true val multiselectChildren: Sequence<Multiselectable> = parent.children.filterIsInstance(Multiselectable::class.java) val isDarkTheme = ThemeUtil.isDarkTheme(parent.context) unselectedPaint.color = when { chatWallpaperProvider()?.isPhoto == true -> Color.WHITE chatWallpaperProvider() != null || isDarkTheme -> transparentWhite60 else -> transparentBlack20 } if (chatWallpaperProvider() == null && !isDarkTheme) { checkPaint.colorFilter = SimpleColorFilter(ultramarine) } else { checkPaint.colorFilter = null } multiselectChildren.forEach { child -> val parts: MultiselectCollection = child.conversationMessage.multiselectCollection parts.toSet().forEach { val topBoundary = child.getTopBoundaryOfMultiselectPart(it) val bottomBoundary = child.getBottomBoundaryOfMultiselectPart(it) if (drawCircleBehindSelector) { drawPhotoCircle(canvas, parent, topBoundary, bottomBoundary) } val alphaProgress = selectedAnimationProgressProvider(it) if (adapter.selectedItems.contains(it)) { drawUnselectedCircle(canvas, parent, topBoundary, bottomBoundary, 1f - alphaProgress) drawSelectedCircle(canvas, parent, topBoundary, bottomBoundary, alphaProgress) } else { drawUnselectedCircle(canvas, parent, topBoundary, bottomBoundary, alphaProgress) if (!isInitialAnimation()) { drawSelectedCircle(canvas, parent, topBoundary, bottomBoundary, 1f - alphaProgress) } } } } } /** * Draws an extra circle behind the selection circle. This is to make it easier to see and * is specifically for when a photo wallpaper is being used. */ private fun drawPhotoCircle(canvas: Canvas, parent: RecyclerView, topBoundary: Int, bottomBoundary: Int) { val centerX: Float = if (ViewUtil.isLtr(parent)) { photoCirclePaddingStart + photoCircleRadius } else { parent.right - photoCircleRadius - photoCirclePaddingStart }.toFloat() val centerY: Float = topBoundary + (bottomBoundary - topBoundary).toFloat() / 2 canvas.drawCircle(centerX, centerY, photoCircleRadius.toFloat(), photoCirclePaint) } /** * Draws the checkmark for selected content */ private fun drawSelectedCircle(canvas: Canvas, parent: RecyclerView, topBoundary: Int, bottomBoundary: Int, alphaProgress: Float) { val topX: Float = if (ViewUtil.isLtr(parent)) { paddingStart } else { parent.right - paddingStart - circleRadius * 2 }.toFloat() val topY: Float = topBoundary + (bottomBoundary - topBoundary).toFloat() / 2 - circleRadius val bitmap = checkedBitmap val alpha = checkPaint.alpha checkPaint.alpha = (alpha * alphaProgress).toInt() if (bitmap != null) { canvas.drawBitmap(bitmap, topX, topY, checkPaint) } checkPaint.alpha = alpha } /** * Draws the empty circle for unselected content */ private fun drawUnselectedCircle(c: Canvas, parent: RecyclerView, topBoundary: Int, bottomBoundary: Int, alphaProgress: Float) { val centerX: Float = if (ViewUtil.isLtr(parent)) { paddingStart + circleRadius } else { parent.right - circleRadius - paddingStart }.toFloat() val alpha = unselectedPaint.alpha unselectedPaint.alpha = (alpha * alphaProgress).toInt() val centerY: Float = topBoundary + (bottomBoundary - topBoundary).toFloat() / 2 c.drawCircle(centerX, centerY, circleRadius.toFloat(), unselectedPaint) unselectedPaint.alpha = alpha } /** * Update the start-aligned gutter in which the checks display. This is called in onDraw to * ensure we don't hit situations where we try to set offsets before items are laid out, and * called in getItemOffsets to ensure the gutter goes away when multiselect mode ends. */ private fun updateChildOffsets(parent: RecyclerView, child: View) { val adapter = parent.adapter as ConversationAdapter val isLtr = ViewUtil.isLtr(child) if (adapter.selectedItems.isNotEmpty() && child is Multiselectable) { val firstPart = child.conversationMessage.multiselectCollection.toSet().first() val target = child.getHorizontalTranslationTarget() if (target != null) { val start = if (isLtr) { target.left } else { parent.right - target.right } val translation: Float = if (isInitialAnimation()) { max(0, gutter - start) * selectedAnimationProgressProvider(firstPart) } else { max(0, gutter - start).toFloat() } child.translationX = if (isLtr) { translation } else { -translation } } } else if (child is Multiselectable) { child.translationX = 0f } } }
gpl-3.0
314ffdbb6c73f5b855b04c75abcf7785
34.503472
144
0.717164
4.451458
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/model/psi/impl/Psi2SymbolReference.kt
10
1393
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.model.psi.impl import com.intellij.model.Symbol import com.intellij.model.psi.PsiSymbolReference import com.intellij.model.psi.PsiSymbolService import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiPolyVariantReference import com.intellij.psi.PsiReference internal class Psi2SymbolReference(private val psiReference: PsiReference) : PsiSymbolReference { override fun getElement(): PsiElement = psiReference.element override fun getRangeInElement(): TextRange = psiReference.rangeInElement override fun resolveReference(): Collection<Symbol> { if (psiReference is PsiPolyVariantReference) { return psiReference.multiResolve(false).mapNotNull { it.element }.map(PsiSymbolService.getInstance()::asSymbol) } else { val resolved: PsiElement = psiReference.resolve() ?: return emptyList() return listOf(PsiSymbolService.getInstance().asSymbol(resolved)) } } override fun resolvesTo(target: Symbol): Boolean { val psi = PsiSymbolService.getInstance().extractElementFromSymbol(target) if (psi == null) { return super.resolvesTo(target) } else { return psiReference.isReferenceTo(psi) } } }
apache-2.0
2baad6a607498c7ddcf9d9cb1dcd07d4
34.717949
140
0.75664
4.722034
false
false
false
false
GunoH/intellij-community
platform/webSymbols/testSrc/com/intellij/webSymbols/query/impl/WebTypesMockScopeImpl.kt
2
1143
// 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.webSymbols.query.impl import com.intellij.model.Pointer import com.intellij.webSymbols.webTypes.WebTypesJsonFilesCache import com.intellij.webSymbols.webTypes.WebTypesSymbolTypeSupport import com.intellij.webSymbols.webTypes.WebTypesSymbolsScopeBase import java.io.File internal class WebTypesMockScopeImpl : WebTypesSymbolsScopeBase() { fun registerFile(file: File) { val webTypes = WebTypesJsonFilesCache.fromUrlNoCache(file.toURI().toString()) val context = WebTypesJsonOriginImpl( webTypes, typeSupport = object : WebTypesSymbolTypeSupport { override fun resolve(types: List<WebTypesSymbolTypeSupport.TypeReference>): Any = types.map { if (it.module != null) "${it.module}:${it.name}" else it.name }.let { if (it.size == 1) it[0] else it } } ) addWebTypes(webTypes, context) } override fun createPointer(): Pointer<out WebTypesSymbolsScopeBase> = Pointer.hardPointer(this) }
apache-2.0
0f10d267f8c2e1474d98752670712b9c
34.75
120
0.716535
4.067616
false
false
false
false
ftomassetti/kolasu
core/src/main/kotlin/com/strumenta/kolasu/language/Unparser.kt
1
957
package com.strumenta.kolasu.language import com.strumenta.kolasu.model.Node import com.strumenta.kolasu.traversing.walkChildren // TODO Alessio this is a work in progress class Unparser { fun unparse(root: Node): String? { val sourceText = root.sourceText return if (sourceText != null) { var template: String = sourceText root.walkChildren() .filter { it.position != null } .sortedByDescending { it.position } .forEach { val replacement = unparse(it) if (replacement != null) { template = template.replaceRange( it.position!!.start.offset(template), it.position!!.end.offset(template), replacement ) } } template } else null } }
apache-2.0
bfdb99a1fa98af3cb5583be71e9daf87
33.178571
65
0.500522
5.316667
false
false
false
false
jk1/Intellij-idea-mail
src/main/kotlin/github/jk1/smtpidea/server/smtp/SmtpsMailServer.kt
1
893
package github.jk1.smtpidea.server.smtp import github.jk1.smtpidea.config.SmtpConfig import java.net.ServerSocket import java.net.InetSocketAddress import javax.net.ssl.SSLServerSocketFactory /** * TLS-secured SMTP server implementation. * It requires client connections to start with a handshake. */ public class SmtpsMailServer(configuration: SmtpConfig) : SmtpMailServer(configuration){ { setEnableTLS(false); // disable STARTTLS, it makes no sense here } protected override fun createServerSocket(): ServerSocket { val isa = InetSocketAddress(getBindAddress(), getPort()) val factory = SSLServerSocketFactory.getDefault() as SSLServerSocketFactory val serverSocket = factory.createServerSocket(getPort(), getBacklog(), isa.getAddress()) if (getPort() == 0) setPort(serverSocket.getLocalPort()) return serverSocket } }
gpl-2.0
ba49fe44c69f6d5e53cd8cee14bd9022
34.72
96
0.743561
4.465
false
true
false
false
Doctoror/ParticleConstellationsLiveWallpaper
app/src/main/java/io/reactivex/subjects/AsyncInitialValueBehaviorSubject.kt
1
2037
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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 io.reactivex.subjects import androidx.annotation.VisibleForTesting import io.reactivex.Observer import io.reactivex.disposables.Disposable /** * [BehaviorSubject] wrapper which supplies initial value from [initialValueSupplier] on * [subscribeActual]. */ class AsyncInitialValueBehaviorSubject<T> : Subject<T> { private val initialValueSupplier: () -> T private val wrapped: BehaviorSubject<T> constructor(initialValueSupplier: () -> T) : this( initialValueSupplier, BehaviorSubject.create() ) @VisibleForTesting constructor( initialValueSupplier: () -> T, wrapped: BehaviorSubject<T> ) { this.initialValueSupplier = initialValueSupplier this.wrapped = wrapped } override fun getThrowable() = wrapped.throwable override fun hasComplete() = wrapped.hasComplete() override fun hasObservers() = wrapped.hasObservers() override fun hasThrowable() = wrapped.hasThrowable() override fun onComplete() = wrapped.onComplete() override fun onError(e: Throwable) = wrapped.onError(e) override fun onNext(t: T) = wrapped.onNext(t) override fun onSubscribe(d: Disposable) = wrapped.onSubscribe(d) override fun subscribeActual(observer: Observer<in T>?) { wrapped.subscribeActual(observer) if (!wrapped.hasValue()) { wrapped.onNext(initialValueSupplier()) } } }
apache-2.0
014eeb5c639a3be60a17ca3e267d0462
28.521739
88
0.706431
4.587838
false
false
false
false
aerisweather/AerisAndroidSDK
Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/view/weather/viewmodel/BaseWeatherViewModel.kt
1
2175
package com.example.demoaerisproject.view.weather.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.aerisweather.aeris.model.AerisBatchResponse import com.aerisweather.aeris.response.ObservationResponse import com.example.demoaerisproject.data.weather.AerisBatchResponseEvent import com.example.demoaerisproject.data.weather.WeatherRepository import com.example.demoaerisproject.data.weather.model.SunMoonResponse import kotlinx.coroutines.launch open class BaseWeatherViewModel(val weatherRepository: WeatherRepository) : ViewModel() { protected val _event = MutableLiveData<ObservationEvent>() val event: LiveData<ObservationEvent> = _event init { initEventListener() } protected fun initEventListener() { kotlin.runCatching { viewModelScope.launch { weatherRepository.batchEvent.collect { val event = when (it) { is AerisBatchResponseEvent.Success -> ObservationEvent.Success(it.response) is AerisBatchResponseEvent.SunMoon -> ObservationEvent.SunMoon(it.response) is AerisBatchResponseEvent.Map -> ObservationEvent.Map(it.response) is AerisBatchResponseEvent.Error -> ObservationEvent.Error(it.msg) } _event.value = event } } }.onFailure { _event.value = ObservationEvent.Error(it.toString()) Log.e("BaseWeatherViewModel.initEventListener", it.toString()) } } } sealed class ObservationEvent() { object InProgress : ObservationEvent() class Success(val response: AerisBatchResponse?) : ObservationEvent() class SunMoon(val response: SunMoonResponse?) : ObservationEvent() class Map(val response: ObservationResponse?) : ObservationEvent() class Error(val msg: String) : ObservationEvent() }
mit
b484b93b5ecae4bdc9aa6fd56839e7ad
37.857143
89
0.665287
5.397022
false
false
false
false
mdanielwork/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowInfoImpl.kt
3
5233
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl import com.intellij.openapi.components.BaseState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.wm.* import com.intellij.util.xmlb.Converter import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Property import com.intellij.util.xmlb.annotations.Tag import com.intellij.util.xmlb.annotations.Transient import java.awt.Rectangle private val LOG = logger<WindowInfoImpl>() private fun canActivateOnStart(id: String?): Boolean { for (ep in ToolWindowEP.EP_NAME.extensions) { if (id == ep.id) { val factory = ep.toolWindowFactory return !factory!!.isDoNotActivateOnStart } } return true } @Suppress("EqualsOrHashCode") @Tag("window_info") @Property(style = Property.Style.ATTRIBUTE) class WindowInfoImpl : Cloneable, WindowInfo, BaseState() { companion object { internal const val TAG = "window_info" const val DEFAULT_WEIGHT = 0.33f } @get:Transient var isRegistered = false override var isActive by property(false) @get:Attribute(converter = ToolWindowAnchorConverter::class) override var anchor by property(ToolWindowAnchor.LEFT) { it == ToolWindowAnchor.LEFT } @get:Attribute("auto_hide") override var isAutoHide by property(false) /** * Bounds of window in "floating" mode. It equals to `null` if floating bounds are undefined. */ @get:Property(flat = true, style = Property.Style.ATTRIBUTE) override var floatingBounds by property<Rectangle?>(null) { it == null || (it.width == 0 && it.height == 0 && it.x == 0 && it.y == 0) } /** * This attribute persists state 'maximized' for ToolWindowType.WINDOWED where decoration is presented by JFrame */ @get:Attribute("maximized") override var isMaximized by property(false) /** * ID of the tool window */ var id: String? by string() /** * @return type of the tool window in internal (docked or sliding) mode. Actually the tool * window can be in floating mode, but this method has sense if you want to know what type * tool window had when it was internal one. */ @get:Attribute("internal_type") var internalType: ToolWindowType by property(ToolWindowType.DOCKED) override var type: ToolWindowType by property(ToolWindowType.DOCKED) @get:Attribute("visible") var isVisible by property(false) @get:Attribute("show_stripe_button") override var isShowStripeButton by property(true) /** * Internal weight of tool window. "weight" means how much of internal desktop * area the tool window is occupied. The weight has sense if the tool window is docked or * sliding. */ var weight: Float by property(DEFAULT_WEIGHT) { Math.max(0f, Math.min(1f, it)) } var sideWeight: Float by property(0.5f) { Math.max(0f, Math.min(1f, it)) } @get:Attribute("side_tool") override var isSplit by property(false) @get:Attribute("content_ui", converter = ContentUiTypeConverter::class) override var contentUiType: ToolWindowContentUiType by property(ToolWindowContentUiType.TABBED) { it == ToolWindowContentUiType.TABBED } /** * Defines order of tool window button inside the stripe. */ var order: Int by property(-1) @get:Transient var isWasRead: Boolean = false private set fun copy(): WindowInfoImpl { val info = WindowInfoImpl() info.copyFrom(this) return info } override val isDocked: Boolean get() = type == ToolWindowType.DOCKED override val isFloating: Boolean get() = type == ToolWindowType.FLOATING override val isWindowed: Boolean get() = type == ToolWindowType.WINDOWED override val isSliding: Boolean get() = type == ToolWindowType.SLIDING fun normalizeAfterRead() { isWasRead = true setTypeAndCheck(type) if (isVisible && !canActivateOnStart(id)) { isVisible = false } } internal fun setType(type: ToolWindowType) { if (ToolWindowType.DOCKED == type || ToolWindowType.SLIDING == type) { internalType = type } setTypeAndCheck(type) } //Hardcoded to avoid single-usage-API private fun setTypeAndCheck(value: ToolWindowType) { type = if (ToolWindowId.PREVIEW === id && value == ToolWindowType.DOCKED) ToolWindowType.SLIDING else value } override fun hashCode(): Int { return anchor.hashCode() + id!!.hashCode() + type.hashCode() + order } override fun toString(): String = "id: $id, ${super.toString()}" } private class ContentUiTypeConverter : Converter<ToolWindowContentUiType>() { override fun fromString(value: String): ToolWindowContentUiType = ToolWindowContentUiType.getInstance(value) override fun toString(value: ToolWindowContentUiType): String = value.name } private class ToolWindowAnchorConverter : Converter<ToolWindowAnchor>() { override fun fromString(value: String): ToolWindowAnchor { try { return ToolWindowAnchor.fromText(value) } catch (e: IllegalArgumentException) { LOG.warn(e) return ToolWindowAnchor.LEFT } } override fun toString(value: ToolWindowAnchor): String = value.toString() }
apache-2.0
a6cc7c8b94263a9219d070b6579f88bd
30.341317
140
0.720046
4.216761
false
false
false
false
mdanielwork/intellij-community
plugins/git4idea/tests/git4idea/test/GitTestAssertions.kt
1
6828
// 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 git4idea.test import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.systemIndependentPath import com.intellij.openapi.vcs.Executor import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.PlatformTestCase import com.intellij.testFramework.PlatformTestCase.assertOrderedEquals import com.intellij.util.ui.UIUtil import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcsUtil.VcsUtil.getFilePath import git4idea.changes.GitChangeUtils import git4idea.history.GitHistoryUtils import git4idea.history.GitLogUtil import git4idea.repo.GitRepository import org.assertj.core.api.Assertions import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import java.io.File fun GitRepository.assertStatus(file: VirtualFile, status: Char) { assertStatus(getFilePath(file), status) } fun GitRepository.assertStatus(file: FilePath, status: Char) { assertStatus(file.ioFile, status) } fun GitRepository.assertStatus(file: File, status: Char) { val actualStatus = git("status --porcelain ${file.path}").trim() assertTrue("File status is not-changed: $actualStatus", !actualStatus.isEmpty()) assertEquals("File status is incorrect: $actualStatus", status, actualStatus[0]) } /** * Checks the latest part of git history by commit messages. */ fun GitRepository.assertLatestHistory(vararg expectedMessages: String) { assertLatestHistory( { it.fullMessage }, *expectedMessages) } fun GitRepository.assertLatestSubjects(vararg expectedMessages: String) { assertLatestHistory( { it.subject }, *expectedMessages) } private fun GitRepository.assertLatestHistory(mapping: (VcsCommitMetadata) -> String, vararg expectedMessages: String) { val actualMessages = GitLogUtil.collectMetadata(project, root, false).commits .map(mapping) .subList(0, expectedMessages.size) assertOrderedEquals("History is incorrect", actualMessages, expectedMessages.asList()) } fun GitRepository.assertStagedChanges(changes: ChangesBuilder.() -> Unit) { val cb = ChangesBuilder() cb.changes() val actualChanges = GitChangeUtils.getStagedChanges(project, root) for (change in cb.changes) { val found = actualChanges.find(change.matcher) PlatformTestCase.assertNotNull("The change [$change] is not staged", found) actualChanges.remove(found) } PlatformTestCase.assertTrue(actualChanges.isEmpty()) } fun GitRepository.assertCommitted(depth: Int = 1, changes: ChangesBuilder.() -> Unit) { val cb = ChangesBuilder() cb.changes() val allChanges = GitHistoryUtils.history(project, root, "-${depth}")[depth - 1].changes val actualChanges = allChanges.toMutableSet() for (change in cb.changes) { val found = actualChanges.find(change.matcher) PlatformTestCase.assertNotNull("The change [$change] wasn't committed\n$allChanges", found) actualChanges.remove(found) } PlatformTestCase.assertTrue(actualChanges.isEmpty()) } fun GitPlatformTest.assertLastMessage(actual: String, failMessage: String = "Last commit is incorrect") { assertMessage(actual, lastMessage(), failMessage) } fun assertMessage(actual: String, expected: String, failMessage: String = "Commit message is incorrect") { Assertions.assertThat(actual).isEqualToIgnoringWhitespace(expected).withFailMessage(failMessage) } fun GitPlatformTest.assertLogMessages(vararg messages: String) { val separator = "\u0001" val actualMessages = git("log -${messages.size} --pretty=${getPrettyFormatTagForFullCommitMessage(project)}${separator}").split(separator) for ((index, message) in messages.withIndex()) { Assertions.assertThat(actualMessages[index].trim()).isEqualToIgnoringWhitespace(message.trimIndent()) } } fun ChangeListManager.assertNoChanges() { PlatformTestCase.assertEmpty("No changes is expected: ${allChanges.joinToString()}}", allChanges) } fun ChangeListManager.assertOnlyDefaultChangelist() { PlatformTestCase.assertEquals("Only default changelist is expected among: ${dumpChangeLists()}", 1, changeListsNumber) PlatformTestCase.assertEquals("Default changelist is not active", LocalChangeList.DEFAULT_NAME, defaultChangeList.name) } fun ChangeListManager.waitScheduledChangelistDeletions() { (this as ChangeListManagerImpl).waitEverythingDoneInTestMode() ApplicationManager.getApplication().invokeAndWait { UIUtil.dispatchAllInvocationEvents() } } fun ChangeListManager.assertChangeListExists(comment: String): LocalChangeList { val changeLists = changeListsCopy val list = changeLists.find { it.comment == comment } PlatformTestCase.assertNotNull("Didn't find changelist with comment '$comment' among: ${dumpChangeLists()}", list) return list!! } private fun ChangeListManager.dumpChangeLists() = changeLists.joinToString { "'${it.name}' - '${it.comment}'" } class ChangesBuilder { data class AChange(val type: FileStatus, val nameBefore: String?, val nameAfter: String, val matcher: (Change) -> Boolean) { constructor(type: FileStatus, nameAfter: String, matcher: (Change) -> Boolean) : this(type, null, nameAfter, matcher) override fun toString(): String { when (type) { Change.Type.NEW -> return "A: $nameAfter" Change.Type.DELETED -> return "D: $nameAfter" Change.Type.MOVED -> return "M: $nameBefore -> $nameAfter" else -> return "M: $nameAfter" } } } val changes = linkedSetOf<AChange>() fun deleted(name: String) { PlatformTestCase.assertTrue(changes.add(AChange(FileStatus.DELETED, name) { it.fileStatus == FileStatus.DELETED && it.beforeRevision.relativePath == name && it.afterRevision == null })) } fun added(name: String) { PlatformTestCase.assertTrue(changes.add(AChange(FileStatus.ADDED, name) { it.fileStatus == FileStatus.ADDED && it.beforeRevision == null && it.afterRevision.relativePath == name })) } fun modified(name:String) { PlatformTestCase.assertTrue(changes.add(AChange(FileStatus.MODIFIED, name) { it.fileStatus == FileStatus.MODIFIED && it.beforeRevision.relativePath == name && it.afterRevision.relativePath == name })) } fun rename(from: String, to: String) { PlatformTestCase.assertTrue(changes.add(AChange(FileStatus.MODIFIED, from, to) { it.isRenamed && from == it.beforeRevision.relativePath && to == it.afterRevision.relativePath })) } } private val ContentRevision?.relativePath: String get() = FileUtil.getRelativePath(Executor.ourCurrentDir().systemIndependentPath, this!!.file.path, '/')!!
apache-2.0
47b7cd281d2936937a133934575d68d7
39.64881
140
0.761863
4.326996
false
true
false
false
ngthtung2805/dalatlaptop
app/src/main/java/com/tungnui/dalatlaptop/views/loopViewPager/LoopPagerAdapterWrapper.kt
1
3730
package com.tungnui.dalatlaptop.views.loopViewPager import android.os.Parcelable import android.support.v4.app.FragmentPagerAdapter import android.support.v4.app.FragmentStatePagerAdapter import android.support.v4.view.PagerAdapter import android.util.SparseArray import android.view.View import android.view.ViewGroup class LoopPagerAdapterWrapper internal constructor(val realAdapter: PagerAdapter) : PagerAdapter() { private var mToDestroy = SparseArray<ToDestroy>() private var mBoundaryCaching: Boolean = false private val realFirstPosition: Int get() = REAL_FIRST_POSITION private val realLastPosition: Int get() = realFirstPosition + realCount - 1 val realCount: Int get() = realAdapter.count internal fun setBoundaryCaching(flag: Boolean) { mBoundaryCaching = flag } override fun notifyDataSetChanged() { mToDestroy = SparseArray() super.notifyDataSetChanged() } internal fun toRealPosition(position: Int): Int { val realCount = realCount if (realCount == 0) return 0 var realPosition = (position - 1) % realCount if (realPosition < 0) realPosition += realCount return realPosition } fun toInnerPosition(realPosition: Int): Int { return realPosition + 1 } override fun getCount(): Int { return realAdapter.count + 2 } override fun instantiateItem(container: ViewGroup, position: Int): Any { val realPosition = if (realAdapter is FragmentPagerAdapter || realAdapter is FragmentStatePagerAdapter) position else toRealPosition(position) if (mBoundaryCaching) { val toDestroy = mToDestroy.get(position) if (toDestroy != null) { mToDestroy.remove(position) return toDestroy.`object` } } return realAdapter.instantiateItem(container, realPosition) } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { val realFirst = realFirstPosition val realLast = realLastPosition val realPosition = if (realAdapter is FragmentPagerAdapter || realAdapter is FragmentStatePagerAdapter) position else toRealPosition(position) if (mBoundaryCaching && (position == realFirst || position == realLast)) { mToDestroy.put(position, ToDestroy(container, realPosition, `object`)) } else { realAdapter.destroyItem(container, realPosition, `object`) } } /* * Delegate rest of methods directly to the inner adapter. */ override fun finishUpdate(container: ViewGroup) { realAdapter.finishUpdate(container) } override fun isViewFromObject(view: View, `object`: Any): Boolean { return realAdapter.isViewFromObject(view, `object`) } override fun restoreState(bundle: Parcelable?, classLoader: ClassLoader?) { realAdapter.restoreState(bundle, classLoader) } override fun saveState(): Parcelable { return realAdapter.saveState() } override fun startUpdate(container: ViewGroup) { realAdapter.startUpdate(container) } override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) { realAdapter.setPrimaryItem(container, position, `object`) } /* * End delegation */ /** * Container class for caching the boundary views */ internal class ToDestroy(var container: ViewGroup, var position: Int, var `object`: Any) companion object { private val REAL_FIRST_POSITION = 1 } }
mit
8370ed2fdaa10da5d71b531b76f90948
28.140625
111
0.6563
4.806701
false
false
false
false
TechzoneMC/SonarPet
api/src/main/kotlin/net/techcable/sonarpet/utils/enums.kt
1
863
package net.techcable.sonarpet.utils import com.google.common.collect.ImmutableMap import java.util.* inline fun <reified K: Enum<K>, V> immutableEnumMap(valueFunc: (K) -> V?): ImmutableMap<K, V> { val resultBuilder = EnumMap<K, V>(K::class.java) for (key in enumValues<K>()) { val value = valueFunc(key) if (value != null) { resultBuilder.put(key, value) } } // ImmutableMap.copyOf special-cases EnumMap into a highly optimized 'ImmutableEnumMap' return ImmutableMap.copyOf(resultBuilder) } inline fun <reified K: Enum<K>, V: Any> completeImmutableEnumMap(valueFunc: (K) -> V): CompleteEnumMap<K, V> { val keys = enumValues<K>() val values = Array<Any>(keys.size) { valueFunc(keys[it]) } @Suppress("UNCHECKED_CAST") // Erasure :( return CompleteEnumMap.copyOf<K, V>(values as Array<V>) }
gpl-3.0
5b393e5fb0ca01be2617f9cefddde8f0
38.227273
110
0.667439
3.566116
false
false
false
false
randombyte-developer/free-blocks
src/main/kotlin/de/randombyte/freeblocks/PlayerEventListeners.kt
1
5127
package de.randombyte.freeblocks import org.spongepowered.api.data.key.Keys import org.spongepowered.api.data.property.PropertyHolder import org.spongepowered.api.data.property.block.SolidCubeProperty import org.spongepowered.api.entity.EntityTypes import org.spongepowered.api.entity.living.player.Player import org.spongepowered.api.event.Listener import org.spongepowered.api.event.action.InteractEvent import org.spongepowered.api.event.block.InteractBlockEvent import org.spongepowered.api.event.entity.InteractEntityEvent import org.spongepowered.api.event.filter.cause.First import org.spongepowered.api.event.filter.type.Include import org.spongepowered.api.event.network.ClientConnectionEvent import org.spongepowered.api.text.Text import org.spongepowered.api.text.chat.ChatTypes import org.spongepowered.api.text.format.TextColors import org.spongepowered.api.world.Location import org.spongepowered.api.world.extent.Extent /** * Manages all player interactions(creating, moving, destroying FreeBlocks, etc.). * * The MainHand version of all events is used to only have the event fired once for one action. If * the superclass/superinterface would be used(e.g. InteractBlockEvent.Secondary instead of * InteractBlockEvent.Secondary.MainHand) the event gets fired two times. That's a problem for some * interactions like de/selecting a FreeBlock. * But there is one exception: InteractEvent.Primary, which gets fired only once. One could use the * MainHand version but there might be cases where only the OffHand version gets fired. */ class PlayerEventListeners { companion object { fun Player.isInEditMode() = FreeBlocks.currentEditor?.equals(uniqueId) ?: false fun Player.isSneaking() = getOrElse(Keys.IS_SNEAKING, false) fun PropertyHolder.isSolid() = getProperty(SolidCubeProperty::class.java).orElse(null)?.value ?: false fun Location<out Extent>.getCenter() = Location(extent, blockPosition.toDouble().add(0.5, 0.0, 0.5)) } @Listener fun onRightClickOnBlock(event: InteractBlockEvent.Secondary.MainHand, @First player: Player) { if (player.run { isInEditMode() && !isSneaking() } && event.targetBlock.isSolid()) { val targetLocation = event.targetBlock.location.orElseThrow { RuntimeException("Couldn't get location of block that was right clicked!") } FreeBlock.create(targetLocation.getCenter(), targetLocation.block).selected = true } } @Listener fun onRightClickOnShulker(event: InteractEntityEvent.Secondary.MainHand, @First player: Player) { if (player.run { isInEditMode() && !isSneaking() } && event.targetEntity.type == EntityTypes.SHULKER) { FreeBlock.fromPassengerEntity(event.targetEntity)?.apply { selected = !selected } } } @Listener fun onLeftClickOnShulker(event: InteractEntityEvent.Primary, @First player: Player) { if (player.run { isInEditMode() && !isSneaking() } && event.targetEntity.type == EntityTypes.SHULKER) { FreeBlock.fromPassengerEntity(event.targetEntity)?.remove() } } @Listener @Include(InteractBlockEvent.Secondary.MainHand::class, InteractEntityEvent.Secondary.MainHand::class) fun onRightClickSneak(event: InteractEvent, @First player: Player) { if (player.run { isInEditMode() && isSneaking() }) { FreeBlocks.currentMoveAxis = FreeBlocks.currentMoveAxis.cycleNext() player.sendMessage(ChatTypes.ACTION_BAR, Text.of(FreeBlocks.LOGO, TextColors.YELLOW, " Switched to ${FreeBlocks.currentMoveAxis.name}-axis!")) } } @Listener fun onEditorScrolled(event: CurrentEditorScrolledEvent) { if (event.direction == 0) return if (!event.targetEntity.isSneaking()) { FreeBlock.getSelectedBlocks().forEach { freeBlock -> val oldPosition = freeBlock.armorStand.location.position val movement = FreeBlocks.currentMoveAxis.toVector3d() .mul(event.direction.toDouble() * FreeBlocks.movementSpeeds[FreeBlocks.currentMoveSpeedIndex]) freeBlock.armorStand.location = freeBlock.armorStand.location.setPosition(oldPosition.add(movement)) } } } @Listener fun onEditorSneakScrolled(event: CurrentEditorScrolledEvent) { if (event.targetEntity.run { isInEditMode() && isSneaking() }) { val nextMoveSpeedIndex = (FreeBlocks.currentMoveSpeedIndex + event.direction) .coerceIn(0, FreeBlocks.movementSpeeds.lastIndex) if (FreeBlocks.currentMoveSpeedIndex != nextMoveSpeedIndex) { event.targetEntity.sendMessage(ChatTypes.ACTION_BAR, Text.of(FreeBlocks.LOGO, TextColors.YELLOW, " Movement speed: ${FreeBlocks.movementSpeeds[nextMoveSpeedIndex]}")) } FreeBlocks.currentMoveSpeedIndex = nextMoveSpeedIndex } } @Listener fun onLeave(event: ClientConnectionEvent.Disconnect) { FreeBlocks.resetPlayer(event.targetEntity) } }
gpl-2.0
e2f52f5d1f7d229a52b7225fd6c0918a
47.377358
118
0.715233
4.312027
false
false
false
false
MasoodFallahpoor/InfoCenter
InfoCenter/src/main/java/com/fallahpoor/infocenter/fragments/SensorsFragment.kt
1
6187
/* Copyright (C) 2014 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 import android.annotation.TargetApi import android.content.Context import android.hardware.Sensor import android.hardware.SensorManager import android.os.Build import android.os.Bundle import android.util.SparseArray import android.view.LayoutInflater import android.view.View import android.view.ViewGroup 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.* /** * SensorsFragment displays a list of sensors and determines whether the device * supports each sensor or not. */ class SensorsFragment : Fragment() { private var isApiAtLeast18: Boolean = false private var isApiAtLeast19: Boolean = false private val listItems: ArrayList<ListItem> get() { val listItems = ArrayList<ListItem>() val itemsArrayList = itemsArrayList val subItemsArrayList = subItemsArrayList for (i in itemsArrayList.indices) { listItems.add(OrdinaryListItem(itemsArrayList[i], subItemsArrayList[i])) } return listItems } private val itemsArrayList: ArrayList<String> get() { val items = ArrayList( listOf( getString(R.string.sen_item_accelerometer), getString(R.string.sen_item_ambient_temperature), getString(R.string.sen_item_gravity), getString(R.string.sen_item_gyroscope), getString(R.string.sen_item_light), getString(R.string.sen_item_linear_acceleration), getString(R.string.sen_item_magnetic_field), getString(R.string.sen_item_pressure), getString(R.string.sen_item_proximity), getString(R.string.sen_item_relative_humidity), getString(R.string.sen_item_rotation_vector) ) ) if (isApiAtLeast18) { items.add(getString(R.string.sen_item_game_rotation_vector)) items.add(getString(R.string.sen_item_significant_motion)) } if (isApiAtLeast19) { items.add(getString(R.string.sen_item_geomagnetic_rotation_vector)) items.add(getString(R.string.sen_item_step_counter)) items.add(getString(R.string.sen_item_step_detector)) } return items } private val subItemsArrayList: ArrayList<String> @TargetApi(Build.VERSION_CODES.KITKAT) get() { val sensorsArray = SparseArray<String>() val subItems = ArrayList<String>() var iterator: Iterator<Int> val supported = getString(R.string.supported) val unsupported = getString(R.string.unsupported) val sensorTypes = ArrayList( listOf( Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_AMBIENT_TEMPERATURE, Sensor.TYPE_GRAVITY, Sensor.TYPE_GYROSCOPE, Sensor.TYPE_LIGHT, Sensor.TYPE_LINEAR_ACCELERATION, Sensor.TYPE_MAGNETIC_FIELD, Sensor.TYPE_PRESSURE, Sensor.TYPE_PROXIMITY, Sensor.TYPE_RELATIVE_HUMIDITY, Sensor.TYPE_ROTATION_VECTOR ) ) if (isApiAtLeast18) { sensorTypes.add(Sensor.TYPE_GAME_ROTATION_VECTOR) sensorTypes.add(Sensor.TYPE_SIGNIFICANT_MOTION) } if (isApiAtLeast19) { sensorTypes.add(Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR) sensorTypes.add(Sensor.TYPE_STEP_COUNTER) sensorTypes.add(Sensor.TYPE_STEP_DETECTOR) } val sensorManager = activity!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager val sensors = sensorManager.getSensorList(Sensor.TYPE_ALL) iterator = sensorTypes.iterator() while (iterator.hasNext()) { sensorsArray.put(iterator.next(), unsupported) } for (sensor in sensors) { sensorsArray.put(sensor.type, supported) } iterator = sensorTypes.iterator() while (iterator.hasNext()) { subItems.add(sensorsArray.get(iterator.next())) } return subItems } // end method getSubItemsArrayList 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) isApiAtLeast18 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 isApiAtLeast19 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT listView.adapter = CustomArrayAdapter(activity, listItems) } }
gpl-3.0
53e2a4c361c7ffed6f9462c24ed392d0
34.36
100
0.625182
4.704943
false
false
false
false
vicboma1/GameBoyEmulatorEnvironment
src/main/kotlin/assets/panel/grid/PanelGridLayoutImpl.kt
1
2619
package assets.panel.grid /** * Created by vicboma on 12/02/17. */ /*class PanelGridLayoutImpl internal constructor( private val _rows: Int, private val _cols: Int, private val _hgap: Int, private val _vgap: Int, private val dimension : Dimension, private val tableModelImpl : TableModelImpl) : JPanel() { private var container: Container private val scrollSize by lazy { ScrollPane.create(this, dimension) } companion object { fun create(_rows: Int, _cols: Int, _hgap: Int, _vgap: Int, dimension: Dimension,tableModelImpl : TableModelImpl) = PanelGridLayoutImpl(_rows, _cols, _hgap, _vgap, dimension,tableModelImpl) fun create(_rows: Int, _cols: Int,dimension: Dimension, tableModelImpl : TableModelImpl) = PanelGridLayoutImpl(_rows, _cols, 0, 0, dimension,tableModelImpl) fun create(dimension: Dimension, tableModelImpl : TableModelImpl) = PanelGridLayoutImpl(1, 0, 0, 0, dimension,tableModelImpl) } init { container = Frame.create(scrollSize, BorderLayout.CENTER).contentPane val grid = GridLayout(_rows, _cols, _hgap, _vgap) setLayout(grid) for (row in 0.._rows - 1) { for (col in 0.._cols - 1) { val nameRom = this.tableModelImpl.getValueAt((row * _cols) + col, 1).toString() val nameGame = nameRom.toLowerCase().split(".")[0].toString().plus(".png") // println(nameGame) val image = Thread.currentThread().contextClassLoader.getResource("cover/$nameGame") var bufferedImage : BufferedImage? bufferedImage = when(image){ null -> ImageIcon().scale(350, 300,Thread.currentThread().contextClassLoader.getResource("cover/_gbNotFound_.png").file.toString()) else -> ImageIcon().scale(350, 300, image.file.toString()) } val panel = JPanel(GridBagLayout()).apply{ layout = BoxLayout(this, BoxLayout.Y_AXIS) add(JLabel(ImageIcon(bufferedImage)).apply { setAlignmentX(Component.CENTER_ALIGNMENT) }) add(JLabel(" ").apply { setAlignmentX(Component.CENTER_ALIGNMENT) }) add(JLabel(nameRom).apply { setAlignmentX(Component.CENTER_ALIGNMENT) }) } add(panel).setLocation(row, col) } //b.addActionListener() } } fun scrollPane() : Container = container override fun setVisible(aFlag: Boolean) { container.setVisible(aFlag) } }*/
lgpl-3.0
7afd3a3d6a829cd28c6c46e9cfbeb6a0
42.666667
196
0.607102
4.46167
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/training/input/TargetView.kt
1
19841
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.features.training.input import android.animation.Animator import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.app.AlertDialog import android.content.Context import android.graphics.* import android.text.TextPaint import android.util.AttributeSet import android.util.Property import android.view.MotionEvent import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.widget.ArrayAdapter import android.widget.GridView import androidx.core.graphics.toRect import de.dreier.mytargets.R import de.dreier.mytargets.features.settings.SettingsManager import de.dreier.mytargets.features.training.input.TargetView.EKeyboardType.LEFT import de.dreier.mytargets.shared.analysis.aggregation.EAggregationStrategy import de.dreier.mytargets.shared.models.Dimension import de.dreier.mytargets.shared.models.Target import de.dreier.mytargets.shared.models.db.Shot import de.dreier.mytargets.shared.targets.drawable.TargetDrawable import de.dreier.mytargets.shared.utils.EndRenderer import de.dreier.mytargets.shared.utils.MatrixEvaluator import de.dreier.mytargets.shared.views.TargetViewBase import de.dreier.mytargets.shared.views.TargetViewBase.EInputMethod.KEYBOARD import de.dreier.mytargets.shared.views.TargetViewBase.EInputMethod.PLOTTING class TargetView : TargetViewBase { private var spotMatrices: Array<Matrix>? = null private var arrowNumbering: Boolean = false private var arrowDiameter: Dimension? = null private var maxArrowNumber: Int = 0 private var targetZoomFactor: Float = 0.toFloat() private var updateListener: OnEndUpdatedListener? = null /** * Matrix to translate the target face with -1..1 coordinate system * to the correct area on the screen. */ private var fullMatrix: Matrix? = null /** * Matrix to translate the target face with -1..1 coordinate system * to the correct area on the screen when selecting a shot position. * This area is inset by 30dp to allow easier placement outside of the target face. */ private var fullExtendedMatrix: Matrix? = null /** * Inverse of [.fullExtendedMatrix]. * Allows to map screen coordinates to -1..1 coordinate system. */ private var fullExtendedMatrixInverse: Matrix? = null /** * Temporary point vector used to translate between different coordinate systems. */ private val pt = FloatArray(2) private var aggregationStrategy = EAggregationStrategy.NONE /** * Left-handed or right-handed mode. */ private var keyboardType: EKeyboardType? = null /** * Used to draw the keyboard buttons. */ private var fillPaint = Paint() /** * Used to draw the keyboard button borders. */ private var borderPaint = Paint() /** * Used to draw the keyboard button texts. */ private var textPaint = TextPaint() /** * Percentage of the keyboard that is currently supposed to be shown. (0..1). */ private var keyboardVisibility = 0f private var keyboardRect: RectF? = null private var targetRect: RectF? = null private val slipDetector = FingerSlipDetector() public override var inputMethod: TargetViewBase.EInputMethod get() = super.inputMethod set(mode) { super.inputMethod = mode targetDrawable!!.drawArrowsEnabled(inputMethod === PLOTTING) targetDrawable!!.setAggregationStrategy( if (inputMethod === PLOTTING) aggregationStrategy else EAggregationStrategy.NONE ) } private val spotEndMatrix: Matrix get() { return if (currentShotIndex == EndRenderer.NO_SELECTION || inputMethod === KEYBOARD) { Matrix() } else { spotMatrices!![currentShotIndex % target.model.faceCount] } } val inputMode: TargetViewBase.EInputMethod get() = inputMethod override val selectedShotCircleRadius: Int get() = if (inputMethod === KEYBOARD) EndRenderer.MAX_CIRCLE_SIZE else 0 constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super( context, attrs, defStyle ) { init() } private fun init() { // Set up a default TextPaint object textPaint.flags = Paint.ANTI_ALIAS_FLAG textPaint.textAlign = Paint.Align.LEFT textPaint.color = Color.BLACK textPaint.textSize = 22 * density textPaint.textAlign = Paint.Align.CENTER fillPaint.isAntiAlias = true borderPaint.color = -0xe3e3e5 borderPaint.isAntiAlias = true borderPaint.style = Paint.Style.STROKE } override fun replaceWithEnd(shots: List<Shot>, exact: Boolean) { inputMethod = if (shots.all { it.scoringRing == Shot.NOTHING_SELECTED }) { if (exact) PLOTTING else KEYBOARD } else { SettingsManager.inputMethod } super.replaceWithEnd(shots, exact) } fun setArrow(diameter: Dimension, numbers: Boolean, maxArrowNumber: Int) { this.arrowNumbering = numbers this.arrowDiameter = diameter this.maxArrowNumber = maxArrowNumber targetDrawable!!.setArrowDiameter(diameter, SettingsManager.inputArrowDiameterScale) } fun setAggregationStrategy(aggregationStrategy: EAggregationStrategy) { this.aggregationStrategy = aggregationStrategy } override fun onDraw(canvas: Canvas) { // Draw target if (inputMethod === PLOTTING && isCurrentlySelecting) { drawZoomedInTarget(canvas) } else { drawTarget(canvas) } drawBackspaceButton(canvas) // Draw right indicator if (keyboardVisibility > 0) { drawKeyboard(canvas) } // Draw all points of this end at the top endRenderer.draw(canvas) } private fun drawZoomedInTarget(canvas: Canvas) { val shot = shots[currentShotIndex] targetDrawable!!.setMatrix(fullExtendedMatrix!!) targetDrawable!!.spotMatrix = spotMatrices!![currentShotIndex % target.model.faceCount] targetDrawable!!.setZoom(targetZoomFactor) targetDrawable!!.setFocusedArrow(shot) targetDrawable!!.setOffset(0f, POINTER_OFFSET_Y_DP * density) targetDrawable!!.draw(canvas) } // Draw actual target face private fun drawTarget(canvas: Canvas) { targetDrawable!!.setOffset(0f, 0f) targetDrawable!!.setZoom(1f) targetDrawable!!.setFocusedArrow(null) if (animator == null) { targetDrawable!!.setMatrix(fullMatrix!!) if (currentShotIndex == EndRenderer.NO_SELECTION || inputMethod === KEYBOARD) { targetDrawable!!.spotMatrix = Matrix() } else { targetDrawable!!.spotMatrix = spotMatrices!![currentShotIndex % target.model.faceCount] } } targetDrawable!!.draw(canvas) } override fun notifyTargetShotsChanged() { val displayedShots = shots.filter { it.scoringRing != Shot.NOTHING_SELECTED && it.index != currentShotIndex } targetDrawable!!.replaceShotsWith(displayedShots) super.notifyTargetShotsChanged() updateListener?.onEndUpdated(shots) } override fun getShotCoordinates(shot: Shot): PointF { val coordinate = PointF() if (inputMethod === KEYBOARD) { coordinate.x = keyboardRect!!.left if (keyboardType == LEFT) { coordinate.x += (KEYBOARD_WIDTH_DP + KEYBOARD_INNER_PADDING_DP) * density } else { coordinate.x -= KEYBOARD_INNER_PADDING_DP * density } val indicatorHeight = keyboardRect!!.height() / selectableZones.size val index = getSelectableZoneIndexFromShot(shot) coordinate.y = keyboardRect!!.top + indicatorHeight * index + indicatorHeight / 2.0f } else { pt[0] = shot.x pt[1] = shot.y fullMatrix!!.mapPoints(pt) coordinate.x = pt[0] coordinate.y = pt[1] } return coordinate } override fun initWithTarget(target: Target) { super.initWithTarget(target) spotMatrices = Array(target.model.faceCount) { Matrix() } for (i in 0 until target.model.faceCount) { targetDrawable!!.getPreCalculatedFaceMatrix(i).invert(spotMatrices!![i]) } } override fun updateLayoutBounds(width: Int, height: Int) { targetRect = RectF(0f, MIN_END_RECT_HEIGHT_DP * density, width.toFloat(), height.toFloat()) targetRect!!.inset(TARGET_PADDING_DP * density, TARGET_PADDING_DP * density) if (inputMethod === KEYBOARD) { if (keyboardType == LEFT) { targetRect!!.left += KEYBOARD_TOTAL_WIDTH_DP * density } else { targetRect!!.right -= KEYBOARD_TOTAL_WIDTH_DP * density } } if (targetRect!!.height() > targetRect!!.width()) { targetRect!!.top = targetRect!!.bottom - targetRect!!.width() } fullMatrix = Matrix() fullMatrix!!.setRectToRect(TargetDrawable.SRC_RECT, targetRect, Matrix.ScaleToFit.CENTER) val targetRectExt = RectF(targetRect) targetRectExt.inset(30 * density, 30 * density) fullExtendedMatrix = Matrix() fullExtendedMatrix!! .setRectToRect(TargetDrawable.SRC_RECT, targetRectExt, Matrix.ScaleToFit.CENTER) fullExtendedMatrixInverse = Matrix() fullExtendedMatrix!!.invert(fullExtendedMatrixInverse) keyboardRect = RectF() if (keyboardType == LEFT) { keyboardRect!!.left = KEYBOARD_OUTER_PADDING_DP * density } else { keyboardRect!!.left = width - KEYBOARD_TOTAL_WIDTH_DP * density } keyboardRect!!.right = keyboardRect!!.left + KEYBOARD_WIDTH_DP * density keyboardRect!!.top = (height / (selectableZones.size + 1)).toFloat() keyboardRect!!.bottom = height.toFloat() } override fun getBackspaceButtonBounds(): Rect { val backspaceButtonBounds = Rect() backspaceButtonBounds.top = 0 backspaceButtonBounds.bottom = (keyboardRect!!.top - density).toInt() backspaceButtonBounds.left = keyboardRect!!.left.toInt() backspaceButtonBounds.right = keyboardRect!!.right.toInt() return backspaceButtonBounds } override fun getEndRect(): RectF { val endRect = RectF(targetRect) endRect.top = 0f endRect.bottom = targetRect!!.top if (keyboardType == LEFT) { endRect.left = keyboardRect!!.right } else { endRect.right = keyboardRect!!.left } endRect.inset(20 * density, TARGET_PADDING_DP * density) return endRect } /** * {@inheritDoc} */ override fun updateShotToPosition(shot: Shot, x: Float, y: Float): Boolean { if (inputMethod === KEYBOARD) { if (keyboardRect!!.contains(x, y)) { var index = ((y - keyboardRect!!.top) * selectableZones.size / keyboardRect!!.height()).toInt() index = Math.min(Math.max(0, index), selectableZones.size - 1) shot.scoringRing = selectableZones[index].index } else { return false } } else { pt[0] = x pt[1] = y fullExtendedMatrixInverse!!.mapPoints(pt) shot.x = pt[0] shot.y = pt[1] shot.scoringRing = targetDrawable!!.getZoneFromPoint(shot.x, shot.y) slipDetector.addShot(shot.x, shot.y) } return true } override fun selectPreviousShots(motionEvent: MotionEvent, x: Float, y: Float): Boolean { // Handle selection of already saved shoots val shotIndex = endRenderer.getPressedPosition(x, y) endRenderer.setPressed(shotIndex) if (shotIndex != EndRenderer.NO_SELECTION) { if (motionEvent.action == MotionEvent.ACTION_UP) { currentShotIndex = shotIndex animateToNewState() } return true } return false } override fun collectAnimations(animations: MutableList<Animator>) { val initFullMatrix = Matrix(fullMatrix) updateLayout() val endMatrix = spotEndMatrix val newVisibility = (if (inputMethod === KEYBOARD) 1 else 0).toFloat() val inputAnimator = ValueAnimator.ofFloat(keyboardVisibility, newVisibility) inputAnimator.interpolator = AccelerateDecelerateInterpolator() inputAnimator.addUpdateListener { valueAnimator -> keyboardVisibility = valueAnimator.animatedValue as Float invalidate() } animations.add(inputAnimator) animations.add( ObjectAnimator.ofObject( this, ANIMATED_FULL_TRANSFORM_PROPERTY, MatrixEvaluator(), initFullMatrix, fullMatrix ) ) animations.add( ObjectAnimator.ofObject( this, ANIMATED_SPOT_TRANSFORM_PROPERTY, MatrixEvaluator(), endMatrix ) ) super.collectAnimations(animations) } override fun onShotSelectionFinished() { // Replace shot position with final position from slip detector val position = slipDetector.finalPosition val shot = shots[currentShotIndex] if (position != null) { shot.x = position.x shot.y = position.y shot.scoringRing = targetDrawable!!.getZoneFromPoint(shot.x, shot.y) slipDetector.reset() } if (!arrowNumbering) { super.onShotSelectionFinished() } else { // Prepare grid view val gridView = GridView(context) // Set grid view to alertDialog val dialog = AlertDialog.Builder(context) .setView(gridView) .setCancelable(false) .setTitle(R.string.arrow_numbers) .create() val numbers = (1..maxArrowNumber).map { it.toString() } gridView.adapter = ArrayAdapter(context, android.R.layout.simple_list_item_1, numbers) gridView.numColumns = 4 gridView.setOnItemClickListener { _, _, pos, _ -> if (currentShotIndex < shots.size) { shot.arrowNumber = numbers[pos] } dialog.dismiss() setOnTouchListener(this) super.onShotSelectionFinished() } // Disable touch input while dialog is visible setOnTouchListener(null) dialog.show() } } /** * Draws a rect on the right that shows all possible points. * * @param canvas Canvas to draw on */ private fun drawKeyboard(canvas: Canvas) { for (i in 0 until selectableZones.size) { val zone = selectableZones[i] val rect = getSelectableZonePosition(i) fillPaint.color = zone.zone.fillColor canvas.drawRect(rect, fillPaint) borderPaint.color = zone.zone.strokeColor canvas.drawRect(rect, borderPaint) // For yellow and white background use black font color textPaint.color = zone.zone.textColor canvas.drawText( zone.text, rect.centerX().toFloat(), rect.centerY() + 10 * density, textPaint ) } } override fun getSelectableZonePosition(i: Int): Rect { val rect = RectF() val singleZoneHeight = keyboardRect!!.height() / selectableZones.size rect.top = (singleZoneHeight * i + density + keyboardRect!!.top) rect.bottom = (singleZoneHeight * (i + 1) - density + keyboardRect!!.top) rect.left = keyboardRect!!.left rect.right = keyboardRect!!.right val visibilityXOffset = (KEYBOARD_TOTAL_WIDTH_DP.toFloat() * (1 - keyboardVisibility) * density) if (keyboardType == LEFT) { rect.offset(-visibilityXOffset, 0f) } else { rect.offset(visibilityXOffset, 0f) } return rect.toRect() } override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { // Cancel animation if (animator != null) { cancelPendingAnimations() return true } return super.onTouch(view, motionEvent) } fun setUpdateListener(updateListener: OnEndUpdatedListener) { this.updateListener = updateListener } fun reloadSettings() { this.targetZoomFactor = SettingsManager.inputTargetZoom this.keyboardType = SettingsManager.inputKeyboardType targetDrawable!! .setArrowDiameter(arrowDiameter!!, SettingsManager.inputArrowDiameterScale) } fun setTransparentShots(shotStream: List<Shot>) { targetDrawable!!.replacedTransparentShots(shotStream) } enum class EKeyboardType { LEFT, RIGHT } interface OnEndUpdatedListener { fun onEndUpdated(shots: List<Shot>) } companion object { /** * This property is passed to ObjectAnimator when animating the spot matrix of TargetView */ private val ANIMATED_SPOT_TRANSFORM_PROPERTY = object : Property<TargetView, Matrix>( Matrix::class.java, "animatedSpotTransform" ) { override fun set(targetView: TargetView, matrix: Matrix) { targetView.targetDrawable!!.spotMatrix = matrix targetView.invalidate() } override fun get(targetView: TargetView): Matrix { return targetView.targetDrawable!!.spotMatrix } } /** * This property is passed to ObjectAnimator when animating the full matrix of TargetView */ private val ANIMATED_FULL_TRANSFORM_PROPERTY = object : Property<TargetView, Matrix>( Matrix::class.java, "animatedFullTransform" ) { override fun set(targetView: TargetView, matrix: Matrix) { targetView.targetDrawable!!.setMatrix(matrix) targetView.invalidate() } override fun get(targetView: TargetView): Matrix? { return null } } private const val TARGET_PADDING_DP = 10 private const val KEYBOARD_OUTER_PADDING_DP = 20 private const val KEYBOARD_WIDTH_DP = 40 private const val KEYBOARD_TOTAL_WIDTH_DP = KEYBOARD_WIDTH_DP + KEYBOARD_OUTER_PADDING_DP private const val POINTER_OFFSET_Y_DP = -60 private const val MIN_END_RECT_HEIGHT_DP = 80 private const val KEYBOARD_INNER_PADDING_DP = 40 } }
gpl-2.0
5efbba3fbf292867e3e0b541f98820ee
34.814079
103
0.625573
4.713946
false
false
false
false
heinigger/utils
app/src/main/java/com/magnify/utils/ui/jsoup/JsoupImageFragment.kt
1
3374
package com.magnify.utils.ui.jsoup import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.magnify.utils.R import com.magnify.utils.ui.jsoup.adapter.JsoupImageAdapter import com.magnify.utils.ui.jsoup.utils.JsoupUtils import com.yw.fastviewlibrary.dialog.LoadingDialog import com.yw.fastviewlibrary.fragment.BaseFragment import com.yw.xrecylerview.XRecyclerView import kotlinx.android.synthetic.main.fragment_jsoup_main.* import net.EellyBaseRetrofitApi import net.listeners.SimpleCallBack import retrofit2.Call import retrofit2.Response import utils.utils.LogUtils /** * @author:heinigger 2019/6/17 9:40 * @function: */ class JsoupImageFragment : BaseFragment() { internal var html = "" internal var rawHtml = NetBianConfig.URL internal var mImageAdapters: JsoupImageAdapter? = null private var mPage = 1 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return LayoutInflater.from(context).inflate(R.layout.fragment_jsoup_main, null) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val type = arguments?.getSerializable(KEY_TYPE) as NetBianConfig.TYPE rawHtml += (if (TextUtils.isEmpty(type.type)) "" else "/${type.type}") html = rawHtml } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyler!!.layoutManager = GridLayoutManager(context, 3) recyler!!.setLoadingListener(object : XRecyclerView.LoadingListener { override fun onRefresh() { html = rawHtml lazyLoadDatas() } override fun onLoadMore() { mPage = mPage + 1 LogUtils.v("JsoupActivity", mPage) html = "${rawHtml}/index_$mPage.html" lazyLoadDatas() } }) } override fun lazyLoadDatas() { if (mPage == 1) LoadingDialog.showDialog(context) EellyBaseRetrofitApi.getBasicService().gethtml(html).enqueue(object : SimpleCallBack<String>() { override fun onResponse(call: Call<String>, response: Response<String>) { val mUrls = JsoupUtils.getHighDefinitionImgs(NetBianConfig.URL, response.body()) if (mPage == 1) { recyler!!.refreshComplete() } else { recyler!!.loadMoreComplete() } if (mImageAdapters == null) { mImageAdapters = JsoupImageAdapter(context, mUrls) recyler!!.adapter = mImageAdapters } else { mImageAdapters!!.addDatas(mUrls) } LoadingDialog.dissmissDialog(context) } }) } companion object { private val KEY_TYPE = "TYPE" fun newInstant(type: NetBianConfig.TYPE): JsoupImageFragment { val bundle = Bundle() bundle.putSerializable(KEY_TYPE, type) val mFragment = JsoupImageFragment() mFragment.arguments = bundle return mFragment } } }
apache-2.0
60e1d487f5172ce7129e83baf8777e17
34.893617
116
0.641968
4.590476
false
false
false
false
google/intellij-community
plugins/kotlin/code-insight/live-templates-k1/test/org/jetbrains/kotlin/idea/liveTemplates/LiveTemplatesTest.kt
2
8254
// 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.liveTemplates import com.intellij.codeInsight.lookup.LookupManager import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.codeInsight.template.impl.TemplateState import com.intellij.ide.DataManager import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.editor.actionSystem.EditorActionManager import com.intellij.testFramework.LightProjectDescriptor import com.intellij.util.ArrayUtil import com.intellij.util.ui.UIUtil import junit.framework.TestCase import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.idea.base.plugin.KotlinPluginKind import org.jetbrains.kotlin.idea.base.test.KotlinJvmLightProjectDescriptor import org.jetbrains.kotlin.idea.base.test.NewLightKotlinCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.base.test.TestRoot import org.jetbrains.kotlin.test.TestMetadata import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith import java.util.* @TestRoot("code-insight/live-templates-k1") @TestMetadata("testData/simple") @RunWith(JUnit38ClassRunner::class) class LiveTemplatesTest : NewLightKotlinCodeInsightFixtureTestCase() { override val pluginKind: KotlinPluginKind get() = KotlinPluginKind.FE10_PLUGIN override fun setUp() { super.setUp() TemplateManagerImpl.setTemplateTesting(testRootDisposable) } @TestMetadata("sout.kt") fun testSout() { parameterless() } @TestMetadata("sout_BeforeCall.kt") fun testSout_BeforeCall() { parameterless() } @TestMetadata("sout_BeforeCallSpace.kt") fun testSout_BeforeCallSpace() { parameterless() } @TestMetadata("sout_BeforeBinary.kt") fun testSout_BeforeBinary() { parameterless() } @TestMetadata("sout_InCallArguments.kt") fun testSout_InCallArguments() { parameterless() } @TestMetadata("sout_BeforeQualifiedCall.kt") fun testSout_BeforeQualifiedCall() { parameterless() } @TestMetadata("sout_AfterSemicolon.kt") fun testSout_AfterSemicolon() { parameterless() } @TestMetadata("soutf.kt") fun testSoutf() { parameterless() } @TestMetadata("soutf_InCompanion.kt") fun testSoutf_InCompanion() { parameterless() } @TestMetadata("serr.kt") fun testSerr() { parameterless() } @TestMetadata("main.kt") fun testMain() { parameterless() } @TestMetadata("maina.kt") fun testMaina() { parameterless() } @TestMetadata("soutv.kt") fun testSoutv() { start() assertStringItems("DEFAULT_BUFFER_SIZE", "args", "x", "y") typeAndNextTab("y.plus(\"test\")") checkAfter() } @TestMetadata("soutp.kt") fun testSoutp() { parameterless() } @TestMetadata("fun0.kt") fun testFun0() { start() type("foo") nextTab(2) checkAfter() } @TestMetadata("fun1.kt") fun testFun1() { start() type("foo") nextTab(4) checkAfter() } @TestMetadata("fun2.kt") fun testFun2() { start() type("foo") nextTab(6) checkAfter() } @TestMetadata("exfun.kt") fun testExfun() { start() typeAndNextTab("Int") typeAndNextTab("foo") typeAndNextTab("arg : Int") nextTab() checkAfter() } @TestMetadata("exval.kt") fun testExval() { start() typeAndNextTab("Int") nextTab() typeAndNextTab("Int") checkAfter() } @TestMetadata("exvar.kt") fun testExvar() { start() typeAndNextTab("Int") nextTab() typeAndNextTab("Int") checkAfter() } @TestMetadata("closure.kt") fun testClosure() { start() typeAndNextTab("param") nextTab() checkAfter() } @TestMetadata("interface.kt") fun testInterface() { start() typeAndNextTab("SomeTrait") checkAfter() } @TestMetadata("singleton.kt") fun testSingleton() { start() typeAndNextTab("MySingleton") checkAfter() } @TestMetadata("void.kt") fun testVoid() { start() typeAndNextTab("foo") typeAndNextTab("x : Int") checkAfter() } @TestMetadata("iter.kt") fun testIter() { start() assertStringItems("args", "myList", "o", "str") type("args") nextTab(2) checkAfter() } @TestMetadata("iter_ForKeywordVariable.kt") fun testIter_ForKeywordVariable() { start() nextTab(2) checkAfter() } @TestMetadata("anonymous_1.kt") fun testAnonymous_1() { start() typeAndNextTab("Runnable") checkAfter() } @TestMetadata("anonymous_2.kt") fun testAnonymous_2() { start() typeAndNextTab("Thread") checkAfter() } @TestMetadata("object_ForClass.kt") fun testObject_ForClass() { start() typeAndNextTab("A") checkAfter() } @TestMetadata("ifn.kt") fun testIfn() { doTestIfnInn() } @TestMetadata("inn.kt") fun testInn() { doTestIfnInn() } private fun doTestIfnInn() { start() assertStringItems("b", "t", "y") typeAndNextTab("b") checkAfter() } private fun parameterless() { start() checkAfter() } private fun start() { myFixture.configureByMainPath() myFixture.type(templateName) doAction("ExpandLiveTemplateByTab") } private val templateName: String get() { val testName = getTestName(true) if (testName.contains("_")) { return testName.substring(0, testName.indexOf("_")) } return testName } private fun checkAfter() { TestCase.assertNull(templateState) myFixture.checkResultByExpectedPath(".exp") } private fun typeAndNextTab(s: String) { type(s) nextTab() } private fun type(s: String) { myFixture.type(s) } private fun nextTab() { val project = project UIUtil.invokeAndWaitIfNeeded(Runnable { CommandProcessor.getInstance().executeCommand( project, { templateState!!.nextTab() }, "nextTab", null ) }) } private fun nextTab(times: Int) { for (i in 0 until times) { nextTab() } } private val templateState: TemplateState? get() = TemplateManagerImpl.getTemplateState(myFixture.editor) override fun getProjectDescriptor(): LightProjectDescriptor { return KotlinJvmLightProjectDescriptor.DEFAULT } private fun doAction(@Suppress("SameParameterValue") actionId: String) { val actionManager = EditorActionManager.getInstance() val actionHandler = actionManager.getActionHandler(actionId) actionHandler.execute( myFixture.editor, myFixture.editor.caretModel.currentCaret, DataManager.getInstance().getDataContext(myFixture.editor.component) ) } private fun assertStringItems(@NonNls vararg items: String) { TestCase.assertEquals(listOf(*items), listOf(*itemStringsSorted)) } private val itemStrings: Array<String> get() { val lookup = LookupManager.getActiveLookup(myFixture.editor)!! val result = ArrayList<String>() for (element in lookup.items) { result.add(element.lookupString) } return ArrayUtil.toStringArray(result) } private val itemStringsSorted: Array<String> get() { val items = itemStrings Arrays.sort(items) return items } }
apache-2.0
942ff712a84909e944a4d20328811a22
21.308108
158
0.603344
4.395101
false
true
false
false
JetBrains/intellij-community
python/src/com/jetbrains/python/packaging/PyPIPackageRanking.kt
1
1540
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.packaging import com.google.common.io.Resources import com.google.gson.Gson import com.intellij.openapi.components.Service import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.util.* import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write @Service class PyPIPackageRanking { private val lock = ReentrantReadWriteLock() private var myPackageRank: Map<String, Int> = emptyMap() get() = lock.read { field } set(value) { lock.write { field = value } } val packageRank: Map<String, Int> get() = myPackageRank val names: Sequence<String> get() = myPackageRank.asSequence().map { it.key } suspend fun reload() { withContext(Dispatchers.IO) { val gson = Gson() val resource = PyPIPackageRanking::class.java.getResource("/packaging/pypi-ranking.json") ?: error("Python package ranking not found") val array = Resources.asCharSource(resource, Charsets.UTF_8).openBufferedStream().use { gson.fromJson(it, Array<Array<String>>::class.java) } val newRanked = array.asSequence() .map { Pair(it[0].lowercase(), it[1].toInt()) } .toMap(LinkedHashMap()) withContext(Dispatchers.Main) { myPackageRank = Collections.unmodifiableMap(newRanked) } } } }
apache-2.0
ed3e77d5fcde89c7a2f905d8fbae9f93
34.837209
158
0.714935
3.958869
false
false
false
false
burntcookie90/KotMeh
app/src/main/kotlin/io/dwak/meh/model/Theme.kt
1
1388
package io.dwak.meh.model import android.graphics.Color import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.drawable.ColorDrawable import rx.Observable class Theme( val accentColor : String, val foreground : String, val backgroundColor : String, val backgroundImage : String) { public companion object { public val FOREGROUND_DARK : String = "dark" public val FOREGROUND_LIGHT : String = "light" } fun getPressedAccentColorDrawable() : ColorDrawable { val accentColor = Color.parseColor(accentColor) val accentColorDrawable = ColorDrawable(accentColor) val filter = PorterDuffColorFilter(accentColor, PorterDuff.Mode.MULTIPLY) accentColorDrawable.setColorFilter(filter) return accentColorDrawable } fun getParsedAccentColor() : Int = Color.parseColor(expandColor(accentColor)) fun getParsedBackgroundColor() : Int = Color.parseColor(expandColor(backgroundColor)) fun expandColor(colorString : String) : String { return when (colorString.length()) { 4 -> { "${colorString[0]}${colorString[1]}${colorString[1]}${colorString[2]}${colorString[2]}${colorString[3]}${colorString[3]}" } else -> { colorString } } } }
apache-2.0
dd2ba56d2dfbaf897b47ab8e81f6711f
32.071429
137
0.664265
4.939502
false
false
false
false
Masterzach32/SwagBot
src/main/kotlin/features/music/tables/MusicSettings.kt
1
741
package xyz.swagbot.features.music.tables import discord4j.common.util.* import io.facet.exposed.* import org.jetbrains.exposed.sql.* import xyz.swagbot.features.guilds.* object MusicSettings : Table("music_settings") { val guildId = snowflake("guild_id") references GuildTable.guildId val enabled = bool("enabled").default(false) val volume = integer("volume").default(100) val lastConnectedChannel = snowflake("channel_id").nullable() val loop = bool("loop").default(false) val autoplay = bool("autoplay").default(false) override val primaryKey = PrimaryKey(guildId) fun whereGuildIs(guildId: Snowflake): SqlExpressionBuilder.() -> Op<Boolean> = { [email protected] eq guildId } }
gpl-2.0
cfff0f9c6505440dfb1985caa396cae4
32.681818
84
0.723347
4.139665
false
false
false
false
NeatoRobotics/neato-sdk-android
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/robotservices/housecleaning/HouseCleaningServiceFactory.kt
1
941
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.robotservices.housecleaning import com.neatorobotics.sdk.android.robotservices.RobotServices object HouseCleaningServiceFactory { fun get(serviceVersion: String): HouseCleaningService? { return when { RobotServices.VERSION_BASIC_1.equals(serviceVersion, ignoreCase = true) -> HouseCleaningBasic1Service() RobotServices.VERSION_BASIC_3.equals(serviceVersion, ignoreCase = true) -> HouseCleaningBasic3Service() RobotServices.VERSION_MINIMAL_2.equals(serviceVersion, ignoreCase = true) -> HouseCleaningMinimal2Service() RobotServices.VERSION_BASIC_4.equals(serviceVersion, ignoreCase = true) -> HouseCleaningBasic4Service() RobotServices.VERSION_ADVANCED_4.equals(serviceVersion, ignoreCase = true) -> HouseCleaningAdvanced4Service() else -> null } } }
mit
232c3e9bddac8e6248cefe99b7311458
41.772727
121
0.726886
4.545894
false
false
false
false
DeflatedPickle/Quiver
core/src/main/kotlin/com/deflatedpickle/quiver/frontend/dialog/NewDialog.kt
1
15643
/* Copyright (c) 2020-2021 DeflatedPickle under the MIT license */ @file:Suppress("MemberVisibilityCanBePrivate") package com.deflatedpickle.quiver.frontend.dialog import com.deflatedpickle.haruhi.util.PluginUtil import com.deflatedpickle.marvin.builder.Builder import com.deflatedpickle.marvin.builder.FileBuilder import com.deflatedpickle.marvin.dsl.DSLFileNode import com.deflatedpickle.marvin.util.OSUtil import com.deflatedpickle.quiver.backend.extension.toPatternFilter import com.deflatedpickle.quiver.backend.util.DotMinecraft import com.deflatedpickle.quiver.backend.util.ExtraResourceType import com.deflatedpickle.quiver.backend.util.Filters import com.deflatedpickle.quiver.backend.util.PackType import com.deflatedpickle.quiver.backend.util.PackUtil import com.deflatedpickle.quiver.backend.util.VersionUtil import com.deflatedpickle.quiver.frontend.widget.ButtonField import com.deflatedpickle.quiver.frontend.widget.FoldingNotificationLabel import com.deflatedpickle.quiver.frontend.widget.ThemedBalloonTip import com.deflatedpickle.undulation.DocumentAdapter import com.deflatedpickle.undulation.constraints.FillBothFinishLine import com.deflatedpickle.undulation.constraints.FillHorizontal import com.deflatedpickle.undulation.constraints.FillHorizontalFinishLine import com.deflatedpickle.undulation.constraints.StickEast import com.deflatedpickle.undulation.extensions.expandAll import com.jidesoft.swing.CheckBoxList import com.jidesoft.swing.CheckBoxTree import org.apache.logging.log4j.LogManager import org.jdesktop.swingx.JXButton import org.jdesktop.swingx.JXCollapsiblePane import org.jdesktop.swingx.JXLabel import org.jdesktop.swingx.JXPanel import org.jdesktop.swingx.JXRadioGroup import org.jdesktop.swingx.JXTextField import org.jdesktop.swingx.JXTitledSeparator import org.oxbow.swingbits.dialog.task.TaskDialog import java.awt.Dimension import java.awt.GridBagLayout import java.io.File import java.nio.file.Files import java.nio.file.Paths import javax.swing.BorderFactory import javax.swing.DefaultListCellRenderer import javax.swing.JComboBox import javax.swing.JFileChooser import javax.swing.JPanel import javax.swing.JScrollPane import javax.swing.SwingUtilities import javax.swing.text.PlainDocument import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.TreePath class NewDialog : TaskDialog(PluginUtil.window, "Create New Pack") { private val logger = LogManager.getLogger() private fun validationCheck() = nameEntry.text != "" && locationEntry.field.text != "" && resolutionEntry.text != "" private fun validateResolution(text: String) = text.isNotEmpty() && text.toInt() / 16 == 0 val postTaskQueue = mutableListOf<() -> Unit>() val nameEntry: JXTextField = JXTextField("Name").apply { toolTipText = "The name of the pack directory; i.e. the name of the pack" (document as PlainDocument).documentFilter = Filters.FILE this.document.addDocumentListener(DocumentAdapter { fireValidationFinished(validationCheck()) nameNotEmptyTip.isVisible = this.text == "" }) // We have to initially fire the validation as we don't have access to the OK button SwingUtilities.invokeLater { fireValidationFinished(this.text != "") } } private val nameNotEmptyTip = ThemedBalloonTip(nameEntry, "Name must not be empty", initiallyVisible = true) val locationEntry: ButtonField = ButtonField( "Location", "The location of the pack", OSUtil.getOS().toPatternFilter(), "Open" ) { val directoryChooser = JFileChooser( it.field.text ).apply { fileSelectionMode = JFileChooser.DIRECTORIES_ONLY isAcceptAllFileFilterUsed = false } val openResult = directoryChooser.showOpenDialog(PluginUtil.window) if (openResult == JFileChooser.APPROVE_OPTION) { it.field.text = directoryChooser.selectedFile.absolutePath } }.apply { this.field.text = DotMinecraft.resourcePacks.absolutePath this.field.document.addDocumentListener(DocumentAdapter { fireValidationFinished(validationCheck()) locationNotEmptyTip.isVisible = this.field.text == "" val path = Paths.get(field.text) if (Files.exists(path)) { if (path != DotMinecraft.resourcePacks.toPath()) { // This path isn't in the resource packs, add a button to make a symbolic link locationHelpCollapsable.setFields( "Create Symbolic Link?", "This path isn't in your resource pack folder, would you like to create a link to it?", JXButton("OK").apply { addActionListener { logger.info("Creating a symlink to \"$path\" in \"${DotMinecraft.resourcePacks}\"...") postTaskQueue.add { Files.createSymbolicLink( DotMinecraft.resourcePacks .resolve(nameEntry.text) .toPath(), path.resolve(nameEntry.text) ) } locationHelpCollapsable.emptyAndClose() } } ) locationHelpCollapsable.isCollapsed = false } else { // Everything's fine, close the collapsable locationHelpCollapsable.emptyAndClose() } } else { // The given path doesn't exist, add a button to make it locationHelpCollapsable.setFields( "Missing Directory", "This directory doesn't exist, would you like to create it?", JXButton("OK").apply { addActionListener { logger.info("Creating a chain of directories at \"$path\"...") postTaskQueue.add { path.toFile().mkdirs() } locationHelpCollapsable.emptyAndClose() } } ) locationHelpCollapsable.isCollapsed = false } }) } private val locationNotEmptyTip = ThemedBalloonTip(locationEntry.field, "Location must not be empty", false) private val locationHelpCollapsable = FoldingNotificationLabel() val resolutionEntry: JXTextField = JXTextField("Resolution").apply { text = "16" toolTipText = "The resolution of the pack" (document as PlainDocument).documentFilter = Filters.INTEGER this.document.addDocumentListener(DocumentAdapter { fireValidationFinished(validationCheck()) resolutionEmptyTip.isVisible = this.text.isEmpty() resolutionWrongTip.isVisible = validateResolution(this.text) }) // We have to initially fire the validation as we don't have access to the OK button SwingUtilities.invokeLater { fireValidationFinished(validateResolution(this.text)) } } private val resolutionEmptyTip = ThemedBalloonTip(resolutionEntry, "Resolution must not be empty", initiallyVisible = false) private val resolutionWrongTip = ThemedBalloonTip(resolutionEntry, "Resolution must be a multiplication of 16", initiallyVisible = false) val resolutionCollapsable = JXCollapsiblePane().apply { layout = GridBagLayout() isAnimated = true } // We'll cache a few game versions here so we don't keep generating them val packToVersion = Array(6) { PackUtil.packVersionToGameVersion(it + 1) } val packVersionComboBox = JComboBox((1..6).toList().toTypedArray()).apply { setRenderer { list, value, index, isSelected, cellHasFocus -> DefaultListCellRenderer().getListCellRendererComponent( list, packToVersion[value - 1], index, isSelected, cellHasFocus ) } toolTipText = "The version this pack will be based off of, different versions have different quirks; i.e. lang names" selectedItem = this.itemCount } val descriptionEntry = JXTextField("Description").apply { toolTipText = "The description of the pack, used in pack.mcmeta" // border = BorderFactory.createEtchedBorder() } val defaultVersionComboBox = JComboBox( // Returns the versions or an empty list if there are none (DotMinecraft.versions.listFiles() ?: listOf<File>().toTypedArray()).filter { it.name.matches(VersionUtil.RELEASE) /*|| it.name.matches(VersionUtil.ALPHA) || it.name.matches(VersionUtil.BETA)*/ }.toTypedArray() ).apply { for (i in itemCount - 1 downTo 0) { if (getItemAt(i).name.matches(VersionUtil.RELEASE)) { selectedIndex = i break } } } val folderStructureRootNode = DefaultMutableTreeNode("root").apply { fun loopNodes(list: List<Builder.Node<File>>, lastNode: DefaultMutableTreeNode) { for (i in list) { val nextNode = DefaultMutableTreeNode(i.get().name) lastNode.add(nextNode) } } fun loopBuilders(list: List<FileBuilder>, lastNode: DefaultMutableTreeNode) { for (i in list) { val nextNode = DefaultMutableTreeNode(i.firstNode.get().name) loopNodes(i.nodeList.filterIsInstance<DSLFileNode>(), nextNode) lastNode.add(nextNode) loopBuilders(i.builder.childBuilderList, nextNode) } } val emptyPack = PackUtil.createEmptyPack("", false) // loopNodes(emptyPack.nodeList.filterIsInstance<DSLFileNode>(), this) loopBuilders(emptyPack.childBuilderList, this) } val folderStructure = CheckBoxTree(folderStructureRootNode).apply { toolTipText = "Folder structure of an empty pack" isRootVisible = false this.expandAll() checkBoxTreeSelectionModel.addSelectionPath(TreePath(folderStructureRootNode)) isDigIn = true } val folderStructureCollapsable = JXCollapsiblePane().apply { layout = GridBagLayout() } val extraResourceTree = CheckBoxList(ExtraResourceType.values()).apply { toolTipText = "Extra resources that aren't included in the default pack" selectAll() } val extraResourceCollapsable = JXCollapsiblePane().apply { layout = GridBagLayout() } val packTypeGroup = JXRadioGroup(PackType.values()).apply { isOpaque = false // The buttons have a gray background by default for (packType in PackType.values()) { this.getChildButton(packType).apply { toolTipText = when (packType) { PackType.EMPTY_PACK -> "Creates an empty pack structure" PackType.DEFAULT_PACK -> "Extracts and copies the default pack for the given version" } isOpaque = false addActionListener { versionPanel.removeAll() versionPanel.add(when (packType) { PackType.EMPTY_PACK -> packVersionComboBox PackType.DEFAULT_PACK -> defaultVersionComboBox }, FillHorizontalFinishLine) } } } for (i in PackType.values()) { getChildButton(i).text = i.name .toLowerCase() .split("_") .joinToString(" ") { it.capitalize() } } // Disables the "Default Pack" radio button if there are no versions if (defaultVersionComboBox.model.size <= 0) { getChildButton(1).isEnabled = false } addActionListener { val isDefaultPack = selectedValue == PackType.DEFAULT_PACK defaultVersionComboBox.isEnabled = isDefaultPack extraResourceTree.isEnabled = isDefaultPack resolutionCollapsable.isCollapsed = isDefaultPack folderStructureCollapsable.isCollapsed = isDefaultPack extraResourceCollapsable.isCollapsed = !isDefaultPack if (isDefaultPack) { extraResourceTree.selectAll() } else { extraResourceTree.selectNone() } } // This triggers the action listener selectedValue = PackType.EMPTY_PACK } val versionPanel = JXPanel().apply { isOpaque = false layout = GridBagLayout() add(packVersionComboBox, FillHorizontalFinishLine) } init { setCommands( StandardCommand.OK, StandardCommand.CANCEL ) this.defaultVersionComboBox.setRenderer { list, value, index, isSelected, cellHasFocus -> DefaultListCellRenderer().getListCellRendererComponent( list, if (packTypeGroup.selectedValue == PackType.EMPTY_PACK) " ".repeat(16) else value.name, index, isSelected, cellHasFocus ) } this.fixedComponent = JScrollPane(JPanel().apply { isOpaque = false layout = GridBagLayout() /* Pack */ this.add(JXTitledSeparator("Pack"), FillHorizontalFinishLine) this.add(JXLabel("Name" + ":"), StickEast) this.add(nameEntry, FillHorizontalFinishLine) this.add(JXLabel("Location" + ":"), StickEast) this.add(locationEntry, FillHorizontalFinishLine) this.add(locationHelpCollapsable, FillBothFinishLine) this.add(resolutionCollapsable.apply { this.add(JXLabel("Resolution" + ":"), StickEast) this.add(resolutionEntry, FillHorizontalFinishLine) }, FillBothFinishLine) /* Metadata */ this.add(JXTitledSeparator("Metadata"), FillHorizontalFinishLine) this.add(JXLabel("Version" + ":"), StickEast) this.add(versionPanel, FillHorizontalFinishLine) this.add(JXLabel("Description" + ":"), StickEast) this.add(descriptionEntry, FillHorizontalFinishLine) /* Pack Type */ this.add(JXTitledSeparator("Type"), FillHorizontalFinishLine) this.add(JXPanel().apply { isOpaque = false this.add(packTypeGroup, FillHorizontal) }, FillHorizontalFinishLine) this.add(folderStructureCollapsable.apply { this.add(JXTitledSeparator("Included Files"), FillHorizontalFinishLine) this.add(JScrollPane(folderStructure), FillBothFinishLine) }, FillBothFinishLine) this.add(extraResourceCollapsable.apply { this.add(JXTitledSeparator("Extra Vanilla Data"), FillHorizontalFinishLine) this.add(JScrollPane(extraResourceTree), FillBothFinishLine) }, FillBothFinishLine) }).apply { isOpaque = false viewport.isOpaque = false border = BorderFactory.createEmptyBorder() preferredSize = Dimension(600, 500) } } }
mit
ba110d1eab12579801befaf63aeaa45a
39.007673
141
0.627181
5.065738
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/src/channels/ArrayBroadcastChannel.kt
1
16867
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.channels import kotlinx.atomicfu.* import kotlinx.coroutines.* import kotlinx.coroutines.internal.* import kotlinx.coroutines.selects.* /** * Broadcast channel with array buffer of a fixed [capacity]. * Sender suspends only when buffer is full due to one of the receives being slow to consume and * receiver suspends only when buffer is empty. * * **Note**, that elements that are sent to this channel while there are no * [openSubscription] subscribers are immediately lost. * * This channel is created by `BroadcastChannel(capacity)` factory function invocation. * * This implementation uses lock to protect the buffer, which is held only during very short buffer-update operations. * The lock at each subscription is also used to manage concurrent attempts to receive from the same subscriber. * The lists of suspended senders or receivers are lock-free. */ internal class ArrayBroadcastChannel<E>( /** * Buffer capacity. */ val capacity: Int ) : AbstractSendChannel<E>(null), BroadcastChannel<E> { init { require(capacity >= 1) { "ArrayBroadcastChannel capacity must be at least 1, but $capacity was specified" } } /** * NB: prior to changing any logic of ArrayBroadcastChannel internals, please ensure that * you do not break internal invariants of the SubscriberList implementation on K/N and KJS */ /* * Writes to buffer are guarded by bufferLock, but reads from buffer are concurrent with writes * - Write element to buffer then write "tail" (volatile) * - Read "tail" (volatile), then read element from buffer * So read/writes to buffer need not be volatile */ private val bufferLock = ReentrantLock() private val buffer = arrayOfNulls<Any?>(capacity) // head & tail are Long (64 bits) and we assume that they never wrap around // head, tail, and size are guarded by bufferLock private val _head = atomic(0L) private var head: Long // do modulo on use of head get() = _head.value set(value) { _head.value = value } private val _tail = atomic(0L) private var tail: Long // do modulo on use of tail get() = _tail.value set(value) { _tail.value = value } private val _size = atomic(0) private var size: Int get() = _size.value set(value) { _size.value = value } @Suppress("DEPRECATION") private val subscribers = subscriberList<Subscriber<E>>() override val isBufferAlwaysFull: Boolean get() = false override val isBufferFull: Boolean get() = size >= capacity public override fun openSubscription(): ReceiveChannel<E> = Subscriber(this).also { updateHead(addSub = it) } public override fun close(cause: Throwable?): Boolean { if (!super.close(cause)) return false checkSubOffers() return true } @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") override fun cancel(cause: Throwable?): Boolean = cancelInternal(cause) override fun cancel(cause: CancellationException?) { cancelInternal(cause) } private fun cancelInternal(cause: Throwable?): Boolean = close(cause).also { for (sub in subscribers) sub.cancelInternal(cause) } // result is `OFFER_SUCCESS | OFFER_FAILED | Closed` override fun offerInternal(element: E): Any { bufferLock.withLock { // check if closed for send (under lock, so size cannot change) closedForSend?.let { return it } val size = this.size if (size >= capacity) return OFFER_FAILED val tail = this.tail buffer[(tail % capacity).toInt()] = element this.size = size + 1 this.tail = tail + 1 } // if offered successfully, then check subscribers outside of lock checkSubOffers() return OFFER_SUCCESS } // result is `ALREADY_SELECTED | OFFER_SUCCESS | OFFER_FAILED | Closed` override fun offerSelectInternal(element: E, select: SelectInstance<*>): Any { bufferLock.withLock { // check if closed for send (under lock, so size cannot change) closedForSend?.let { return it } val size = this.size if (size >= capacity) return OFFER_FAILED // let's try to select sending this element to buffer if (!select.trySelect()) { // :todo: move trySelect completion outside of lock return ALREADY_SELECTED } val tail = this.tail buffer[(tail % capacity).toInt()] = element this.size = size + 1 this.tail = tail + 1 } // if offered successfully, then check subscribers outside of lock checkSubOffers() return OFFER_SUCCESS } private fun checkSubOffers() { var updated = false var hasSubs = false @Suppress("LoopToCallChain") // must invoke `checkOffer` on every sub for (sub in subscribers) { hasSubs = true if (sub.checkOffer()) updated = true } if (updated || !hasSubs) updateHead() } // updates head if needed and optionally adds / removes subscriber under the same lock private tailrec fun updateHead(addSub: Subscriber<E>? = null, removeSub: Subscriber<E>? = null) { // update head in a tail rec loop var send: Send? = null bufferLock.withLock { if (addSub != null) { addSub.subHead = tail // start from last element val wasEmpty = subscribers.isEmpty() subscribers.add(addSub) if (!wasEmpty) return // no need to update when adding second and etc sub } if (removeSub != null) { subscribers.remove(removeSub) if (head != removeSub.subHead) return // no need to update } val minHead = computeMinHead() val tail = this.tail var head = this.head val targetHead = minHead.coerceAtMost(tail) if (targetHead <= head) return // nothing to do -- head was already moved var size = this.size // clean up removed (on not need if we don't have any subscribers anymore) while (head < targetHead) { buffer[(head % capacity).toInt()] = null val wasFull = size >= capacity // update the size before checking queue (no more senders can queue up) this.head = ++head this.size = --size if (wasFull) { while (true) { send = takeFirstSendOrPeekClosed() ?: break // when when no sender if (send is Closed<*>) break // break when closed for send val token = send!!.tryResumeSend(null) if (token != null) { assert { token === RESUME_TOKEN } // put sent element to the buffer buffer[(tail % capacity).toInt()] = (send as Send).pollResult this.size = size + 1 this.tail = tail + 1 return@withLock // go out of lock to wakeup this sender } // Too late, already cancelled, but we removed it from the queue and need to release resources. // However, ArrayBroadcastChannel does not support onUndeliveredElement, so nothing to do } } } return // done updating here -> return } // we only get out of the lock normally when there is a sender to resume send!!.completeResumeSend() // since we've just sent an element, we might need to resume some receivers checkSubOffers() // tailrec call to recheck updateHead() } private fun computeMinHead(): Long { var minHead = Long.MAX_VALUE for (sub in subscribers) minHead = minHead.coerceAtMost(sub.subHead) // volatile (atomic) reads of subHead return minHead } @Suppress("UNCHECKED_CAST") private fun elementAt(index: Long): E = buffer[(index % capacity).toInt()] as E private class Subscriber<E>( private val broadcastChannel: ArrayBroadcastChannel<E> ) : AbstractChannel<E>(null), ReceiveChannel<E> { private val subLock = ReentrantLock() private val _subHead = atomic(0L) var subHead: Long // guarded by subLock get() = _subHead.value set(value) { _subHead.value = value } override val isBufferAlwaysEmpty: Boolean get() = false override val isBufferEmpty: Boolean get() = subHead >= broadcastChannel.tail override val isBufferAlwaysFull: Boolean get() = error("Should not be used") override val isBufferFull: Boolean get() = error("Should not be used") override fun close(cause: Throwable?): Boolean { val wasClosed = super.close(cause) if (wasClosed) { broadcastChannel.updateHead(removeSub = this) subLock.withLock { subHead = broadcastChannel.tail } } return wasClosed } // returns true if subHead was updated and broadcast channel's head must be checked // this method is lock-free (it never waits on lock) @Suppress("UNCHECKED_CAST") fun checkOffer(): Boolean { var updated = false var closed: Closed<*>? = null loop@ while (needsToCheckOfferWithoutLock()) { // just use `tryLock` here and break when some other thread is checking under lock // it means that `checkOffer` must be retried after every `unlock` if (!subLock.tryLock()) break val receive: ReceiveOrClosed<E>? var result: Any? try { result = peekUnderLock() when { result === POLL_FAILED -> continue@loop // must retest `needsToCheckOfferWithoutLock` outside of the lock result is Closed<*> -> { closed = result break@loop // was closed } } // find a receiver for an element receive = takeFirstReceiveOrPeekClosed() ?: break // break when no one's receiving if (receive is Closed<*>) break // noting more to do if this sub already closed val token = receive.tryResumeReceive(result as E, null) ?: continue assert { token === RESUME_TOKEN } val subHead = this.subHead this.subHead = subHead + 1 // retrieved element for this subscriber updated = true } finally { subLock.unlock() } receive!!.completeResumeReceive(result as E) } // do close outside of lock if needed closed?.also { close(cause = it.closeCause) } return updated } // result is `E | POLL_FAILED | Closed` override fun pollInternal(): Any? { var updated = false val result = subLock.withLock { val result = peekUnderLock() when { result is Closed<*> -> { /* just bail out of lock */ } result === POLL_FAILED -> { /* just bail out of lock */ } else -> { // update subHead after retrieiving element from buffer val subHead = this.subHead this.subHead = subHead + 1 updated = true } } result } // do close outside of lock (result as? Closed<*>)?.also { close(cause = it.closeCause) } // there could have been checkOffer attempt while we were holding lock // now outside the lock recheck if anything else to offer if (checkOffer()) updated = true // and finally update broadcast's channel head if needed if (updated) broadcastChannel.updateHead() return result } // result is `ALREADY_SELECTED | E | POLL_FAILED | Closed` override fun pollSelectInternal(select: SelectInstance<*>): Any? { var updated = false val result = subLock.withLock { var result = peekUnderLock() when { result is Closed<*> -> { /* just bail out of lock */ } result === POLL_FAILED -> { /* just bail out of lock */ } else -> { // let's try to select receiving this element from buffer if (!select.trySelect()) { // :todo: move trySelect completion outside of lock result = ALREADY_SELECTED } else { // update subHead after retrieiving element from buffer val subHead = this.subHead this.subHead = subHead + 1 updated = true } } } result } // do close outside of lock (result as? Closed<*>)?.also { close(cause = it.closeCause) } // there could have been checkOffer attempt while we were holding lock // now outside the lock recheck if anything else to offer if (checkOffer()) updated = true // and finally update broadcast's channel head if needed if (updated) broadcastChannel.updateHead() return result } // Must invoke this check this after lock, because offer's invocation of `checkOffer` might have failed // to `tryLock` just before the lock was about to unlocked, thus loosing notification to this // subscription about an element that was just offered private fun needsToCheckOfferWithoutLock(): Boolean { if (closedForReceive != null) return false // already closed -> nothing to do if (isBufferEmpty && broadcastChannel.closedForReceive == null) return false // no data for us && broadcast channel was not closed yet -> nothing to do return true // check otherwise } // guarded by lock, returns: // E - the element from the buffer at subHead // Closed<*> when closed; // POLL_FAILED when there seems to be no data, but must retest `needsToCheckOfferWithoutLock` outside of lock private fun peekUnderLock(): Any? { val subHead = this.subHead // guarded read (can be non-volatile read) // note: from the broadcastChannel we must read closed token first, then read its tail // because it is Ok if tail moves in between the reads (we make decision based on tail first) val closedBroadcast = broadcastChannel.closedForReceive // unguarded volatile read val tail = broadcastChannel.tail // unguarded volatile read if (subHead >= tail) { // no elements to poll from the queue -- check if closed broads & closed this sub // must retest `needsToCheckOfferWithoutLock` outside of the lock return closedBroadcast ?: this.closedForReceive ?: POLL_FAILED } // Get tentative result. This result may be wrong (completely invalid value, including null), // because this subscription might get closed, moving channel's head past this subscription's head. val result = broadcastChannel.elementAt(subHead) // now check if this subscription was closed val closedSub = this.closedForReceive if (closedSub != null) return closedSub // we know the subscription was not closed, so this tentative result is Ok to return return result } } // ------ debug ------ override val bufferDebugString: String get() = "(buffer:capacity=${buffer.size},size=$size)" }
apache-2.0
0db416e628bf1ec25338c80b32c714b0
42.924479
129
0.567914
5.036429
false
false
false
false
SmokSmog/smoksmog-android
app/src/main/kotlin/com/antyzero/smoksmog/ui/screen/PickStationActivity.kt
1
4370
package com.antyzero.smoksmog.ui.screen import android.app.Activity import android.content.Intent import android.content.res.Configuration import android.os.Bundle import android.support.v4.view.MenuItemCompat import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.LinearLayoutManager.VERTICAL import android.support.v7.widget.SearchView import android.view.Menu import com.antyzero.smoksmog.R import com.antyzero.smoksmog.SmokSmogApplication import com.antyzero.smoksmog.dsl.fullscreen import com.antyzero.smoksmog.ui.BaseDragonActivity import kotlinx.android.synthetic.main.activity_pick_station.* import pl.malopolska.smoksmog.Api import pl.malopolska.smoksmog.model.Station import rx.Observable import rx.android.schedulers.AndroidSchedulers import javax.inject.Inject class PickStationActivity : BaseDragonActivity(), OnStationClick, SearchView.OnQueryTextListener { @Inject lateinit var api: Api private val listStation: MutableList<Station> = mutableListOf() private val allStations: MutableList<Station> = mutableListOf() private lateinit var adapter: SimpleStationAdapter private lateinit var skipIds: LongArray override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_pick_station) fullscreen() SmokSmogApplication[this].appComponent .plus(ActivityModule(this)) .inject(this) setSupportActionBar(toolbar) skipIds = intent?.extras?.getLongArray(EXTRA_SKIP_IDS) ?: LongArray(0) adapter = SimpleStationAdapter(listStation, this) recyclerView.setHasFixedSize(true) recyclerView.adapter = adapter if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) { recyclerView.layoutManager = GridLayoutManager(this, 2) } else { recyclerView.layoutManager = LinearLayoutManager(this, VERTICAL, false) } api.stations() .flatMap { Observable.from(it) } .filter { skipIds.contains(it.id).not() } .toList() .observeOn(AndroidSchedulers.mainThread()) .subscribe { allStations.addAll(it.sortedBy { it.name }) listStation.addAll(allStations) adapter.notifyDataSetChanged() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.pick_station, menu) val searchView = MenuItemCompat.getActionView(menu.findItem(R.id.search)) as SearchView searchView.setOnQueryTextListener(this) return true } override fun onQueryTextChange(newText: String): Boolean { listStation.clear() listStation.addAll(allStations.filter { it.name.contains(newText, true) }) adapter.notifyDataSetChanged() return false } override fun onQueryTextSubmit(query: String?) = false override fun click(station: Station) { endWithResult(station) } private fun endWithResult(station: Station) { val returnIntent = Intent() returnIntent.putExtra(EXTRA_STATION_ID, station.id) returnIntent.putExtra(EXTRA_STATION_NAME, station.name) setResult(RESULT_OK, returnIntent) finish() } companion object { private val EXTRA_STATION_ID = "extraStationId" private val EXTRA_STATION_NAME = "extraStationName" private val EXTRA_SKIP_IDS = "extraSkipIds" fun startForResult(activity: Activity, requestCode: Int) { this.startForResult(activity, requestCode, LongArray(0)) } fun startForResult(activity: Activity, requestCode: Int, skipIds: LongArray = LongArray(0)) { val intent = Intent(activity, PickStationActivity::class.java) intent.putExtra(EXTRA_SKIP_IDS, skipIds) activity.startActivityForResult(intent, requestCode) } @JvmStatic fun gatherResult(intent: Intent): Pair<Long, String> { val stationId = intent.getLongExtra(EXTRA_STATION_ID, -1) val stationName = intent.getStringExtra(EXTRA_STATION_NAME) return stationId to stationName } } }
gpl-3.0
ce50814478ec6bcf23c4b3f16f27fcb4
35.425
101
0.691991
4.724324
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/bridges/fakeOverrideWithSynthesizedImplementation.kt
5
345
open class A(val value: String) { fun component1() = value } interface B { fun component1(): Any } class C(value: String) : A(value), B fun box(): String { val c = C("OK") val b: B = c val a: A = c if (b.component1() != "OK") return "Fail 1" if (a.component1() != "OK") return "Fail 2" return c.component1() }
apache-2.0
cedd654b0d758ac9acb3eb1538fbc9eb
18.166667
47
0.556522
2.875
false
false
false
false
blokadaorg/blokada
android5/app/src/main/java/utils/Logger.kt
1
1665
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package utils import android.util.Log import java.time.ZoneId import java.time.format.DateTimeFormatter open class Logger(private val component: String) { open fun e(message: String) = Logger.e(component, message) open fun w(message: String) = Logger.w(component, message) open fun v(message: String) = Logger.v(component, message) companion object { val dateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS") .withZone(ZoneId.of("UTC")) fun e(component: String, message: String) { logcatLine(6, component, message) } fun w(component: String, message: String) { logcatLine(5, component, message) } fun v(component: String, message: String) { logcatLine(2, component, message) } private fun logcatLine(priority: Int, component: String, message: String) { Log.println(priority, component, message) } } } class LoggerWithThread(val component: String) : Logger(component) { override fun e(message: String) = super.e(thread() + message) override fun w(message: String) = super.w(thread() + message) override fun v(message: String) = super.v(thread() + message) private fun thread() = "{${Thread.currentThread().id}} " }
mpl-2.0
0d9b83c96517ac47b88afe64baac151c
28.210526
87
0.655048
3.860789
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/webview/events/TopShouldStartLoadWithRequestEvent.kt
2
991
package abi44_0_0.host.exp.exponent.modules.api.components.webview.events import abi44_0_0.com.facebook.react.bridge.WritableMap import abi44_0_0.com.facebook.react.uimanager.events.Event import abi44_0_0.com.facebook.react.uimanager.events.RCTEventEmitter /** * Event emitted when shouldOverrideUrlLoading is called */ class TopShouldStartLoadWithRequestEvent(viewId: Int, private val mData: WritableMap) : Event<TopShouldStartLoadWithRequestEvent>(viewId) { companion object { const val EVENT_NAME = "topShouldStartLoadWithRequest" } init { mData.putString("navigationType", "other") // Android does not raise shouldOverrideUrlLoading for inner frames mData.putBoolean("isTopFrame", true) } override fun getEventName(): String = EVENT_NAME override fun canCoalesce(): Boolean = false override fun getCoalescingKey(): Short = 0 override fun dispatch(rctEventEmitter: RCTEventEmitter) = rctEventEmitter.receiveEvent(viewTag, EVENT_NAME, mData) }
bsd-3-clause
ba1a4a55d373e46ecd7b0057473b4b64
33.172414
139
0.775984
4.217021
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/model/KslScope.kt
1
3183
package de.fabmax.kool.modules.ksl.model import kotlin.math.max import kotlin.math.min open class KslScope(val parentOp: KslOp?) { val dependencies = mutableMapOf<KslState, KslMutatedState>() val mutations = mutableMapOf<KslState, KslStateMutation>() val definedStates = mutableSetOf<KslState>() val ops = mutableListOf<KslOp>() var scopeName = parentOp?.opName ?: "unnamed" fun isEmpty(): Boolean = ops.isEmpty() fun isNotEmpty(): Boolean = ops.isNotEmpty() fun dependsOn(state: KslState): Boolean = dependencies.containsKey(state) fun mutates(state: KslState): Boolean = mutations.containsKey(state) fun updateModel() { ops.forEach { it.updateModel() } updateDependenciesAndMutations() } private fun updateDependenciesAndMutations() { val startStates = mutableMapOf<KslState, Int>() val endStates = mutableMapOf<KslState, Int>() parentOp?.let { parent -> parent.dependencies.values.forEach { startStates[it.state] = it.mutation } parent.mutations.values.forEach { endStates[it.state] = it.toMutation } } ops.forEach { op -> op.dependencies.values.filter { it.state !in definedStates }.forEach { extDep -> val start = min(startStates.getOrElse(extDep.state) { extDep.mutation }, extDep.mutation) startStates[extDep.state] = start } op.mutations.values.filter { it.state !in definedStates }.forEach { extMut -> val end = max(endStates.getOrElse(extMut.state) { extMut.toMutation }, extMut.toMutation) endStates[extMut.state] = end } } dependencies.clear() mutations.clear() startStates.forEach { (state, startMutation) -> val endMutation = endStates[state] ?: startMutation dependencies[state] = KslMutatedState(state, startMutation) if (startMutation != endMutation) { mutations[state] = KslStateMutation(state, startMutation, endMutation) } parentOp?.let { parent -> parent.dependencies[state] = KslMutatedState(state, startMutation) if (startMutation != endMutation) { parent.mutations[state] = KslStateMutation(state, startMutation, endMutation) } } } } fun toPseudoCode(): String { val str = StringBuilder("{ // scope: $scopeName\n") str.appendLine(" // depends on:") dependencies.values.forEach { str.appendLine(" // $it") } str.appendLine() str.appendLine(" // mutates:") mutations.values.forEach { str.appendLine(" // $it") } str.appendLine() definedStates.forEach { state -> str.appendLine(" def ${state.toPseudoCode()}") } if (definedStates.isNotEmpty()) { str.appendLine() } ops.forEach { op -> str.appendLine(op.toPseudoCode().prependIndent(" ")) } str.append("}") return str.toString() } }
apache-2.0
6ebcb5c58230c0f8bc36c3e470b78e0b
34.377778
105
0.591894
4.445531
false
false
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_Basal_Set_Temporary_Basal.kt
1
2006
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption class DanaRS_Packet_APS_Basal_Set_Temporary_Basal( injector: HasAndroidInjector, private var percent: Int ) : DanaRS_Packet(injector) { var temporaryBasalRatio = 0 var temporaryBasalDuration = 0 var error = 0 init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__APS_SET_TEMPORARY_BASAL aapsLogger.debug(LTag.PUMPCOMM, "New message: percent: $percent") if (percent < 0) percent = 0 if (percent > 500) percent = 500 temporaryBasalRatio = percent if (percent < 100) { temporaryBasalDuration = PARAM30MIN aapsLogger.debug(LTag.PUMPCOMM, "APS Temp basal start percent: $percent duration 30 min") } else { temporaryBasalDuration = PARAM15MIN aapsLogger.debug(LTag.PUMPCOMM, "APS Temp basal start percent: $percent duration 15 min") } } override fun getRequestParams(): ByteArray { val request = ByteArray(3) request[0] = (temporaryBasalRatio and 0xff).toByte() request[1] = (temporaryBasalRatio ushr 8 and 0xff).toByte() request[2] = (temporaryBasalDuration and 0xff).toByte() return request } override fun handleMessage(data: ByteArray) { val result = byteArrayToInt(getBytes(data, DATA_START, 1)) if (result != 0) { failed = true aapsLogger.debug(LTag.PUMPCOMM, "Set APS temp basal start result: $result FAILED!!!") } else { failed = false aapsLogger.debug(LTag.PUMPCOMM, "Set APS temp basal start result: $result") } } override fun getFriendlyName(): String { return "BASAL__APS_SET_TEMPORARY_BASAL" } companion object { const val PARAM30MIN = 160 const val PARAM15MIN = 150 } }
agpl-3.0
591b659bd76825801ebe71cbf5bb9347
33.016949
101
0.650548
4.528217
false
false
false
false
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/local/subscription/SubscriptionViewModel.kt
1
3331
package org.schabi.newpipe.local.subscription import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.xwray.groupie.Group import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.processors.BehaviorProcessor import io.reactivex.rxjava3.schedulers.Schedulers import org.schabi.newpipe.local.feed.FeedDatabaseManager import org.schabi.newpipe.local.subscription.item.ChannelItem import org.schabi.newpipe.local.subscription.item.FeedGroupCardGridItem import org.schabi.newpipe.local.subscription.item.FeedGroupCardItem import org.schabi.newpipe.util.DEFAULT_THROTTLE_TIMEOUT import org.schabi.newpipe.util.ThemeHelper import java.util.concurrent.TimeUnit class SubscriptionViewModel(application: Application) : AndroidViewModel(application) { private var feedDatabaseManager: FeedDatabaseManager = FeedDatabaseManager(application) private var subscriptionManager = SubscriptionManager(application) // true -> list view, false -> grid view private val listViewMode = BehaviorProcessor.createDefault( !ThemeHelper.shouldUseGridLayout(application) ) private val listViewModeFlowable = listViewMode.distinctUntilChanged() private val mutableStateLiveData = MutableLiveData<SubscriptionState>() private val mutableFeedGroupsLiveData = MutableLiveData<Pair<List<Group>, Boolean>>() val stateLiveData: LiveData<SubscriptionState> = mutableStateLiveData val feedGroupsLiveData: LiveData<Pair<List<Group>, Boolean>> = mutableFeedGroupsLiveData private var feedGroupItemsDisposable = Flowable .combineLatest( feedDatabaseManager.groups(), listViewModeFlowable, ::Pair ) .throttleLatest(DEFAULT_THROTTLE_TIMEOUT, TimeUnit.MILLISECONDS) .map { (feedGroups, listViewMode) -> Pair( feedGroups.map(if (listViewMode) ::FeedGroupCardItem else ::FeedGroupCardGridItem), listViewMode ) } .subscribeOn(Schedulers.io()) .subscribe( { mutableFeedGroupsLiveData.postValue(it) }, { mutableStateLiveData.postValue(SubscriptionState.ErrorState(it)) } ) private var stateItemsDisposable = subscriptionManager.subscriptions() .throttleLatest(DEFAULT_THROTTLE_TIMEOUT, TimeUnit.MILLISECONDS) .map { it.map { entity -> ChannelItem(entity.toChannelInfoItem(), entity.uid, ChannelItem.ItemVersion.MINI) } } .subscribeOn(Schedulers.io()) .subscribe( { mutableStateLiveData.postValue(SubscriptionState.LoadedState(it)) }, { mutableStateLiveData.postValue(SubscriptionState.ErrorState(it)) } ) override fun onCleared() { super.onCleared() stateItemsDisposable.dispose() feedGroupItemsDisposable.dispose() } fun setListViewMode(newListViewMode: Boolean) { listViewMode.onNext(newListViewMode) } fun getListViewMode(): Boolean { return listViewMode.value ?: true } sealed class SubscriptionState { data class LoadedState(val subscriptions: List<Group>) : SubscriptionState() data class ErrorState(val error: Throwable? = null) : SubscriptionState() } }
gpl-3.0
602d885caebeb9dcffc38375d04efad5
40.6375
119
0.734314
5.054628
false
false
false
false
siosio/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinLambdaMethodFilter.kt
1
3346
// 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.debugger.stepping.smartStepInto import com.intellij.debugger.SourcePosition import com.intellij.debugger.engine.BreakpointStepMethodFilter import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.util.Range import com.sun.jdi.Location import org.jetbrains.kotlin.codegen.coroutines.isResumeImplMethodNameFromAnyLanguageSettings import org.jetbrains.kotlin.idea.core.util.isMultiLine import org.jetbrains.kotlin.idea.debugger.isInsideInlineArgument import org.jetbrains.kotlin.idea.debugger.safeMethod import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.util.OperatorNameConventions class KotlinLambdaMethodFilter(target: KotlinLambdaSmartStepTarget) : BreakpointStepMethodFilter { private val lambdaPtr = target.getLambda().createSmartPointer() private val myCallingExpressionLines: Range<Int>? = target.callingExpressionLines private val isInline = target.isInline private val isSuspend = target.isSuspend private val myFirstStatementPosition: SourcePosition? private val myLastStatementLine: Int init { val lambda = target.getLambda() val body = lambda.bodyExpression if (body != null && lambda.isMultiLine()) { var firstStatementPosition: SourcePosition? = null var lastStatementPosition: SourcePosition? = null val statements = (body as? KtBlockExpression)?.statements ?: listOf(body) if (statements.isNotEmpty()) { firstStatementPosition = SourcePosition.createFromElement(statements.first()) if (firstStatementPosition != null) { val lastStatement = statements.last() lastStatementPosition = SourcePosition.createFromOffset(firstStatementPosition.file, lastStatement.textRange.endOffset) } } myFirstStatementPosition = firstStatementPosition myLastStatementLine = lastStatementPosition?.line ?: -1 } else { myFirstStatementPosition = SourcePosition.createFromElement(lambda) myLastStatementLine = myFirstStatementPosition!!.line } } override fun getBreakpointPosition() = myFirstStatementPosition override fun getLastStatementLine() = myLastStatementLine override fun locationMatches(process: DebugProcessImpl, location: Location): Boolean { val lambda = runReadAction { lambdaPtr.element } ?: return true if (isInline) { return isInsideInlineArgument(lambda, location, process) } val method = location.safeMethod() ?: return true return isLambdaName(method.name()) } override fun getCallingExpressionLines() = if (isInline) Range(0, Int.MAX_VALUE) else myCallingExpressionLines private fun isLambdaName(name: String?): Boolean { if (isSuspend && name != null) { return isResumeImplMethodNameFromAnyLanguageSettings(name) } return name == OperatorNameConventions.INVOKE.asString() } }
apache-2.0
4e7f6b54088e842d7927d91c9d34129a
44.216216
158
0.732815
5.108397
false
false
false
false
zsmb13/MaterialDrawerKt
app/src/main/java/co/zsmb/materialdrawerktexample/originalactivities/AdvancedDrawerActivity.kt
1
7621
package co.zsmb.materialdrawerktexample.originalactivities import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import co.zsmb.materialdrawerkt.builders.accountHeader import co.zsmb.materialdrawerkt.builders.drawer import co.zsmb.materialdrawerkt.builders.footer import co.zsmb.materialdrawerkt.draweritems.badge import co.zsmb.materialdrawerkt.draweritems.badgeable.primaryItem import co.zsmb.materialdrawerkt.draweritems.badgeable.secondaryItem import co.zsmb.materialdrawerkt.draweritems.profile.profile import co.zsmb.materialdrawerkt.draweritems.profile.profileSetting import co.zsmb.materialdrawerkt.draweritems.sectionHeader import co.zsmb.materialdrawerktexample.R import co.zsmb.materialdrawerktexample.customitems.customprimary.CustomPrimaryDrawerItem import co.zsmb.materialdrawerktexample.customitems.customurl.CustomUrlPrimaryDrawerItem import co.zsmb.materialdrawerktexample.customitems.overflow.overflowMenuItem import co.zsmb.materialdrawerktexample.utils.toast import com.mikepenz.iconics.typeface.library.fonrawesome.FontAwesome.Icon.faw_bullhorn import com.mikepenz.iconics.typeface.library.fonrawesome.FontAwesome.Icon.faw_cog import com.mikepenz.iconics.typeface.library.fonrawesome.FontAwesome.Icon.faw_gamepad import com.mikepenz.iconics.typeface.library.fonrawesome.FontAwesome.Icon.faw_github import com.mikepenz.iconics.typeface.library.fonrawesome.FontAwesome.Icon.faw_home import com.mikepenz.iconics.typeface.library.fonrawesome.FontAwesome.Icon.faw_question import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial.Icon.gmd_add import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial.Icon.gmd_android import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial.Icon.gmd_filter_center_focus import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial.Icon.gmd_settings import com.mikepenz.materialdrawer.AccountHeader import com.mikepenz.materialdrawer.Drawer import com.mikepenz.materialdrawer.model.ProfileDrawerItem import kotlinx.android.synthetic.main.activity_sample.* class AdvancedDrawerActivity : AppCompatActivity() { private lateinit var result: Drawer private lateinit var headerResult: AccountHeader override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sample) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setHomeButtonEnabled(false) result = drawer { toolbar = [email protected] savedInstance = savedInstanceState actionBarDrawerToggleEnabled = true headerResult = accountHeader { savedInstance = savedInstanceState background = R.drawable.header profile("Mike Penz", "[email protected]") { icon = R.drawable.profile } profile("Max Muster", "[email protected]") { icon = R.drawable.profile2 } profile("Felix House", "[email protected]") { icon = R.drawable.profile3 } profile("Mr. X", "[email protected]") { icon = R.drawable.profile4 } profile("Batman", "[email protected]") { icon = R.drawable.profile5 } profileSetting("Add account", "Add new GitHub Account") { iicon = gmd_add onClick { _ -> val newProfile = ProfileDrawerItem() .withNameShown(true) .withName("Batman") .withEmail("[email protected]") .withIcon(R.drawable.profile6) headerResult.profiles?.let { headerResult.addProfile(newProfile, it.size - 2) } false } } profileSetting("Manage Account") { iicon = gmd_settings } } primaryItem(R.string.drawer_item_home) { iicon = faw_home } overflowMenuItem(R.string.drawer_item_menu_drawer_item, R.string.drawer_item_menu_drawer_item_desc) { iicon = gmd_filter_center_focus menuRes = R.menu.fragment_menu onMenuItemClick { toast(it.title) false } } attachItem( CustomPrimaryDrawerItem() .withBackgroundRes(R.color.accent) .withName(R.string.drawer_item_free_play) .withIcon(faw_gamepad) ) primaryItem(R.string.drawer_item_custom) { iicon = faw_gamepad description = "This is a description" } attachItem( CustomUrlPrimaryDrawerItem().apply { withName(R.string.drawer_item_contact) withDescription(R.string.drawer_item_fragment_drawer_desc) withIcon("https://avatars3.githubusercontent.com/u/1476232?v=3&s=460") } ) sectionHeader(R.string.drawer_item_section_header) secondaryItem(R.string.drawer_item_settings) { iicon = faw_cog } secondaryItem(R.string.drawer_item_help) { iicon = faw_question } secondaryItem(R.string.drawer_item_open_source) { iicon = faw_github badge("12") } secondaryItem(R.string.drawer_item_contact) { iicon = faw_bullhorn } footer { secondaryItem(R.string.drawer_item_settings) { iicon = faw_cog } secondaryItem(R.string.drawer_item_open_source) { iicon = faw_github } } onNavigation { finish() true } } } override fun onSaveInstanceState(outState: Bundle) { result.saveInstanceState(outState) headerResult.saveInstanceState(outState) super.onSaveInstanceState(outState) } override fun onBackPressed() { if (result.isDrawerOpen) result.closeDrawer() else super.onBackPressed() } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.menu_1 -> { val profile2 = headerResult.profiles!![1] profile2.withIcon(gmd_android) headerResult.updateProfile(profile2) true } R.id.menu_2 -> { result.actionBarDrawerToggle?.isDrawerIndicatorEnabled = false true } R.id.menu_3 -> { result.actionBarDrawerToggle?.isDrawerIndicatorEnabled = true true } else -> super.onOptionsItemSelected(item) } }
apache-2.0
0fb0b3c1740737d9dddd8898bb1cda6d
39.973118
113
0.604645
5.000656
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/window/WindowSize.desktop.kt
3
3125
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.window import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.isSpecified import androidx.compose.ui.util.packFloats import androidx.compose.ui.util.unpackFloat1 import androidx.compose.ui.util.unpackFloat2 /** * Constructs an [WindowSize] from [width] and [height] [Dp] values. */ @Suppress("DEPRECATION") @Deprecated( "Use DpSize", replaceWith = ReplaceWith("DpSize(width, height)", "androidx.compose.ui.unit.DpSize") ) fun WindowSize( /** * The width of the window in [Dp]. If it is [Dp.Unspecified] then the width of the window * will determined by the inner content. */ width: Dp, /** * The height of the window in [Dp]. If it is [Dp.Unspecified] then the height of the window * will determined by the inner content. */ height: Dp ) = WindowSize(packFloats(width.value, height.value)) /** * Size of the window or dialog in [Dp]. */ @Suppress("INLINE_CLASS_DEPRECATED", "EXPERIMENTAL_FEATURE_WARNING") @Immutable @Deprecated("Use DpSize", replaceWith = ReplaceWith("DpSize", "androidx.compose.ui.unit.DpSize")) inline class WindowSize internal constructor(@PublishedApi internal val packedValue: Long) { /** * `true` if the window size has specified values * * `false` if the window size are not yet determined ([width] or [height] are [Dp.Unspecified]) */ val isSpecified: Boolean get() = width.isSpecified && height.isSpecified /** * The width of the window in [Dp]. If it is [Dp.Unspecified] then the width of the window * will determined by the inner content. */ @Stable val width: Dp get() = unpackFloat1(packedValue).dp /** * The height of the window in [Dp]. If it is [Dp.Unspecified] then the height of the window * will determined by the inner content. */ @Stable val height: Dp get() = unpackFloat2(packedValue).dp @Stable operator fun component1(): Dp = width @Stable operator fun component2(): Dp = height /** * Returns a copy of this [WindowSize] instance optionally overriding the * [width] or [height] parameter. */ @Suppress("DEPRECATION") fun copy( width: Dp = this.width, height: Dp = this.height ): WindowSize = WindowSize(width, height) @Stable override fun toString() = "$width x $height" }
apache-2.0
cc9acd3a66fef75765b5f59c05695845
30.897959
99
0.68768
4.047927
false
false
false
false
androidx/androidx
room/room-compiler/src/test/kotlin/androidx/room/writer/DaoWriterTest.kt
3
6876
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.writer import COMMON import androidx.room.compiler.codegen.CodeLanguage import androidx.room.compiler.codegen.toJavaPoet import androidx.room.compiler.processing.XTypeElement import androidx.room.compiler.processing.util.Source import androidx.room.compiler.processing.util.XTestInvocation import androidx.room.compiler.processing.util.runProcessorTest import androidx.room.ext.RoomTypeNames.ROOM_DB import androidx.room.processor.DaoProcessor import androidx.room.testing.context import createVerifierFromEntitiesAndViews import java.util.Locale import loadTestSource import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class DaoWriterTest { @Test fun complexDao() { singleDao( loadTestSource( fileName = "databasewriter/input/ComplexDatabase.java", qName = "foo.bar.ComplexDatabase" ), loadTestSource( fileName = "daoWriter/input/ComplexDao.java", qName = "foo.bar.ComplexDao" ) ) { val backendFolder = backendFolder(it) it.assertCompilationResult { generatedSource( loadTestSource( fileName = "daoWriter/output/$backendFolder/ComplexDao.java", qName = "foo.bar.ComplexDao_Impl" ) ) } } } @Test fun complexDao_turkishLocale() { val originalLocale = Locale.getDefault() try { Locale.setDefault(Locale("tr")) // Turkish has special upper/lowercase i chars complexDao() } finally { Locale.setDefault(originalLocale) } } @Test fun writerDao() { singleDao( loadTestSource( fileName = "daoWriter/input/WriterDao.java", qName = "foo.bar.WriterDao" ) ) { val backendFolder = backendFolder(it) it.assertCompilationResult { generatedSource( loadTestSource( fileName = "daoWriter/output/$backendFolder/WriterDao.java", qName = "foo.bar.WriterDao_Impl" ) ) } } } @Test fun deletionDao() { singleDao( loadTestSource( fileName = "daoWriter/input/DeletionDao.java", qName = "foo.bar.DeletionDao" ) ) { val backendFolder = backendFolder(it) it.assertCompilationResult { generatedSource( loadTestSource( fileName = "daoWriter/output/$backendFolder/DeletionDao.java", qName = "foo.bar.DeletionDao_Impl" ) ) } } } @Test fun updateDao() { singleDao( loadTestSource( fileName = "daoWriter/input/UpdateDao.java", qName = "foo.bar.UpdateDao" ) ) { val backendFolder = backendFolder(it) it.assertCompilationResult { generatedSource( loadTestSource( fileName = "daoWriter/output/$backendFolder/UpdateDao.java", qName = "foo.bar.UpdateDao_Impl" ) ) } } } @Test fun upsertDao() { singleDao( loadTestSource( fileName = "daoWriter/input/UpsertDao.java", qName = "foo.bar.UpsertDao" ) ) { val backendFolder = backendFolder(it) it.assertCompilationResult { generatedSource( loadTestSource( fileName = "daoWriter/output/$backendFolder/UpsertDao.java", qName = "foo.bar.UpsertDao_Impl" ) ) } } } private fun singleDao( vararg inputs: Source, handler: (XTestInvocation) -> Unit ) { val sources = listOf( COMMON.USER, COMMON.MULTI_PKEY_ENTITY, COMMON.BOOK, COMMON.LIVE_DATA, COMMON.COMPUTABLE_LIVE_DATA, COMMON.RX2_SINGLE, COMMON.RX2_MAYBE, COMMON.RX2_COMPLETABLE, COMMON.USER_SUMMARY, COMMON.RX2_ROOM, COMMON.PARENT, COMMON.CHILD1, COMMON.CHILD2, COMMON.INFO, COMMON.LISTENABLE_FUTURE, COMMON.GUAVA_ROOM ) + inputs runProcessorTest( sources = sources ) { invocation -> val dao = invocation.roundEnv .getElementsAnnotatedWith( androidx.room.Dao::class.qualifiedName!! ).filterIsInstance<XTypeElement>().firstOrNull() if (dao != null) { val db = invocation.roundEnv .getElementsAnnotatedWith( androidx.room.Database::class.qualifiedName!! ).filterIsInstance<XTypeElement>().firstOrNull() ?: invocation.context.processingEnv .requireTypeElement(ROOM_DB.toJavaPoet()) val dbType = db.type val dbVerifier = createVerifierFromEntitiesAndViews(invocation) invocation.context.attachDatabaseVerifier(dbVerifier) val parser = DaoProcessor( baseContext = invocation.context, element = dao, dbType = dbType, dbVerifier = dbVerifier ) val parsedDao = parser.process() DaoWriter(parsedDao, db, CodeLanguage.JAVA) .write(invocation.processingEnv) } // we could call handler inside the if block but if something happens and we cannot // find the dao, test will never assert on generated code. handler(invocation) } } private fun backendFolder(invocation: XTestInvocation) = invocation.processingEnv.backend.name.lowercase() }
apache-2.0
7989f11de2c9e4cbd17fc009070064f5
33.552764
95
0.555992
5.041056
false
true
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/find/actions/findUsages.kt
2
3290
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:ApiStatus.Internal package com.intellij.find.actions import com.intellij.find.FindSettings import com.intellij.find.actions.SearchOptionsService.SearchVariant import com.intellij.find.usages.api.SearchTarget import com.intellij.find.usages.api.UsageHandler import com.intellij.find.usages.impl.AllSearchOptions import com.intellij.find.usages.impl.buildUsageViewQuery import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.Factory import com.intellij.psi.impl.search.runSearch import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.usageView.UsageViewBundle import com.intellij.usageView.UsageViewContentManager import com.intellij.usages.UsageSearcher import com.intellij.usages.UsageViewManager import com.intellij.usages.UsageViewPresentation import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls fun findUsages(showDialog: Boolean, project: Project, selectedScope: SearchScope, target: SearchTarget) { val allOptions = getSearchOptions(SearchVariant.FIND_USAGES, target, selectedScope) if (showDialog) { val canReuseTab = canReuseTab(project) val dialog = UsageOptionsDialog(project, target.displayString, allOptions, target.showScopeChooser(), canReuseTab) if (!dialog.showAndGet()) { // cancelled return } val dialogResult: AllSearchOptions = dialog.result() setSearchOptions(SearchVariant.FIND_USAGES, target, dialogResult) findUsages(project, target, dialogResult) } else { findUsages(project, target, allOptions) } } internal fun findUsages(project: Project, target: SearchTarget, allOptions: AllSearchOptions) { val query = buildUsageViewQuery(project, target, allOptions) val factory = Factory { UsageSearcher { runSearch(project, query, it) } } val usageViewPresentation = UsageViewPresentation().apply { searchString = target.usageHandler.getSearchString(allOptions) scopeText = allOptions.options.searchScope.displayName tabText = UsageViewBundle.message("search.title.0.in.1", searchString, scopeText) isOpenInNewTab = FindSettings.getInstance().isShowResultsInSeparateView || !canReuseTab(project) } project.service<UsageViewManager>().searchAndShowUsages( arrayOf(SearchTarget2UsageTarget(project, target, allOptions)), factory, false, true, usageViewPresentation, null ) } private fun canReuseTab(project: Project): Boolean { val contentManager = UsageViewContentManager.getInstance(project) val selectedContent = contentManager.getSelectedContent(true) return if (selectedContent == null) { contentManager.reusableContentsCount != 0 } else { !selectedContent.isPinned } } internal val SearchTarget.displayString: String get() = presentation().presentableText @Nls(capitalization = Nls.Capitalization.Title) internal fun UsageHandler.getSearchString(allOptions: AllSearchOptions): String { return getSearchString(allOptions.options) } internal fun SearchTarget.showScopeChooser(): Boolean { return maximalSearchScope !is LocalSearchScope }
apache-2.0
8a9ff5233aebdfadcc212e5147068a63
36.816092
120
0.792705
4.300654
false
false
false
false
NordicSemiconductor/Android-DFU-Library
app/src/main/java/no/nordicsemi/android/dfu/app/DFUApplication.kt
1
3102
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.dfu.app import android.app.Application import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.annotation.RequiresApi import dagger.hilt.android.HiltAndroidApp import no.nordicsemi.android.dfu.analytics.DfuAnalytics import no.nordicsemi.android.dfu.analytics.AppOpenEvent import javax.inject.Inject @HiltAndroidApp class DFUApplication : Application() { @Inject lateinit var analytics: DfuAnalytics override fun onCreate() { super.onCreate() analytics.logEvent(AppOpenEvent) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createDfuNotificationChannel(this) } } /* Note: The same method is available in DFUServiceInitializer. */ @RequiresApi(api = Build.VERSION_CODES.O) private fun createDfuNotificationChannel(context: Context) { val channel = NotificationChannel( "dfu", context.getString(R.string.dfu_channel_name), NotificationManager.IMPORTANCE_LOW ) channel.description = context.getString(R.string.dfu_channel_description) channel.setShowBadge(false) channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC val notificationManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } }
bsd-3-clause
2aa0b9e30f4f88c181707da26fcd0065
38.769231
103
0.755319
4.809302
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadPresenter.kt
2
4470
package eu.kanade.tachiyomi.ui.recently_read import android.os.Bundle import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaChapterHistory import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import rx.Observable import rx.android.schedulers.AndroidSchedulers import timber.log.Timber import uy.kohesive.injekt.injectLazy import java.util.* /** * Presenter of RecentlyReadFragment. * Contains information and data for fragment. * Observable updates should be called from here. */ class RecentlyReadPresenter : BasePresenter<RecentlyReadFragment>() { /** * Used to connect to database */ val db: DatabaseHelper by injectLazy() override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) // Used to get a list of recently read manga getRecentMangaObservable() .subscribeLatestCache({ view, historyList -> view.onNextManga(historyList) }) } /** * Get recent manga observable * @return list of history */ fun getRecentMangaObservable(): Observable<List<MangaChapterHistory>> { // Set date for recent manga val cal = Calendar.getInstance() cal.time = Date() cal.add(Calendar.MONTH, -1) return db.getRecentManga(cal.time).asRxObservable() .observeOn(AndroidSchedulers.mainThread()) } /** * Reset last read of chapter to 0L * @param history history belonging to chapter */ fun removeFromHistory(history: History) { history.last_read = 0L db.updateHistoryLastRead(history).asRxObservable() .subscribe() } /** * Removes all chapters belonging to manga from history. * @param mangaId id of manga */ fun removeAllFromHistory(mangaId: Long) { db.getHistoryByMangaId(mangaId).asRxSingle() .map { list -> list.forEach { it.last_read = 0L } db.updateHistoryLastRead(list).executeAsBlocking() } .subscribe() } /** * Open the next chapter instead of the current one. * @param chapter the chapter of the history object. * @param manga the manga of the chapter. */ fun openNextChapter(chapter: Chapter, manga: Manga) { val sortFunction: (Chapter, Chapter) -> Int = when (manga.sorting) { Manga.SORTING_SOURCE -> { c1, c2 -> c2.source_order.compareTo(c1.source_order) } Manga.SORTING_NUMBER -> { c1, c2 -> c1.chapter_number.compareTo(c2.chapter_number) } else -> throw NotImplementedError("Unknown sorting method") } db.getChapters(manga).asRxSingle() .map { it.sortedWith(Comparator<Chapter> { c1, c2 -> sortFunction(c1, c2) }) } .map { chapters -> val currChapterIndex = chapters.indexOfFirst { chapter.id == it.id } when (manga.sorting) { Manga.SORTING_SOURCE -> { chapters.getOrNull(currChapterIndex + 1) } Manga.SORTING_NUMBER -> { val chapterNumber = chapter.chapter_number var nextChapter: Chapter? = null for (i in (currChapterIndex + 1) until chapters.size) { val c = chapters[i] if (c.chapter_number > chapterNumber && c.chapter_number <= chapterNumber + 1) { nextChapter = c break } } nextChapter } else -> throw NotImplementedError("Unknown sorting method") } } .toObservable() .observeOn(AndroidSchedulers.mainThread()) .subscribeFirst({ view, chapter -> view.onOpenNextChapter(chapter, manga) }, { view, error -> Timber.e(error) }) } }
gpl-3.0
7911bf928ff53bee29145a61a058a26d
35.639344
96
0.559284
4.966667
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/Boxing.kt
1
9093
/* * Copyright 2010-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.kotlin.backend.konan import llvm.* import org.jetbrains.kotlin.backend.konan.ir.KonanSymbols import org.jetbrains.kotlin.backend.konan.llvm.* import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.name.Name internal fun KonanSymbols.getTypeConversion(actualType: IrType, expectedType: IrType): IrSimpleFunctionSymbol? = getTypeConversionImpl(actualType.getInlinedClassNative(), expectedType.getInlinedClassNative()) private fun KonanSymbols.getTypeConversionImpl( actualInlinedClass: IrClass?, expectedInlinedClass: IrClass? ): IrSimpleFunctionSymbol? { if (actualInlinedClass == expectedInlinedClass) return null return when { actualInlinedClass == null && expectedInlinedClass == null -> null actualInlinedClass != null && expectedInlinedClass == null -> context.getBoxFunction(actualInlinedClass) actualInlinedClass == null && expectedInlinedClass != null -> context.getUnboxFunction(expectedInlinedClass) else -> error("actual type is ${actualInlinedClass?.fqNameForIrSerialization}, expected ${expectedInlinedClass?.fqNameForIrSerialization}") }?.symbol } internal object DECLARATION_ORIGIN_INLINE_CLASS_SPECIAL_FUNCTION : IrDeclarationOriginImpl("INLINE_CLASS_SPECIAL_FUNCTION") internal val Context.getBoxFunction: (IrClass) -> IrSimpleFunction by Context.lazyMapMember { inlinedClass -> require(inlinedClass.isUsedAsBoxClass()) val classes = mutableListOf<IrClass>(inlinedClass) var parent = inlinedClass.parent while (parent is IrClass) { classes.add(parent) parent = parent.parent } require(parent is IrFile) { "Local inline classes are not supported" } val symbols = ir.symbols val isNullable = inlinedClass.inlinedClassIsNullable() val unboxedType = inlinedClass.defaultOrNullableType(isNullable) val boxedType = symbols.any.owner.defaultOrNullableType(isNullable) val parameterType = unboxedType val returnType = boxedType val startOffset = inlinedClass.startOffset val endOffset = inlinedClass.endOffset IrFunctionImpl( startOffset, endOffset, DECLARATION_ORIGIN_INLINE_CLASS_SPECIAL_FUNCTION, IrSimpleFunctionSymbolImpl(), Name.special("<${classes.reversed().joinToString(".") { it.name.asString() }}-box>"), DescriptorVisibilities.PUBLIC, Modality.FINAL, returnType, isInline = false, isExternal = false, isTailrec = false, isSuspend = false, isExpect = false, isFakeOverride = false, isOperator = false, isInfix = false ).also { function -> function.valueParameters = listOf( IrValueParameterImpl( startOffset, endOffset, IrDeclarationOrigin.DEFINED, IrValueParameterSymbolImpl(), Name.identifier("value"), index = 0, varargElementType = null, isCrossinline = false, type = parameterType, isNoinline = false, isHidden = false, isAssignable = false ).apply { parent = function }) function.parent = inlinedClass.getContainingFile()!! } } internal val Context.getUnboxFunction: (IrClass) -> IrSimpleFunction by Context.lazyMapMember { inlinedClass -> require(inlinedClass.isUsedAsBoxClass()) val classes = mutableListOf<IrClass>(inlinedClass) var parent = inlinedClass.parent while (parent is IrClass) { classes.add(parent) parent = parent.parent } require(parent is IrFile) { "Local inline classes are not supported" } val symbols = ir.symbols val isNullable = inlinedClass.inlinedClassIsNullable() val unboxedType = inlinedClass.defaultOrNullableType(isNullable) val boxedType = symbols.any.owner.defaultOrNullableType(isNullable) val parameterType = boxedType val returnType = unboxedType val startOffset = inlinedClass.startOffset val endOffset = inlinedClass.endOffset IrFunctionImpl( startOffset, endOffset, DECLARATION_ORIGIN_INLINE_CLASS_SPECIAL_FUNCTION, IrSimpleFunctionSymbolImpl(), Name.special("<${classes.reversed().joinToString(".") { it.name.asString() } }-unbox>"), DescriptorVisibilities.PUBLIC, Modality.FINAL, returnType, isInline = false, isExternal = false, isTailrec = false, isSuspend = false, isExpect = false, isFakeOverride = false, isOperator = false, isInfix = false ).also { function -> function.valueParameters = listOf( IrValueParameterImpl( startOffset, endOffset, IrDeclarationOrigin.DEFINED, IrValueParameterSymbolImpl(), Name.identifier("value"), index = 0, varargElementType = null, isCrossinline = false, type = parameterType, isNoinline = false, isHidden = false, isAssignable = false ).apply { parent = function }) function.parent = inlinedClass.getContainingFile()!! } } /** * Initialize static boxing. * If output target is native binary then the cache is created. */ internal fun initializeCachedBoxes(context: Context) { if (context.producedLlvmModuleContainsStdlib) { BoxCache.values().forEach { cache -> val cacheName = "${cache.name}_CACHE" val rangeStart = "${cache.name}_RANGE_FROM" val rangeEnd = "${cache.name}_RANGE_TO" initCache(cache, context, cacheName, rangeStart, rangeEnd) } } } /** * Adds global that refers to the cache. */ private fun initCache(cache: BoxCache, context: Context, cacheName: String, rangeStartName: String, rangeEndName: String) { val kotlinType = context.irBuiltIns.getKotlinClass(cache) val staticData = context.llvm.staticData val llvmType = staticData.getLLVMType(kotlinType.defaultType) val (start, end) = context.config.target.getBoxCacheRange(cache) // Constancy of these globals allows LLVM's constant propagation and DCE // to remove fast path of boxing function in case of empty range. staticData.placeGlobal(rangeStartName, createConstant(llvmType, start), true) .setConstant(true) staticData.placeGlobal(rangeEndName, createConstant(llvmType, end), true) .setConstant(true) val values = (start..end).map { staticData.createInitializer(kotlinType, createConstant(llvmType, it)) } val llvmBoxType = structType(context.llvm.runtime.objHeaderType, llvmType) staticData.placeGlobalConstArray(cacheName, llvmBoxType, values, true).llvm } private fun createConstant(llvmType: LLVMTypeRef, value: Int): ConstValue = constValue(LLVMConstInt(llvmType, value.toLong(), 1)!!) // When start is greater than end then `inRange` check is always false // and can be eliminated by LLVM. private val emptyRange = 1 to 0 // Memory usage is around 20kb. private val BoxCache.defaultRange get() = when (this) { BoxCache.BOOLEAN -> (0 to 1) BoxCache.BYTE -> (-128 to 127) BoxCache.SHORT -> (-128 to 127) BoxCache.CHAR -> (0 to 255) BoxCache.INT -> (-128 to 127) BoxCache.LONG -> (-128 to 127) } private fun KonanTarget.getBoxCacheRange(cache: BoxCache): Pair<Int, Int> = when (this) { is KonanTarget.ZEPHYR -> emptyRange else -> cache.defaultRange } internal fun IrBuiltIns.getKotlinClass(cache: BoxCache): IrClass = when (cache) { BoxCache.BOOLEAN -> booleanClass BoxCache.BYTE -> byteClass BoxCache.SHORT -> shortClass BoxCache.CHAR -> charClass BoxCache.INT -> intClass BoxCache.LONG -> longClass }.owner // TODO: consider adding box caches for unsigned types. enum class BoxCache { BOOLEAN, BYTE, SHORT, CHAR, INT, LONG }
apache-2.0
46968c56da76593f3416e65f0ed35943
38.025751
147
0.668536
4.750784
false
false
false
false
GunoH/intellij-community
plugins/eclipse/src/org/jetbrains/idea/eclipse/codeStyleMapping/util/SettingMapping.kt
2
6444
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.eclipse.codeStyleMapping.util import java.lang.IllegalArgumentException import kotlin.reflect.KMutableProperty0 interface SettingMapping<External> { /** * @throws IllegalStateException if [isExportAllowed] == false */ fun export(): External /** * @throws IllegalStateException if [isImportAllowed] == false * @throws UnexpectedIncomingValue if [value] could not be converted anywhere in the chain */ fun import(value: External) val isExportAllowed get() = true val isImportAllowed get() = true } fun <E> SettingMapping<E>.importIfAllowed(value: E) { if (isImportAllowed) import(value) } abstract class WrappingSettingMapping<Outer, Inner>(val wrappee: SettingMapping<Inner>) : SettingMapping<Outer> { override val isExportAllowed by wrappee::isExportAllowed override val isImportAllowed by wrappee::isImportAllowed } class ConvertingSettingMapping<External, Internal>( wrappee: SettingMapping<Internal>, private val convertor: Convertor<External, Internal> ) : WrappingSettingMapping<External, Internal>(wrappee) { override fun export(): External = convertor.convertOutgoing(wrappee.export()) override fun import(value: External) = wrappee.import(convertor.convertIncoming(value)) } class ConstSettingMapping<E>(val value: E) : SettingMapping<E> { override fun export(): E = value override fun import(value: E) { throw IllegalStateException("const setting mapping cannot import anything") } override val isImportAllowed = false } interface Convertor<E, I> { fun convertIncoming(value: E): I fun convertOutgoing(value: I): E } /** * Signalizes that a value could not be parsed correctly on import. */ class UnexpectedIncomingValue(val value: Any) : IllegalArgumentException(value.toString()) object IntConvertor : Convertor<String, Int> { override fun convertOutgoing(value: Int): String = value.toString() override fun convertIncoming(value: String): Int = try { value.toInt() } catch (e: NumberFormatException) { throw UnexpectedIncomingValue(value) } } object BooleanConvertor : Convertor<String, Boolean> { override fun convertOutgoing(value: Boolean): String = value.toString() override fun convertIncoming(value: String): Boolean = when (value.lowercase()) { "true" -> true "false" -> false else -> throw UnexpectedIncomingValue(value) } } class FieldSettingMapping<I>( val field: KMutableProperty0<I>, ) : SettingMapping<I> { override fun export(): I = field.getter.call() override fun import(value: I) = field.setter.call(value) } class AlsoImportFieldsSettingMapping<I>( wrappee: SettingMapping<I>, val fields: Array<out KMutableProperty0<I>> ) : WrappingSettingMapping<I, I>(wrappee) { override fun export(): I = wrappee.export() override fun import(value: I) { fields.forEach { it.setter.call(value) } wrappee.import(value) } } class ComputableSettingMapping<I>( val _import: (I) -> Unit, val _export: () -> I ) : SettingMapping<I> { override fun export() = _export() override fun import(value: I) = _import(value) } class ConditionalImportSettingMapping<External>( wrappee: SettingMapping<External>, override val isImportAllowed: Boolean ) : WrappingSettingMapping<External, External>(wrappee) { override fun export(): External = wrappee.export() override fun import(value: External) { if (isImportAllowed) { wrappee.import(value) } else { throw IllegalStateException() } } } object SettingsMappingHelpers { /** * Create export only mapping. * * Meant for cases when there is no corresponding IDEA settings field (the behavior is *constant*). * I.e. for Eclipse options, that do not have a counterpart in IDEA, * but the default behaviour in IDEA corresponds to one of the possible values for this Eclipse option. */ fun <I> const(value: I) = ConstSettingMapping(value) /** * Create mapping to a **bound** property. * * Note that the property has to be public, so that the mapping object can call its getter/setter */ fun <T> field(field: KMutableProperty0<T>) = FieldSettingMapping(field) fun <I> compute(import: (I) -> Unit, export: () -> I) = ComputableSettingMapping(import, export) /** * Does not export nor import any setting. * * It is used to explicitly declare that an Eclipse option is not mapped to anything. */ fun ignored() = IgnoredSettingMapping } fun <External, Internal> SettingMapping<Internal>.convert(convertor: Convertor<External, Internal>) = ConvertingSettingMapping(this, convertor) fun SettingMapping<Boolean>.convertBoolean() = convert(BooleanConvertor) fun SettingMapping<Int>.convertInt() = convert(IntConvertor) /** * Specifies that a [FieldSettingMapping] should only be used for export. * * Useful for N to 1 (external to internal) mappings. * I.e. when multiple options in Eclipse correspond to a single IDEA setting (field). * This function allows us to control which one of the Eclipse options will be used to set the IDEA setting, * otherwise, the result depends on the order, in which settings are imported. */ fun <External> SettingMapping<External>.doNotImport() = ConditionalImportSettingMapping(this, false) /** * Specify fields whose values should be set alongside a [FieldSettingMapping] on import. * * Useful 1 to N (external to internal) mappings. * I.e. when setting one option in Eclipse corresponds to setting multiple settings in IDEA. * Only the original ([FieldSettingMapping]) will be used for export. */ fun <Internal> FieldSettingMapping<Internal>.alsoSet(vararg fields: KMutableProperty0<Internal>) = AlsoImportFieldsSettingMapping(this, fields) class InvertingBooleanSettingMapping(wrappee: SettingMapping<Boolean>) : WrappingSettingMapping<Boolean, Boolean>(wrappee) { override fun export(): Boolean = !wrappee.export() override fun import(value: Boolean) = wrappee.import(!value) } fun SettingMapping<Boolean>.invert() = InvertingBooleanSettingMapping(this) object IgnoredSettingMapping : SettingMapping<String> { override fun export(): String { throw IllegalStateException() } override fun import(value: String) { throw IllegalStateException() } override val isExportAllowed = false override val isImportAllowed = false }
apache-2.0
bf809d7438357db1d45eb1538199159c
31.225
120
0.737585
4.047739
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/toolWindow/ToolWindowPaneOldButtonManager.kt
3
7523
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") package com.intellij.toolWindow import com.intellij.ide.ui.UISettings import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.RegisterToolWindowTask import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.WindowInfo import com.intellij.openapi.wm.impl.AbstractDroppableStripe import com.intellij.openapi.wm.impl.ToolWindowImpl import com.intellij.ui.awt.DevicePoint import java.awt.Dimension import java.awt.Rectangle import javax.swing.Icon import javax.swing.JComponent import javax.swing.JLayeredPane import javax.swing.SwingConstants internal class ToolWindowPaneOldButtonManager(paneId: String) : ToolWindowButtonManager { private val leftStripe = Stripe(paneId, SwingConstants.LEFT) private val rightStripe = Stripe(paneId, SwingConstants.RIGHT) private val bottomStripe = Stripe(paneId, SwingConstants.BOTTOM) private val topStripe = Stripe(paneId, SwingConstants.TOP) private val stripes = java.util.List.of(topStripe, leftStripe, bottomStripe, rightStripe) override val isNewUi: Boolean get() = false override fun add(pane: JComponent) { } override fun addToToolWindowPane(pane: JComponent) { pane.add(topStripe, JLayeredPane.POPUP_LAYER, -1) pane.add(leftStripe, JLayeredPane.POPUP_LAYER, -1) pane.add(bottomStripe, JLayeredPane.POPUP_LAYER, -1) pane.add(rightStripe, JLayeredPane.POPUP_LAYER, -1) } override fun updateToolStripesVisibility(showButtons: Boolean, state: ToolWindowPaneState): Boolean { val oldVisible = leftStripe.isVisible val visible = showButtons || state.isStripesOverlaid leftStripe.isVisible = visible rightStripe.isVisible = visible topStripe.isVisible = visible bottomStripe.isVisible = visible if (!Registry.`is`("disable.toolwindow.overlay")) { val overlaid = !showButtons && state.isStripesOverlaid leftStripe.setOverlaid(overlaid) rightStripe.setOverlaid(overlaid) topStripe.setOverlaid(overlaid) bottomStripe.setOverlaid(overlaid) } return oldVisible != visible } override fun layout(size: Dimension, layeredPane: JComponent) { val topSize = topStripe.preferredSize val bottomSize = bottomStripe.preferredSize val leftSize = leftStripe.preferredSize val rightSize = rightStripe.preferredSize val topBounds = Rectangle(0, 0, size.width, topSize.height) val height = size.height - topSize.height - bottomSize.height val leftBounds = Rectangle(0, topSize.height, leftSize.width, height) val rightBounds = Rectangle(size.width - rightSize.width, topSize.height, rightSize.width, height) val bottomBounds = Rectangle(0, size.height - bottomSize.height, size.width, bottomSize.height) topStripe.putClientProperty(Stripe.VIRTUAL_BOUNDS, topBounds) leftStripe.putClientProperty(Stripe.VIRTUAL_BOUNDS, leftBounds) rightStripe.putClientProperty(Stripe.VIRTUAL_BOUNDS, rightBounds) bottomStripe.putClientProperty(Stripe.VIRTUAL_BOUNDS, bottomBounds) if (topStripe.isVisible) { topStripe.bounds = topBounds leftStripe.bounds = leftBounds rightStripe.bounds = rightBounds bottomStripe.bounds = bottomBounds val uiSettings = UISettings.getInstance() if (uiSettings.hideToolStripes || uiSettings.presentationMode) { layeredPane.setBounds(0, 0, size.width, size.height) } else { val width = size.width - leftSize.width - rightSize.width layeredPane.setBounds(leftSize.width, topSize.height, width, height) } } else { topStripe.setBounds(0, 0, 0, 0) bottomStripe.setBounds(0, 0, 0, 0) leftStripe.setBounds(0, 0, 0, 0) rightStripe.setBounds(0, 0, 0, 0) layeredPane.setBounds(0, 0, size.width, size.height) } } override fun validateAndRepaint() { for (stripe in stripes) { stripe.revalidate() stripe.repaint() } } override fun revalidateNotEmptyStripes() { for (stripe in stripes) { if (stripe.getButtons().isNotEmpty()) { stripe.revalidate() } } } override fun getBottomHeight() = if (bottomStripe.isVisible) bottomStripe.height else 0 override fun getStripeFor(anchor: ToolWindowAnchor, isSplit: Boolean?): Stripe { return when(anchor) { ToolWindowAnchor.TOP -> topStripe ToolWindowAnchor.BOTTOM -> bottomStripe ToolWindowAnchor.LEFT -> leftStripe ToolWindowAnchor.RIGHT -> rightStripe else -> throw IllegalArgumentException("Anchor=$anchor") } } override fun getStripeFor(devicePoint: DevicePoint, preferred: AbstractDroppableStripe, pane: JComponent): AbstractDroppableStripe? { val screenPoint = devicePoint.getLocationOnScreen(pane) if (Rectangle(pane.locationOnScreen, pane.size).contains(screenPoint)) { // Find the stripe that owns this point. Depending on implementation, this could be just the physical bounds of the stripe, or could // include the virtual bounds of the drop area for the stripe. Because these bounds might overlap, check the preferred stripe first if (preferred.containsPoint(screenPoint)) { return preferred } return stripes.firstOrNull { it.containsPoint(screenPoint) } } return null } override fun getStripeWidth(anchor: ToolWindowAnchor): Int { val stripe = getStripeFor(anchor, null) return if (stripe.isVisible && stripe.isShowing) stripe.width else 0 } override fun getStripeHeight(anchor: ToolWindowAnchor): Int { // We no longer support the top stripe if (anchor == ToolWindowAnchor.TOP) return 0 val stripe = getStripeFor(anchor, null) return if (stripe.isVisible && stripe.isShowing) stripe.height else 0 } override fun startDrag() { for (s in stripes) { if (s.isVisible) { s.startDrag() } } } override fun stopDrag() { for (s in stripes) { if (s.isVisible) { s.stopDrag() } } } override fun reset() { stripes.forEach(Stripe::reset) } override fun createStripeButton(toolWindow: ToolWindowImpl, info: WindowInfo, task: RegisterToolWindowTask?): StripeButtonManager { val button = StripeButton(toolWindow) button.isSelected = info.isVisible button.updatePresentation() val stripe = getStripeFor(info.anchor, info.isSplit) val manager = object : StripeButtonManager { override val id: String = toolWindow.id override val toolWindow = toolWindow override val windowDescriptor: WindowInfo get() = toolWindow.windowInfo override fun getComponent() = button override fun updateState(toolWindow: ToolWindowImpl) { button.isSelected = toolWindow.isVisible button.updateState(toolWindow) } override fun updatePresentation() { button.updatePresentation() } override fun updateIcon(icon: Icon?) { button.updateIcon(icon) } override fun remove(anchor: ToolWindowAnchor, split: Boolean) { stripe.removeButton(this) } } stripe.addButton(manager) return manager } override fun hasButtons(): Boolean { return leftStripe.getButtons().isNotEmpty() || rightStripe.getButtons().isNotEmpty() || bottomStripe.getButtons().isNotEmpty() || topStripe.getButtons().isNotEmpty() } }
apache-2.0
799772900d8f724f1f2695bc5eedf182
34.490566
138
0.71833
4.358633
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/wizard/AbstractNewProjectWizardBuilder.kt
1
3290
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.wizard import com.intellij.ide.projectWizard.NewProjectWizardCollector import com.intellij.ide.util.projectWizard.ModuleBuilder import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.nameProperty import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.pathProperty import com.intellij.openapi.Disposable import com.intellij.openapi.module.ModifiableModuleModel import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModuleType import com.intellij.openapi.project.Project import javax.swing.Icon abstract class AbstractNewProjectWizardBuilder : ModuleBuilder() { private var panel: NewProjectWizardStepPanel? = null abstract override fun getPresentableName(): String abstract override fun getDescription(): String abstract override fun getNodeIcon(): Icon protected abstract fun createStep(context: WizardContext): NewProjectWizardStep final override fun getModuleType() = object : ModuleType<AbstractNewProjectWizardBuilder>("newWizard.${this::class.java.name}") { override fun createModuleBuilder() = this@AbstractNewProjectWizardBuilder override fun getName() = [email protected] override fun getDescription() = [email protected] override fun getNodeIcon(isOpened: Boolean) = [email protected] } final override fun getCustomOptionsStep(context: WizardContext, parentDisposable: Disposable): ModuleWizardStep { val wizardStep = createStep(context) wizardStep.pathProperty.afterChange { NewProjectWizardCollector.logLocationChanged(context, this::class.java) } wizardStep.nameProperty.afterChange { NewProjectWizardCollector.logNameChanged(context, this::class.java) } panel = NewProjectWizardStepPanel(wizardStep) return BridgeStep(panel!!) } override fun commitModule(project: Project, model: ModifiableModuleModel?): Module? { val step = panel!!.step return detectCreatedModule(project) { step.setupProject(project) NewProjectWizardCollector.logGeneratorFinished(step.context, this::class.java) } } override fun cleanup() { panel = null } private class BridgeStep(private val panel: NewProjectWizardStepPanel) : ModuleWizardStep(), NewProjectWizardStep by panel.step { override fun validate() = panel.validate() override fun updateDataModel() = panel.apply() override fun getPreferredFocusedComponent() = panel.getPreferredFocusedComponent() override fun getComponent() = panel.component } companion object { private fun detectCreatedModule(project: Project, action: () -> Unit): Module? { val manager = ModuleManager.getInstance(project) val modules = manager.modules action() return manager.modules.find { it !in modules } } } }
apache-2.0
c42203b1b96a071554705f5b9d08735c
40.1375
158
0.765046
5.14867
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinGradleModelBuilder.kt
1
14696
// 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 import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.provider.Property import org.gradle.tooling.BuildController import org.gradle.tooling.model.Model import org.gradle.tooling.model.build.BuildEnvironment import org.gradle.tooling.model.gradle.GradleBuild import org.gradle.util.GradleVersion import org.jetbrains.kotlin.idea.gradleTooling.arguments.CACHE_MAPPER_BRANCHING import org.jetbrains.kotlin.idea.gradleTooling.arguments.CachedExtractedArgsInfo import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCachingChain import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCachingManager.cacheCompilerArgument import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheAware import org.jetbrains.kotlin.idea.projectModel.KotlinTaskProperties import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext import org.jetbrains.plugins.gradle.tooling.ModelBuilderService import java.io.File import java.io.Serializable import java.lang.reflect.InvocationTargetException import java.util.* @Deprecated("Use org.jetbrains.kotlin.idea.projectModel.CachedArgsInfo instead") interface ArgsInfo : Serializable { val currentArguments: List<String> val defaultArguments: List<String> val dependencyClasspath: List<String> } @Suppress("DEPRECATION") @Deprecated("Use org.jetbrains.kotlin.idea.gradleTooling.CachedCompilerArgumentsBySourceSet instead") typealias CompilerArgumentsBySourceSet = Map<String, ArgsInfo> typealias CachedCompilerArgumentsBySourceSet = Map<String, CachedExtractedArgsInfo> typealias AdditionalVisibleSourceSetsBySourceSet = Map</* Source Set Name */ String, /* Visible Source Set Names */ Set<String>> interface KotlinGradleModel : Serializable { val hasKotlinPlugin: Boolean @Suppress("DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") @Deprecated( "Use 'cachedCompilerArgumentsBySourceSet' instead", ReplaceWith("cachedCompilerArgumentsBySourceSet"), DeprecationLevel.ERROR ) val compilerArgumentsBySourceSet: CompilerArgumentsBySourceSet val additionalVisibleSourceSets: AdditionalVisibleSourceSetsBySourceSet val cachedCompilerArgumentsBySourceSet: CachedCompilerArgumentsBySourceSet val coroutines: String? val platformPluginId: String? val implements: List<String> val kotlinTarget: String? val kotlinTaskProperties: KotlinTaskPropertiesBySourceSet val gradleUserHome: String val partialCacheAware: CompilerArgumentsCacheAware } data class KotlinGradleModelImpl( override val hasKotlinPlugin: Boolean, @Suppress("OverridingDeprecatedMember", "DEPRECATION", "TYPEALIAS_EXPANSION_DEPRECATION") override val compilerArgumentsBySourceSet: CompilerArgumentsBySourceSet, override val cachedCompilerArgumentsBySourceSet: CachedCompilerArgumentsBySourceSet, override val additionalVisibleSourceSets: AdditionalVisibleSourceSetsBySourceSet, override val coroutines: String?, override val platformPluginId: String?, override val implements: List<String>, override val kotlinTarget: String? = null, override val kotlinTaskProperties: KotlinTaskPropertiesBySourceSet, override val gradleUserHome: String, override val partialCacheAware: CompilerArgumentsCacheAware ) : KotlinGradleModel abstract class AbstractKotlinGradleModelBuilder : ModelBuilderService { companion object { val kotlinCompileJvmTaskClasses = listOf( "org.jetbrains.kotlin.gradle.tasks.KotlinCompile_Decorated", "org.jetbrains.kotlin.gradle.tasks.KotlinCompileWithWorkers_Decorated" ) val kotlinCompileTaskClasses = kotlinCompileJvmTaskClasses + listOf( "org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile_Decorated", "org.jetbrains.kotlin.gradle.tasks.KotlinCompileCommon_Decorated", "org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompileWithWorkers_Decorated", "org.jetbrains.kotlin.gradle.tasks.KotlinCompileCommonWithWorkers_Decorated" ) val platformPluginIds = listOf("kotlin-platform-jvm", "kotlin-platform-js", "kotlin-platform-common") val pluginToPlatform = linkedMapOf( "kotlin" to "kotlin-platform-jvm", "kotlin2js" to "kotlin-platform-js" ) val kotlinPluginIds = listOf("kotlin", "kotlin2js", "kotlin-android") const val ABSTRACT_KOTLIN_COMPILE_CLASS = "org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile" const val kotlinProjectExtensionClass = "org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension" const val kotlinSourceSetClass = "org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet" const val kotlinPluginWrapper = "org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapperKt" private val propertyClassPresent = GradleVersion.current() >= GradleVersion.version("4.3") fun Task.getSourceSetName(): String = try { val method = javaClass.methods.firstOrNull { it.name.startsWith("getSourceSetName") && it.parameterTypes.isEmpty() } val sourceSetName = method?.invoke(this) when { sourceSetName is String -> sourceSetName propertyClassPresent && sourceSetName is Property<*> -> sourceSetName.get() as? String else -> null } } catch (e: InvocationTargetException) { null // can be thrown if property is not initialized yet } ?: "main" } } private const val REQUEST_FOR_NON_ANDROID_MODULES_ONLY = "*" class AndroidAwareGradleModelProvider<TModel>( private val modelClass: Class<TModel>, private val androidPluginIsRequestingVariantSpecificModels: Boolean ) : ProjectImportModelProvider { override fun populateBuildModels( controller: BuildController, buildModel: GradleBuild, consumer: ProjectImportModelProvider.BuildModelConsumer ) = Unit override fun populateProjectModels( controller: BuildController, projectModel: Model, modelConsumer: ProjectImportModelProvider.ProjectModelConsumer ) { val supportsParametrizedModels: Boolean = controller.findModel(BuildEnvironment::class.java)?.gradle?.gradleVersion?.let { // Parametrized build models were introduced in 4.4. Make sure that gradle import does not fail on pre-4.4 GradleVersion.version(it) >= GradleVersion.version("4.4") } ?: false val model = if (androidPluginIsRequestingVariantSpecificModels && supportsParametrizedModels) { controller.findModel(projectModel, modelClass, ModelBuilderService.Parameter::class.java) { it.value = REQUEST_FOR_NON_ANDROID_MODULES_ONLY } } else { controller.findModel(projectModel, modelClass) } if (model != null) { modelConsumer.consume(model, modelClass) } } class Result( private val hasProjectAndroidBasePlugin: Boolean, private val requestedVariantNames: Set<String>? ) { fun shouldSkipBuildAllCall(): Boolean = hasProjectAndroidBasePlugin && requestedVariantNames?.singleOrNull() == REQUEST_FOR_NON_ANDROID_MODULES_ONLY fun shouldSkipSourceSet(sourceSetName: String): Boolean = requestedVariantNames != null && !requestedVariantNames.contains(sourceSetName.lowercase(Locale.getDefault())) } companion object { fun parseParameter(project: Project, parameterValue: String?): Result { return Result( hasProjectAndroidBasePlugin = project.plugins.findPlugin("com.android.base") != null, requestedVariantNames = parameterValue?.splitToSequence(',')?.map { it.lowercase(Locale.getDefault()) }?.toSet() ) } } } class KotlinGradleModelBuilder : AbstractKotlinGradleModelBuilder(), ModelBuilderService.Ex { override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder { return ErrorMessageBuilder.create(project, e, "Gradle import errors") .withDescription("Unable to build Kotlin project configuration") } override fun canBuild(modelName: String?): Boolean = modelName == KotlinGradleModel::class.java.name private fun getImplementedProjects(project: Project): List<Project> { return listOf("expectedBy", "implement") .flatMap { project.configurations.findByName(it)?.dependencies ?: emptySet<Dependency>() } .filterIsInstance<ProjectDependency>() .mapNotNull { it.dependencyProject } } // see GradleProjectResolverUtil.getModuleId() in IDEA codebase private fun Project.pathOrName() = if (path == ":") name else path private fun Task.getDependencyClasspath(): List<String> { try { val abstractKotlinCompileClass = javaClass.classLoader.loadClass(ABSTRACT_KOTLIN_COMPILE_CLASS) val getCompileClasspath = abstractKotlinCompileClass.getDeclaredMethod("getCompileClasspath").apply { isAccessible = true } @Suppress("UNCHECKED_CAST") return (getCompileClasspath.invoke(this) as Collection<File>).map { it.path } } catch (e: ClassNotFoundException) { // Leave arguments unchanged } catch (e: NoSuchMethodException) { // Leave arguments unchanged } catch (e: InvocationTargetException) { // We can safely ignore this exception here as getCompileClasspath() gets called again at a later time // Leave arguments unchanged } return emptyList() } private fun getCoroutines(project: Project): String? { val kotlinExtension = project.extensions.findByName("kotlin") ?: return null val experimentalExtension = try { kotlinExtension::class.java.getMethod("getExperimental").invoke(kotlinExtension) } catch (e: NoSuchMethodException) { return null } return try { experimentalExtension::class.java.getMethod("getCoroutines").invoke(experimentalExtension)?.toString() } catch (e: NoSuchMethodException) { null } } override fun buildAll(modelName: String, project: Project): KotlinGradleModelImpl? { return buildAll(project, null) } override fun buildAll(modelName: String, project: Project, builderContext: ModelBuilderContext): KotlinGradleModelImpl? { return buildAll(project, builderContext) } private fun buildAll(project: Project, builderContext: ModelBuilderContext?): KotlinGradleModelImpl? { // When running in Android Studio, Android Studio would request specific source sets only to avoid syncing // currently not active build variants. We convert names to the lower case to avoid ambiguity with build variants // accidentally named starting with upper case. val androidVariantRequest = AndroidAwareGradleModelProvider.parseParameter(project, builderContext?.parameter) if (androidVariantRequest.shouldSkipBuildAllCall()) return null val kotlinPluginId = kotlinPluginIds.singleOrNull { project.plugins.findPlugin(it) != null } val platformPluginId = platformPluginIds.singleOrNull { project.plugins.findPlugin(it) != null } val target = project.getTarget() if (kotlinPluginId == null && platformPluginId == null && target == null) { return null } val cachedCompilerArgumentsBySourceSet = LinkedHashMap<String, CachedExtractedArgsInfo>() val additionalVisibleSourceSets = LinkedHashMap<String, Set<String>>() val extraProperties = HashMap<String, KotlinTaskProperties>() val masterMapper = builderContext?.getData(CACHE_MAPPER_BRANCHING) ?: return null val detachableMapper = masterMapper.branchOffDetachable(project.name == "buildSrc") val kotlinCompileTasks = target?.let { it.compilations ?: emptyList() } ?.mapNotNull { compilation -> compilation.getCompileKotlinTaskName(project) } ?: (project.getAllTasks(false)[project]?.filter { it.javaClass.name in kotlinCompileTaskClasses } ?: emptyList()) kotlinCompileTasks.forEach { compileTask -> if (compileTask.javaClass.name !in kotlinCompileTaskClasses) return@forEach val sourceSetName = compileTask.getSourceSetName() if (androidVariantRequest.shouldSkipSourceSet(sourceSetName)) return@forEach val currentArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileTask, detachableMapper, defaultsOnly = false) val defaultArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileTask, detachableMapper, defaultsOnly = true) val dependencyClasspath = compileTask.getDependencyClasspath().map { cacheCompilerArgument(it, detachableMapper) } cachedCompilerArgumentsBySourceSet[sourceSetName] = CachedExtractedArgsInfo(detachableMapper.cacheOriginIdentifier, currentArguments, defaultArguments, dependencyClasspath) additionalVisibleSourceSets[sourceSetName] = getAdditionalVisibleSourceSets(project, sourceSetName) extraProperties.acknowledgeTask(compileTask, null) } val platform = platformPluginId ?: pluginToPlatform.entries.singleOrNull { project.plugins.findPlugin(it.key) != null }?.value val implementedProjects = getImplementedProjects(project) return KotlinGradleModelImpl( hasKotlinPlugin = kotlinPluginId != null || platformPluginId != null, compilerArgumentsBySourceSet = emptyMap(), cachedCompilerArgumentsBySourceSet = cachedCompilerArgumentsBySourceSet, additionalVisibleSourceSets = additionalVisibleSourceSets, coroutines = getCoroutines(project), platformPluginId = platform, implements = implementedProjects.map { it.pathOrName() }, kotlinTarget = platform ?: kotlinPluginId, kotlinTaskProperties = extraProperties, gradleUserHome = project.gradle.gradleUserHomeDir.absolutePath, partialCacheAware = detachableMapper.detachCacheAware() ) } }
apache-2.0
7018dc5f4b843c644bbe6b103bc4bafd
49.675862
158
0.729927
5.643625
false
false
false
false
dariopellegrini/Spike
spike/src/main/java/com/dariopellegrini/spike/mapping/CoroutinesExtensions.kt
1
1675
package com.dariopellegrini.spike.mapping import com.dariopellegrini.spike.response.SpikeErrorResponse import com.dariopellegrini.spike.response.SpikeSuccessResponse import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.IOException class SuccessWrapper<T>(val base: T) class ErrorWrapper<T>(val base: T) val <T>SpikeSuccessResponse<T>.suspend: SuccessWrapper<SpikeSuccessResponse<T>> get() = SuccessWrapper(this) val <T>SpikeErrorResponse<T>.suspend: ErrorWrapper<SpikeErrorResponse<T>> get() = ErrorWrapper(this) suspend inline fun <reified T> SuccessWrapper<SpikeSuccessResponse<T>>.mapping(): T? = withContext(Dispatchers.Default) { [email protected]?.let { Gson().fromJsonOrNull<T>(it) } ?: run { null } } suspend inline fun <reified T> SuccessWrapper<SpikeSuccessResponse<T>>.mappingThrowable(): T = withContext(Dispatchers.Default) { [email protected]?.let { Gson().fromJson<T>(it) } ?: run { throw IOException("SpikeSuccessResponse result is null after call is null") } } suspend inline fun <reified T> ErrorWrapper<SpikeErrorResponse<T>>.mapping(): T? = withContext(Dispatchers.Default) { [email protected]?.let { Gson().fromJsonOrNull<T>(it) } ?: run { null } } suspend inline fun <reified T> ErrorWrapper<SpikeErrorResponse<T>>.mappingThrowable(): T = withContext(Dispatchers.Default) { [email protected]?.let { Gson().fromJson<T>(it) } ?: run { throw IOException("SpikeErrorResponse result is null after call is null") } }
mit
145f4b0f2ebcb762a8b4113dc1a0a0c3
33.916667
129
0.724179
3.789593
false
false
false
false
vicpinm/KPresenterAdapter
library/src/main/java/com/vicpin/kpresenteradapter/MyListAdapter.kt
1
5596
package com.vicpin.kpresenteradapter import androidx.recyclerview.widget.* /** * Created by Oesia on 17/01/2019. */ /* * 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. */ /** * [RecyclerView.Adapter] base class for presenting List data in a * [RecyclerView], including computing diffs between Lists on a background thread. * * * This class is a convenience wrapper around [AsyncListDiffer] that implements Adapter common * default behavior for item access and counting. * * * While using a LiveData&lt;List> is an easy way to provide data to the adapter, it isn't required * - you can use [.submitList] when new lists are available. * * * A complete usage pattern with Room would look like this: * <pre> * @Dao * interface UserDao { * @Query("SELECT * FROM user ORDER BY lastName ASC") * public abstract LiveData&lt;List&lt;User>> usersByLastName(); * } * * class MyViewModel extends ViewModel { * public final LiveData&lt;List&lt;User>> usersList; * public MyViewModel(UserDao userDao) { * usersList = userDao.usersByLastName(); * } * } * * class MyActivity extends AppCompatActivity { * @Override * public void onCreate(Bundle savedState) { * super.onCreate(savedState); * MyViewModel viewModel = ViewModelProviders.of(this).get(MyViewModel.class); * RecyclerView recyclerView = findViewById(R.id.user_list); * UserAdapter&lt;User> adapter = new UserAdapter(); * viewModel.usersList.observe(this, list -> adapter.submitList(list)); * recyclerView.setAdapter(adapter); * } * } * * class UserAdapter extends ListAdapter&lt;User, UserViewHolder> { * public UserAdapter() { * super(User.DIFF_CALLBACK); * } * @Override * public void onBindViewHolder(UserViewHolder holder, int position) { * holder.bindTo(getItem(position)); * } * public static final DiffUtil.ItemCallback&lt;User> DIFF_CALLBACK = * new DiffUtil.ItemCallback&lt;User>() { * @Override * public boolean areItemsTheSame( * @NonNull User oldUser, @NonNull User newUser) { * // User properties may have changed if reloaded from the DB, but ID is fixed * return oldUser.getId() == newUser.getId(); * } * @Override * public boolean areContentsTheSame( * @NonNull User oldUser, @NonNull User newUser) { * // NOTE: if you use equals, your object must properly override Object#equals() * // Incorrectly returning false here will result in too many animations. * return oldUser.equals(newUser); * } * } * }</pre> * * Advanced users that wish for more control over adapter behavior, or to provide a specific base * class should refer to [AsyncListDiffer], which provides custom mapping from diff events * to adapter positions. * * @param <T> Type of the Lists this Adapter will receive. * @param <VH> A class that extends ViewHolder that will be used by the adapter. </VH></T> */ abstract class MyListAdapter<T, VH : RecyclerView.ViewHolder> : RecyclerView.Adapter<VH> { private val mHelper: AsyncListDiffer<T> protected constructor(diffCallback: DiffUtil.ItemCallback<T>) { mHelper = AsyncListDiffer(MyListUpdateCallback(this), AsyncDifferConfig.Builder(diffCallback).build()) } protected constructor(config: AsyncDifferConfig<T>) { mHelper = AsyncListDiffer(MyListUpdateCallback(this), config) } /** * Submits a new list to be diffed, and displayed. * * * If a list is already being displayed, a diff will be computed on a background thread, which * will dispatch Adapter.notifyItem events on the main thread. * * @param list The new list to be displayed. */ fun submitList(list: List<T>?) { mHelper.submitList(list) } protected open fun getItem(position: Int): T { return mHelper.currentList[position] } override fun getItemCount(): Int { return mHelper.currentList.size } abstract fun getRecyclerView(): RecyclerView? abstract fun getHeadersCount(): Int inner class MyListUpdateCallback (private val mAdapter: RecyclerView.Adapter<*>) : ListUpdateCallback { /** {@inheritDoc} */ override fun onInserted(position: Int, count: Int) { mAdapter.notifyItemRangeInserted(position + getHeadersCount(), count) } /** {@inheritDoc} */ override fun onRemoved(position: Int, count: Int) { mAdapter.notifyItemRangeRemoved(position + getHeadersCount(), count) } /** {@inheritDoc} */ override fun onMoved(fromPosition: Int, toPosition: Int) { val recyclerViewState = getRecyclerView()?.layoutManager?.onSaveInstanceState() mAdapter.notifyItemMoved(fromPosition + getHeadersCount(), toPosition + getHeadersCount()) getRecyclerView()?.layoutManager?.onRestoreInstanceState(recyclerViewState) } /** {@inheritDoc} */ override fun onChanged(position: Int, count: Int, payload: Any?) { mAdapter.notifyItemRangeChanged(position + getHeadersCount(), count, payload) } } }
apache-2.0
2c16d05a8f3c72f77bed429fc69553ff
33.121951
102
0.696926
4.365055
false
false
false
false
Werb/PickPhotoSample
pickphotoview/src/main/java/com/werb/pickphotoview/widget/PreviewImage.kt
1
4000
package com.werb.pickphotoview.widget import android.content.Context import android.graphics.PorterDuff import android.net.Uri import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import android.widget.RelativeLayout import android.widget.Toast import com.bumptech.glide.Glide import com.werb.eventbus.EventBus import com.werb.pickphotoview.GlobalData import com.werb.pickphotoview.R import com.werb.pickphotoview.event.PickPreviewEvent import com.werb.pickphotoview.extensions.color import com.werb.pickphotoview.extensions.drawable import com.werb.pickphotoview.extensions.string import com.werb.pickphotoview.util.PickPhotoHelper import kotlinx.android.synthetic.main.pick_widget_view_preview.view.* /** Created by wanbo <[email protected]> on 2017/10/19. */ class PreviewImage : FrameLayout { private val images = PickPhotoHelper.selectImages constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) init { initView() } private fun initView() { val layout = LayoutInflater.from(context).inflate(R.layout.pick_widget_view_preview, this, false) as RelativeLayout addView(layout) } fun setImage(path: String, full: () -> Unit) { select(path) image.setOnClickListener { full() } image.isDrawingCacheEnabled = true selectLayout.setOnClickListener { if (images.contains(path)) { removeImage(path) } else { GlobalData.model?.let { if (it.allPhotoSize != 0) { val pickSize = images.size + it.hasPhotoSize if (pickSize >= it.allPhotoSize) { Toast.makeText(context, String.format(context.string(R.string.pick_photo_size_limit), it.allPhotoSize.toString()), Toast.LENGTH_SHORT).show() return@setOnClickListener } } val pickSize = images.size if (pickSize >= it.pickPhotoSize) { Toast.makeText(context, String.format(context.string(R.string.pick_photo_size_limit), it.pickPhotoSize.toString()), Toast.LENGTH_SHORT).show() return@setOnClickListener } addImage(path) } } } Glide.with(context) .load(Uri.parse("file://" + path)) .thumbnail(.1f) .into(image) } fun clear() { Glide.with(context).clear(image) } /** add image in list */ private fun addImage(path: String) { images.add(path) select(path) EventBus.post(PickPreviewEvent(path)) } /** remove image in list */ private fun removeImage(path: String) { images.remove(path) select(path) EventBus.post(PickPreviewEvent(path)) } private fun select(path: String) { if (images.contains(path)) { check.visibility = View.VISIBLE selectBack.visibility = View.VISIBLE val drawable = context.drawable(R.drawable.pick_svg_select_select) val back = context.drawable(R.drawable.pick_svg_select_back) GlobalData.model?.selectIconColor?.let { back.setColorFilter(context.color(it), PorterDuff.Mode.SRC_IN) } selectLayout.setBackgroundDrawable(drawable) selectBack.setBackgroundDrawable(back) } else { check.visibility = View.GONE selectBack.visibility = View.GONE val drawable = context.drawable(R.drawable.pick_svg_select_default) selectLayout.setBackgroundDrawable(drawable) } } }
apache-2.0
e5d96efe1542264b39e2d2d026899686
35.372727
169
0.62625
4.519774
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/auth/SignUpFragment.kt
1
11113
package org.fossasia.openevent.general.auth import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.Navigation.findNavController import kotlinx.android.synthetic.main.fragment_signup.view.textInputLayoutPassword import kotlinx.android.synthetic.main.fragment_signup.view.textInputLayoutConfirmPassword import kotlinx.android.synthetic.main.fragment_signup.view.firstNameText import kotlinx.android.synthetic.main.fragment_signup.view.signUpButton import kotlinx.android.synthetic.main.fragment_signup.view.lastNameText import kotlinx.android.synthetic.main.fragment_signup.view.passwordSignUp import kotlinx.android.synthetic.main.fragment_signup.view.confirmPasswords import kotlinx.android.synthetic.main.fragment_signup.view.emailSignUp import kotlinx.android.synthetic.main.fragment_signup.view.signupNestedScrollView import kotlinx.android.synthetic.main.fragment_signup.view.signUpText import kotlinx.android.synthetic.main.fragment_signup.view.signUpCheckbox import kotlinx.android.synthetic.main.fragment_signup.view.toolbar import org.fossasia.openevent.general.R import org.fossasia.openevent.general.utils.Utils.setToolbar import org.fossasia.openevent.general.utils.Utils.show import org.fossasia.openevent.general.utils.Utils.progressDialog import org.fossasia.openevent.general.utils.Utils.hideSoftKeyboard import org.fossasia.openevent.general.utils.Utils.showNoInternetDialog import org.fossasia.openevent.general.utils.extensions.nonNull import org.koin.androidx.viewmodel.ext.android.viewModel import android.text.SpannableStringBuilder import android.text.method.LinkMovementMethod import androidx.navigation.fragment.navArgs import org.fossasia.openevent.general.utils.StringUtils.getTermsAndPolicyText import org.fossasia.openevent.general.event.EVENT_DETAIL_FRAGMENT import org.fossasia.openevent.general.favorite.FAVORITE_FRAGMENT import org.fossasia.openevent.general.notification.NOTIFICATION_FRAGMENT import org.fossasia.openevent.general.order.ORDERS_FRAGMENT import org.fossasia.openevent.general.search.ORDER_COMPLETED_FRAGMENT import org.fossasia.openevent.general.search.SEARCH_RESULTS_FRAGMENT import org.fossasia.openevent.general.speakercall.SPEAKERS_CALL_FRAGMENT import org.fossasia.openevent.general.ticket.TICKETS_FRAGMENT import org.fossasia.openevent.general.utils.extensions.setSharedElementEnterTransition import org.jetbrains.anko.design.longSnackbar import org.jetbrains.anko.design.snackbar const val MINIMUM_PASSWORD_LENGTH = 8 class SignUpFragment : Fragment() { private val signUpViewModel by viewModel<SignUpViewModel>() private val safeArgs: SignUpFragmentArgs by navArgs() private lateinit var rootView: View override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { rootView = inflater.inflate(R.layout.fragment_signup, container, false) setSharedElementEnterTransition() val progressDialog = progressDialog(context) setToolbar(activity, show = false) rootView.toolbar.setNavigationOnClickListener { activity?.onBackPressed() } rootView.signUpText.text = getTermsAndPolicyText(requireContext(), resources) rootView.signUpText.movementMethod = LinkMovementMethod.getInstance() rootView.emailSignUp.text = SpannableStringBuilder(safeArgs.email) rootView.lastNameText.setOnEditorActionListener { _, actionId, _ -> when (actionId) { EditorInfo.IME_ACTION_DONE -> { if (validateRequiredFieldsEmpty()) { rootView.signUpButton.performClick() } hideSoftKeyboard(context, rootView) true } else -> false } } rootView.signUpButton.setOnClickListener { if (!rootView.signUpCheckbox.isChecked) { rootView.snackbar(R.string.accept_terms_and_conditions) return@setOnClickListener } else { val signUp = SignUp( email = rootView.emailSignUp.text.toString(), password = rootView.passwordSignUp.text.toString(), firstName = rootView.firstNameText.text.toString(), lastName = rootView.lastNameText.text.toString() ) signUpViewModel.signUp(signUp) } } signUpViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { progressDialog.show(it) }) signUpViewModel.showNoInternetDialog .nonNull() .observe(viewLifecycleOwner, Observer { showNoInternetDialog(context) }) signUpViewModel.error .nonNull() .observe(viewLifecycleOwner, Observer { rootView.signupNestedScrollView.longSnackbar(it) }) signUpViewModel.loggedIn .nonNull() .observe(viewLifecycleOwner, Observer { redirectToMain() }) rootView.emailSignUp.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(text: Editable?) { if (text.toString() != safeArgs.email) findNavController(rootView).navigate(SignUpFragmentDirections .actionSignupToAuthPop(redirectedFrom = safeArgs.redirectedFrom, email = text.toString())) } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*Implement here*/ } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*Do Nothing*/ } }) rootView.confirmPasswords.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) { /* to make PasswordToggle visible again, if made invisible after empty field error */ if (!rootView.textInputLayoutConfirmPassword.isEndIconVisible) { rootView.textInputLayoutConfirmPassword.isEndIconVisible = true } if (rootView.confirmPasswords.text.toString() == rootView.passwordSignUp.text.toString()) { rootView.textInputLayoutConfirmPassword.error = null rootView.textInputLayoutConfirmPassword.isErrorEnabled = false } else { rootView.textInputLayoutConfirmPassword.error = getString(R.string.invalid_confirm_password_message) } } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*Implement here*/ } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { rootView.signUpButton.isEnabled = checkPassword() } }) rootView.passwordSignUp.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) { /* to make PasswordToggle visible again, if made invisible after empty field error */ if (!rootView.textInputLayoutPassword.isEndIconVisible) { rootView.textInputLayoutPassword.isEndIconVisible = true } if (rootView.passwordSignUp.text.toString().length >= MINIMUM_PASSWORD_LENGTH) { rootView.textInputLayoutPassword.error = null rootView.textInputLayoutPassword.isErrorEnabled = false } else { rootView.textInputLayoutPassword.error = getString(R.string.invalid_password_message) } if (rootView.confirmPasswords.text.toString() == rootView.passwordSignUp.text.toString()) { rootView.textInputLayoutConfirmPassword.error = null rootView.textInputLayoutConfirmPassword.isErrorEnabled = false } else { rootView.textInputLayoutConfirmPassword.error = getString(R.string.invalid_confirm_password_message) } } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*Implement here*/ } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { rootView.signUpButton.isEnabled = checkPassword() } }) return rootView } private fun redirectToMain() { val destinationId = when (safeArgs.redirectedFrom) { PROFILE_FRAGMENT -> R.id.profileFragment EVENT_DETAIL_FRAGMENT -> R.id.eventDetailsFragment ORDERS_FRAGMENT -> R.id.orderUnderUserFragment TICKETS_FRAGMENT -> R.id.ticketsFragment NOTIFICATION_FRAGMENT -> R.id.notificationFragment SPEAKERS_CALL_FRAGMENT -> R.id.speakersCallFragment FAVORITE_FRAGMENT -> R.id.favoriteFragment SEARCH_RESULTS_FRAGMENT -> R.id.searchResultsFragment ORDER_COMPLETED_FRAGMENT -> R.id.orderCompletedFragment else -> R.id.eventsFragment } if (destinationId == R.id.eventsFragment) { findNavController(rootView).navigate(SignUpFragmentDirections.actionSignUpToEventsPop()) } else { findNavController(rootView).popBackStack(destinationId, false) } rootView.snackbar(R.string.logged_in_automatically) } private fun checkPassword() = rootView.passwordSignUp.text.toString().isNotEmpty() && rootView.passwordSignUp.text.toString().length >= MINIMUM_PASSWORD_LENGTH && rootView.passwordSignUp.text.toString() == rootView.confirmPasswords.text.toString() private fun validateRequiredFieldsEmpty(): Boolean { var status = true if (rootView.emailSignUp.text.isNullOrEmpty()) { rootView.emailSignUp.error = getString(R.string.empty_email_message) status = false } if (rootView.passwordSignUp.text.isNullOrEmpty()) { rootView.passwordSignUp.error = getString(R.string.empty_password_message) // make PasswordToggle invisible rootView.textInputLayoutPassword.isEndIconVisible = false status = false } if (rootView.confirmPasswords.text.isNullOrEmpty()) { rootView.confirmPasswords.error = getString(R.string.empty_confirm_password_message) // make PasswordToggle invisible rootView.textInputLayoutConfirmPassword.isEndIconVisible = false status = false } return status } }
apache-2.0
5cea6e2c833f2c901beb6791e19fa0ce
44.174797
120
0.669396
5.154453
false
false
false
false
marsdevapps/ercot-simple-client
src/main/kotlin/com/marsdev/samples/ercot/simple/ui/Styles.kt
1
892
package com.marsdev.samples.ercot.simple.ui import javafx.scene.paint.Color import tornadofx.* class Styles : Stylesheet() { companion object { val B_200 = c("#90CAF9") val swatch_100 = c("#BBDEFB") val swatch_200 = c("#90CAF9") val swatch_300 = c("#64BEF6") val swatch_400 = c("#42A5F5") val swatch_500 = c("#2196F3") val borderPane by cssclass() } init { root { focusColor = Color.TRANSPARENT faintFocusColor = Color.TRANSPARENT backgroundColor += Color.BLACK unsafe("-fx-accent", raw(B_200.css)) unsafe("-fx-dark-text-color", raw("white")) } borderPane { // focusColor = Color.TRANSPARENT // faintFocusColor = Color.TRANSPARENT // backgroundColor += Color.TRANSPARENT } } }
gpl-3.0
5a6fa7b0e0c633cccaf7201ad3a55a2b
24.514286
56
0.547085
3.912281
false
false
false
false
Bambooin/trime
app/src/main/java/com/osfans/trime/ime/keyboard/KeyboardSwitcher.kt
1
4669
package com.osfans.trime.ime.keyboard import android.content.res.Configuration import com.osfans.trime.data.AppPrefs import com.osfans.trime.data.Config import com.osfans.trime.ime.core.Trime import com.osfans.trime.util.appContext import timber.log.Timber /** Manages [Keyboard]s and their status. **/ class KeyboardSwitcher { var currentId: Int = -1 var lastId: Int = 0 var lastLockId: Int = 0 private var currentDisplayWidth: Int = 0 lateinit var keyboards: Array<Keyboard> lateinit var keyboardNames: List<String> /** To get current keyboard instance. **/ val currentKeyboard: Keyboard get() = keyboards[currentId] /** To get [currentKeyboard]'s ascii mode. **/ val asciiMode: Boolean get() = currentKeyboard.asciiMode init { newOrReset() } fun newOrReset() { val methodName = "\t<TrimeInit>\t" + Thread.currentThread().stackTrace[2].methodName + "\t" Timber.d(methodName) val ims = Trime.getService() Timber.d(methodName + "getConfig") keyboardNames = Config.get(ims).keyboardNames Timber.d(methodName + "land") val land = ( ims.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE ) Timber.d(methodName + "getConfig") Config.get(ims).getKeyboardPadding(land) Timber.d("update KeyboardPadding: KeyboardSwitcher.init") Timber.d(methodName + "getKeyboards") keyboards = Array(keyboardNames.size) { i -> Keyboard(ims, keyboardNames[i]) } Timber.d(methodName + "setKeyboard") setKeyboard(0) Timber.d(methodName + "finish") } /** * Switch to a certain keyboard by given [name]. */ fun switchToKeyboard(name: String?) { var i = if (currentId.isValidId()) currentId else 0 i = when { name.isNullOrEmpty() -> if (keyboards[i].isLock) i else lastLockId name.contentEquals(".default") -> 0 name.contentEquals(".prior") -> currentId - 1 name.contentEquals(".next") -> currentId + 1 name.contentEquals(".last") -> lastId name.contentEquals(".last_lock") -> lastLockId name.contentEquals(".ascii") -> { val asciiKeyboard = keyboards[i].asciiKeyboard if (asciiKeyboard == null || asciiKeyboard.isEmpty()) { i } else { keyboardNames.indexOf(asciiKeyboard) } } else -> keyboardNames.indexOf(name) } setKeyboard(i) } /** * Switch to a certain keyboard by given [name]. */ fun startKeyboard(name: String?) { var i = if (currentId.isValidId()) currentId else 0 i = when { name.isNullOrEmpty() -> if (keyboards[i].isLock) i else lastLockId name.contentEquals(".default") -> 0 name.contentEquals(".prior") -> currentId - 1 name.contentEquals(".next") -> currentId + 1 name.contentEquals(".last") -> lastId name.contentEquals(".last_lock") -> lastLockId name.contentEquals(".ascii") -> { val asciiKeyboard = keyboards[i].asciiKeyboard if (asciiKeyboard == null || asciiKeyboard.isEmpty()) { i } else { keyboardNames.indexOf(asciiKeyboard) } } else -> keyboardNames.indexOf(name) } if (i == 0 && keyboardNames.contains("mini")) { if (AppPrefs.defaultInstance().looks.useMiniKeyboard) { val realkeyboard = appContext.getResources().getConfiguration().keyboard if (realkeyboard != Configuration.KEYBOARD_NOKEYS) { Timber.i("onStartInputView() configuration.keyboard=" + realkeyboard + ", keyboardType=" + i) i = keyboardNames.indexOf("mini") } } } setKeyboard(i) } /** * Change current display width when e.g. rotate the screen. */ fun resize(displayWidth: Int) { if (currentId >= 0 && (displayWidth == currentDisplayWidth)) return currentDisplayWidth = displayWidth newOrReset() } private fun setKeyboard(id: Int) { Timber.d("\t<TrimeInit>\tsetKeyboard()\t" + currentId + "->" + id) lastId = currentId if (lastId.isValidId() && keyboards[lastId].isLock) { lastLockId = lastId } currentId = if (id.isValidId()) id else 0 } public fun getCurrentKeyboardName(): String { return keyboardNames.get(currentId) } private fun Int.isValidId() = this in keyboards.indices }
gpl-3.0
c1c1abacb8a25fc8c5c5f3641774a682
34.915385
121
0.596916
4.396422
false
true
false
false
EMResearch/EvoMaster
core/src/test/kotlin/org/evomaster/core/search/structuralelement/gene/RegexGeneStructureTest.kt
1
3224
package org.evomaster.core.search.structuralelement.gene import org.evomaster.core.parser.RegexHandler import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.regex.* import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class AnyCharacterRxGeneStructureTest : GeneStructuralElementBaseTest() { override fun getCopyFromTemplate(): Gene = AnyCharacterRxGene().apply { value = 'b' } override fun assertCopyFrom(base: Gene) { assertTrue(base is AnyCharacterRxGene) assertEquals('b', (base as AnyCharacterRxGene).value) } override fun getStructuralElement(): AnyCharacterRxGene = AnyCharacterRxGene() override fun getExpectedChildrenSize(): Int = 0 } class CharacterClassEscapeRxGeneStructureTest : GeneStructuralElementBaseTest() { override fun getCopyFromTemplate(): Gene = CharacterClassEscapeRxGene("s").apply { value="bar" } override fun assertCopyFrom(base: Gene) { assertTrue(base is CharacterClassEscapeRxGene) // TODO shall we check the type in copyFrom assertEquals("d", (base as CharacterClassEscapeRxGene).type) assertEquals("bar", base.value) } override fun getStructuralElement(): CharacterClassEscapeRxGene = CharacterClassEscapeRxGene("d").apply { value="foo" } override fun getExpectedChildrenSize(): Int = 0 } class CharacterRangeRxGeneStructureTest : GeneStructuralElementBaseTest() { override fun getCopyFromTemplate(): Gene = CharacterRangeRxGene(false, listOf(Pair('0','9'))).apply { value='2'} override fun assertCopyFrom(base: Gene) { assertTrue(base is CharacterRangeRxGene) //TODO shall we check the range? assertEquals('2', (base as CharacterRangeRxGene).value) } override fun getStructuralElement(): CharacterRangeRxGene = CharacterRangeRxGene(false, listOf(Pair('a','z'))).apply { value= 'w' } override fun getExpectedChildrenSize(): Int = 0 } class RegexGeneStructureTest : GeneStructuralElementBaseTest() { override fun getCopyFromTemplate(): Gene = RegexHandler.createGeneForEcma262("^ba{2}\\d{2}$") // due to PatternCharacterBlock override fun throwExceptionInCopyFromTest(): Boolean = true override fun assertCopyFrom(base: Gene) { } override fun getStructuralElement(): RegexGene = RegexHandler.createGeneForEcma262("^fo{2}\\d{2}$") override fun getExpectedChildrenSize(): Int = 1 @Test fun testInitRegexGene(){ val root = getStructuralElementAndIdentifyAsRoot() as RegexGene assertEquals(root, root.getRoot()) root.disjunctions.apply { assertEquals(1, disjunctions.size) disjunctions.first().apply { assertTrue(terms[0] is PatternCharacterBlockGene) //f assertEquals(0, terms[0].getViewOfChildren().size) assertTrue(terms[1] is QuantifierRxGene) //o assertEquals(2, terms[1].getViewOfChildren().size) assertTrue(terms[2] is QuantifierRxGene) // \d assertEquals(0, terms[2].getViewOfChildren().size) // no atom } } } }
lgpl-3.0
91465c97fefb1e94342e76715a3c2d67
36.488372
135
0.706576
4.446897
false
true
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/shows/search/EpisodeSearchFragment.kt
1
3332
package com.battlelancer.seriesguide.shows.search import android.app.SearchManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.GridView import androidx.fragment.app.viewModels import com.battlelancer.seriesguide.databinding.FragmentSearchBinding import com.battlelancer.seriesguide.shows.episodes.EpisodesActivity import com.battlelancer.seriesguide.util.TabClickEvent import com.battlelancer.seriesguide.util.Utils import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode /** * Displays episode search results. */ class EpisodeSearchFragment : BaseSearchFragment() { private var binding: FragmentSearchBinding? = null private val model by viewModels<EpisodeSearchViewModel>() private lateinit var adapter: EpisodeSearchAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return FragmentSearchBinding.inflate(inflater, container, false) .also { binding = it } .root } override val emptyView: View get() = binding!!.textViewSearchEmpty override val gridView: GridView get() = binding!!.gridViewSearch override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // list items do not have right hand-side buttons, list may be long: enable fast scrolling gridView.apply { isFastScrollAlwaysVisible = false isFastScrollEnabled = true } adapter = EpisodeSearchAdapter(requireContext(), onItemClickListener).also { gridView.adapter = it } model.episodes.observe(viewLifecycleOwner) { episodes -> adapter.setData(episodes) updateEmptyState( episodes.isEmpty(), !model.searchData.value?.searchTerm.isNullOrEmpty() ) } // load for given query (if just created) val args = initialSearchArgs if (args != null) { updateQuery(args) } } override fun onDestroyView() { super.onDestroyView() binding = null } @Subscribe(threadMode = ThreadMode.MAIN) fun onEventMainThread(event: SearchActivityImpl.SearchQueryEvent) { updateQuery(event.args) } private fun updateQuery(args: Bundle) { model.searchData.value = EpisodeSearchViewModel.SearchData( args.getString(SearchManager.QUERY), args.getBundle(SearchManager.APP_DATA)?.getString(ARG_SHOW_TITLE) ) } @Subscribe(threadMode = ThreadMode.MAIN) fun onEventTabClick(event: TabClickEvent) { if (event.position == SearchActivityImpl.TAB_POSITION_EPISODES) { gridView.smoothScrollToPosition(0) } } private val onItemClickListener = object : EpisodeSearchAdapter.OnItemClickListener { override fun onItemClick(anchor: View, episodeId: Long) { EpisodesActivity.intentEpisode(episodeId, requireContext()) .also { Utils.startActivityWithAnimation(activity, it, anchor) } } } companion object { const val ARG_SHOW_TITLE = "title" } }
apache-2.0
e2c172c181b26462cd38bdde3721d87f
32.32
98
0.683974
5.094801
false
false
false
false
AlmasB/FXGL
fxgl-core/src/main/kotlin/com/almasb/fxgl/core/collection/PropertyMap.kt
1
9863
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.core.collection import javafx.beans.property.* import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import java.util.* /** * Maps property (variable) names to observable JavaFX properties. * * Value types are one of * SimpleIntegerProperty, * SimpleDoubleProperty, * SimpleBooleanProperty, * SimpleStringProperty, * SimpleObjectProperty. * * Null values are not allowed. * * @author Almas Baimagambetov ([email protected]) */ class PropertyMap { companion object { @JvmStatic fun fromStringMap(map: Map<String, String>): PropertyMap { return from(map.mapValues { toValue(it.value) }) } /** * Maps [s] to its actual data type, which is one of * int, double, boolean or string. */ private fun toValue(s: String): Any { if (s == "true") return true if (s == "false") return false return s.toIntOrNull() ?: s.toDoubleOrNull() ?: s } @JvmStatic fun from(map: Map<String, Any>): PropertyMap { val pMap = PropertyMap() map.forEach { (key, value) -> pMap.setValue(key, value) } return pMap } } private val properties = hashMapOf<String, Any>() private val mapChangeListeners = arrayListOf<PropertyMapChangeListener>() fun keys(): Set<String> = properties.keys /** * @return true if a property with [propertyName] exists */ fun exists(propertyName: String) = properties.containsKey(propertyName) fun <T : Any> getValueOptional(propertyName: String): Optional<T> { try { return Optional.ofNullable(getValue(propertyName)) } catch (e: Exception) { return Optional.empty() } } @Suppress("UNCHECKED_CAST") fun <T> getValue(propertyName: String): T { return (get(propertyName) as ObservableValue<*>).value as T } fun getValueObservable(propertyName: String): Any { return get(propertyName) } /** * Set a new [value] to an existing var [propertyName] or creates new var. * The value cannot be null. */ fun setValue(propertyName: String, value: Any) { if (exists(propertyName)) { when (value) { is Boolean -> booleanProperty(propertyName).value = value is Int -> intProperty(propertyName).value = value is Double -> doubleProperty(propertyName).value = value is String -> stringProperty(propertyName).value = value else -> { val prop = objectProperty<Any>(propertyName) as UpdatableObjectProperty<Any> val oldValue = prop.value prop.value = value if (oldValue === value) { // object listener is not fired if the _same_ object is passed in, so we fire it manually prop.forceUpdateListeners(oldValue, value) } } } } else { // new property val property = when (value) { is Boolean -> SimpleBooleanProperty(value) is Int -> SimpleIntegerProperty(value) is Double-> SimpleDoubleProperty(value) is String -> SimpleStringProperty(value) else -> UpdatableObjectProperty(value) } properties.put(propertyName, property) // let listeners know we added a new prop mapChangeListeners.forEach { it.onUpdated(propertyName, value) } // add an internal listener for any changes in this new property addListener(propertyName, PropertyChangeListener<Any> { _, now -> mapChangeListeners.forEach { it.onUpdated(propertyName, now) } }) } } fun remove(propertyName: String) { getValueOptional<Any>(propertyName).ifPresent { value -> mapChangeListeners.forEach { it.onRemoved(propertyName, value) } } properties.remove(propertyName) } fun increment(propertyName: String, value: Int) { intProperty(propertyName).value += value } fun increment(propertyName: String, value: Double) { doubleProperty(propertyName).value += value } fun getBoolean(propertyName: String) = booleanProperty(propertyName).value fun getInt(propertyName: String) = intProperty(propertyName).value fun getDouble(propertyName: String) = doubleProperty(propertyName).value fun getString(propertyName: String) = stringProperty(propertyName).value fun <T> getObject(propertyName: String) = objectProperty<T>(propertyName).value fun booleanProperty(propertyName: String) = get(propertyName) as BooleanProperty fun intProperty(propertyName: String) = get(propertyName) as IntegerProperty fun doubleProperty(propertyName: String) = get(propertyName) as DoubleProperty fun stringProperty(propertyName: String) = get(propertyName) as StringProperty @Suppress("UNCHECKED_CAST") fun <T> objectProperty(propertyName: String) = get(propertyName) as ObjectProperty<T> /** * We use ListenerKey to capture both property name and property listener. * We can then use property name to find all remaining JavaFX listeners * in case they weren't explicitly removed. */ private val listeners = hashMapOf<ListenerKey, ChangeListener<*>>() @Suppress("UNCHECKED_CAST") fun <T> addListener(propertyName: String, listener: PropertyChangeListener<T>) { val internalListener = ChangeListener<T> { _, prev, now -> listener.onChange(prev, now) } val key = ListenerKey(propertyName, listener) listeners[key] = internalListener (get(propertyName) as ObservableValue<T>).addListener(internalListener) } @Suppress("UNCHECKED_CAST") fun <T> removeListener(propertyName: String, listener: PropertyChangeListener<T>) { val key = ListenerKey(propertyName, listener) (get(propertyName) as ObservableValue<T>).removeListener(listeners[key] as ChangeListener<in T>) listeners.remove(key) } fun addListener(mapChangeListener: PropertyMapChangeListener) { mapChangeListeners += mapChangeListener } fun removeListener(mapChangeListener: PropertyMapChangeListener) { mapChangeListeners -= mapChangeListener } @Suppress("UNCHECKED_CAST") fun clear() { listeners.forEach { (key, listener) -> // clean up all non-removed JavaFX listeners (get(key.propertyName) as ObservableValue<Any>).removeListener(listener as ChangeListener<Any>) } listeners.clear() mapChangeListeners.clear() properties.clear() } /** * Note: the new map will contain new references for values, but the value wrapped by SimpleObjectProperty * will be the same. * * @return a deep copy of this property map */ fun copy(): PropertyMap { val map = PropertyMap() keys().forEach { name -> map.setValue(name, getValue(name)) } return map } fun toMap(): Map<String, Any> { return keys().map { it to getValue<Any>(it) }.toMap() } /** * Provides functionality of Map.forEach for PropertyMap. * * @param action - lambda or method reference with signature (String, Any), * where Any is the unwrapped (e.g. String, int, etc., not Observable) type */ fun forEach(action: (String, Any) -> Unit) { properties.forEach { (key, _) -> action(key, getValue(key)) } } /** * Provides functionality of Map.forEach for PropertyMap. * * @param action - lambda or method reference with signature (String, Any), * where Any is an Observable type */ fun forEachObservable(action: (String, Any) -> Unit) { properties.forEach(action) } fun addAll(other: PropertyMap) { other.forEach { key, value -> setValue(key, value) } } fun toStringMap(): Map<String, String> { return keys().map { it to getValue<Any>(it).toString() }.toMap() } private fun get(propertyName: String) = properties.get(propertyName) ?: throw IllegalArgumentException("Property $propertyName does not exist") private class ListenerKey(val propertyName: String, val propertyListener: PropertyChangeListener<*>) { override fun hashCode(): Int { return Objects.hash(propertyName, propertyListener) } override fun equals(other: Any?): Boolean { // this assumption is valid since this is a private class that is used only // inside the listeners map above val o = other as ListenerKey return propertyName == o.propertyName && propertyListener === o.propertyListener } } override fun toString(): String { return properties.toMap().toString() } } class UpdatableObjectProperty<T>(initialValue: T) : SimpleObjectProperty<T>(initialValue) { private val listeners = arrayListOf<ChangeListener<in T>>() override fun addListener(listener: ChangeListener<in T>) { super.addListener(listener) listeners.add(listener) } override fun removeListener(listener: ChangeListener<in T>?) { super.removeListener(listener) listeners.remove(listener) } fun forceUpdateListeners(oldValue: T, newValue: T) { listeners.forEach { it.changed(this, oldValue, newValue) } } }
mit
5b1b88a71bf271cd978b7d233da94ee2
30.819355
113
0.628004
4.851451
false
false
false
false
deltaDNA/android-smartads-sdk
library-debug/src/main/java/com/deltadna/android/sdk/ads/debug/DebugReceiver.kt
1
5552
/* * Copyright (c) 2017 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deltadna.android.sdk.ads.debug import android.annotation.TargetApi import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build import android.support.v4.app.NotificationCompat import com.deltadna.android.sdk.ads.bindings.Actions.* class DebugReceiver : BroadcastReceiver() { private var interstitial = "" private var rewarded = "" override fun onReceive(context: Context, intent: Intent) { fun Int.load() = context.getString(this) fun Int.load(vararg args: Any) = context.getString(this, *args) val action = intent.action if (!action.isNullOrEmpty() && !hidden) { val notifications = context.getSystemService( Context.NOTIFICATION_SERVICE) as NotificationManager if (action == DELETE_ACTION) { notifications.cancel(TAG, ID) hidden = true } else { val notification = NotificationCompat.Builder(context, CHANNEL) .setSmallIcon(R.drawable.ddna_ic_stat_logo) .setContentTitle(R.string.ddna_title.load()) .setDeleteIntent(PendingIntent.getBroadcast( context, DELETE_RC, deleteIntent(context), PendingIntent.FLAG_UPDATE_CURRENT)) .setDefaults(0) .setSound(null) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) notification.setChannelId(channel(context).id) val agent = intent.getSerializableExtra(AGENT) as Agent? val text = when (action) { SESSION_UPDATED -> R.string.ddna_session_updated.load() FAILED_TO_REGISTER -> intent.getStringExtra(REASON) LOADED -> R.string.ddna_loaded.load( agent!!.name.toLowerCase(), intent.getStringExtra(NETWORK)) SHOWING -> R.string.ddna_showing.load( agent!!.name.toLowerCase(), intent.getStringExtra(NETWORK)) SHOWN -> R.string.ddna_shown.load( agent!!.name.toLowerCase(), intent.getStringExtra(NETWORK)) SHOWN_AND_LOADED -> R.string.ddna_shown_and_loaded.load( agent!!.name.toLowerCase(), intent.getStringExtra(NETWORK_SHOWN), intent.getStringExtra(NETWORK_LOADED)) else -> throw IllegalStateException("Unknown $action") } if (agent == null) { notification.setContentText(text) } else { when (agent) { Agent.INTERSTITIAL -> interstitial = text Agent.REWARDED -> rewarded = text } notification.setStyle(NotificationCompat.BigTextStyle() .bigText(when { rewarded.isEmpty() -> interstitial interstitial.isEmpty() -> rewarded else -> "$interstitial\n$rewarded" })) } notifications.notify( TAG, ID, notification.build()) } } } @TargetApi(Build.VERSION_CODES.O) private fun channel(context: Context) = NotificationChannel( CHANNEL, context.getString(R.string.ddna_channel_name), NotificationManager.IMPORTANCE_MIN).apply { (context.getSystemService( Context.NOTIFICATION_SERVICE) as NotificationManager) .createNotificationChannel(this)} private fun deleteIntent(context: Context) = Intent() .setClass(context, DebugReceiver::class.java) .setAction(DELETE_ACTION) private companion object { const val TAG = "com.deltadna.android.sdk.ads.debug" const val ID = 1 const val CHANNEL = "com.deltadna.debug" const val DELETE_ACTION = "com.deltadna.android.sdk.ads.debug.ACTION_DELETE" const val DELETE_RC = 1 var hidden = false } }
apache-2.0
e9ba0815dcb3ece57def19ebacd999f1
39.823529
84
0.527918
5.563126
false
false
false
false
industrial-data-space/trusted-connector
ids-api/src/main/java/de/fhg/aisec/ids/api/router/RouteComponent.kt
1
1329
/*- * ========================LICENSE_START================================= * ids-api * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.api.router /** * Representation of a "route component", i.e. a protocol adapter to attach route endpoints to * external services. * * @author Julian Schuette ([email protected]) */ class RouteComponent { var bundle: String? = null private set var description: String? = null private set constructor() { /* Bean std c'tor */ } constructor(bundleName: String?, description: String?) { bundle = bundleName this.description = description } }
apache-2.0
1995aa6a9f191d602b54697321017288
30.642857
94
0.626035
4.43
false
false
false
false
AsynkronIT/protoactor-kotlin
proto-remote/src/main/kotlin/actor/proto/remote/EndpointWatcher.kt
1
1755
package actor.proto.remote import actor.proto.Actor import actor.proto.Behavior import actor.proto.Context import actor.proto.PID import actor.proto.ProcessRegistry import actor.proto.Terminated import actor.proto.Unwatch import actor.proto.Watch import actor.proto.sendSystemMessage class EndpointWatcher(address: String) : Actor { private val behavior: Behavior = Behavior({ connectedAsync(it) }) private val watched: HashMap<String, PID> = HashMap() private var _address: String = address suspend override fun Context.receive(msg: Any) = behavior.receive(this,msg) private suspend fun connectedAsync(msg: Any) { when (msg) { is RemoteTerminate -> { watched.remove(msg.watcher.id) sendSystemMessage(msg.watcher,Terminated(msg.watchee, true)) } is EndpointTerminatedEvent -> { for ((id, pid) in watched) { val watcher: PID = PID(ProcessRegistry.address, id) sendSystemMessage(watcher,Terminated(pid, true)) } behavior.become({ terminatedAsync() }) } is RemoteUnwatch -> { watched.remove(msg.watcher.id) Remote.sendMessage(msg.watchee, Unwatch(msg.watcher), -1) } is RemoteWatch -> { watched.put(msg.watcher.id, msg.watchee) Remote.sendMessage(msg.watchee, Watch(msg.watcher), -1) } } } private suspend fun Context.terminatedAsync() { val msg = message when (msg) { is RemoteWatch -> sendSystemMessage(msg.watcher,Terminated(msg.watchee, true)) else -> { } } } }
apache-2.0
68c935f0ffbb9a02a72cfb9dbaf45b5c
33.411765
90
0.59886
4.376559
false
false
false
false
GoogleCloudPlatform/kotlin-samples
run/grpc-hello-world-streaming/src/main/kotlin/io/grpc/examples/helloworld/HelloWorldServer.kt
1
1914
/* * Copyright 2020 gRPC 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 io.grpc.examples.helloworld import io.grpc.Server import io.grpc.ServerBuilder import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class HelloWorldServer(val port: Int) { val server: Server = ServerBuilder .forPort(port) .addService(HelloWorldService()) .build() fun start() { server.start() println("Server started, listening on $port") Runtime.getRuntime().addShutdownHook( Thread { println("*** shutting down gRPC server since JVM is shutting down") stop() println("*** server shut down") } ) } private fun stop() { server.shutdown() } fun blockUntilShutdown() { server.awaitTermination() } private class HelloWorldService : GreeterGrpcKt.GreeterCoroutineImplBase() { override fun sayHelloStream(request: HelloRequest): Flow<HelloReply> = flow { while (true) { delay(1000) emit(helloReply { message = "hello, ${request.name}" }) } } } } fun main() { val port = System.getenv("PORT")?.toInt() ?: 50051 val server = HelloWorldServer(port) server.start() server.blockUntilShutdown() }
apache-2.0
7a30ef617a4c4dc4806b66b7aee4d8a2
28
85
0.643678
4.451163
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/administration/RoleIdCommand.kt
1
2860
package net.perfectdreams.loritta.morenitta.commands.vanilla.administration import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.dv8tion.jda.api.Permission import net.perfectdreams.loritta.morenitta.messages.LorittaReply import java.util.* import net.perfectdreams.loritta.morenitta.LorittaBot class RoleIdCommand(loritta: LorittaBot) : AbstractCommand(loritta, "roleid", listOf("cargoid", "iddocargo"), net.perfectdreams.loritta.common.commands.CommandCategory.MODERATION) { override fun getDescriptionKey() = LocaleKeyData("commands.command.roleid.description") // TODO: Fix getUsage override fun getExamples(): List<String> { return Arrays.asList("Moderadores") } override fun getDiscordPermissions(): List<Permission> { return listOf(Permission.MANAGE_ROLES) } override fun canUseInPrivateChannel(): Boolean { return false } override suspend fun run(context: CommandContext,locale: BaseLocale) { if (context.rawArgs.isNotEmpty()) { var argument = context.rawArgs.joinToString(" ") val mentionedRoles = context.message.mentions.roles // Se o usuário mencionar o cargo, vamos mostrar o ID dos cargos mencionados val list = mutableListOf<LorittaReply>() if (mentionedRoles.isNotEmpty()) { list.add( LorittaReply( message = locale["commands.command.roleid.identifiers", argument], prefix = "\uD83D\uDCBC" ) ) mentionedRoles.mapTo(list) { LorittaReply( message = "*${it.name}* - `${it.id}`", mentionUser = false ) } } else { val roles = context.guild.roles.filter { it.name.contains(argument, true) } list.add( LorittaReply( message = locale["commands.command.roleid.rolesThatContains", argument], prefix = "\uD83D\uDCBC" ) ) if (roles.isEmpty()) { list.add( LorittaReply( message = "*${locale["commands.command.roleid.emptyRoles"]}*", mentionUser = false, prefix = "\uD83D\uDE22" ) ) } else { roles.mapTo(list) { LorittaReply( message = "*${it.name}* - `${it.id}`", mentionUser = false ) } } } context.reply(*list.toTypedArray()) } else { context.explain() } } }
agpl-3.0
8ca632fbabf209ad482a27912c9770d8
32.647059
181
0.589017
4.516588
false
false
false
false
LorittaBot/Loritta
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/EmojiFightMatchmakingResults.kt
1
429
package net.perfectdreams.loritta.cinnamon.pudding.tables import org.jetbrains.exposed.dao.id.LongIdTable object EmojiFightMatchmakingResults : LongIdTable() { val winner = reference("winner", EmojiFightParticipants).index() val entryPrice = long("entry_price") val entryPriceAfterTax = long("entry_price_after_tax") val tax = long("tax").nullable() val taxPercentage = double("tax_percentage").nullable() }
agpl-3.0
c4790cd8acc568fdbcf3547e1ab926fc
38.090909
68
0.750583
4.125
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/util/extension/ViewExtensions.kt
1
4192
@file:Suppress("NOTHING_TO_INLINE") package me.proxer.app.util.extension import android.animation.LayoutTransition import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.graphics.drawable.StateListDrawable import android.view.ViewGroup import android.widget.ImageView import androidx.annotation.AttrRes import androidx.appcompat.widget.AppCompatTextView import androidx.core.text.PrecomputedTextCompat import androidx.core.view.postDelayed import androidx.core.widget.TextViewCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.IIcon import com.mikepenz.iconics.utils.colorInt import com.mikepenz.iconics.utils.paddingDp import com.mikepenz.iconics.utils.sizeDp import me.proxer.app.R import timber.log.Timber inline var AppCompatTextView.fastText: CharSequence get() = text set(value) { val textMetrics = TextViewCompat.getTextMetricsParams(this) setTextFuture(PrecomputedTextCompat.getTextFuture(value, textMetrics, null)) } inline fun ImageView.setIconicsImage( icon: IIcon, sizeDp: Int, paddingDp: Int = sizeDp / 4, @AttrRes colorAttr: Int = R.attr.colorIcon ) { setImageDrawable( IconicsDrawable(context, icon).apply { this.colorInt = context.resolveColor(colorAttr) this.paddingDp = paddingDp this.sizeDp = sizeDp } ) } inline fun ViewGroup.enableLayoutAnimationsSafely() { this.layoutTransition = LayoutTransition().apply { setAnimateParentHierarchy(false) } } fun RecyclerView.isAtCompleteTop() = when (val layoutManager = this.safeLayoutManager) { is StaggeredGridLayoutManager -> layoutManager.findFirstCompletelyVisibleItemPositions(null).contains(0) is LinearLayoutManager -> layoutManager.findFirstCompletelyVisibleItemPosition() == 0 else -> false } fun RecyclerView.isAtTop() = when (val layoutManager = this.safeLayoutManager) { is StaggeredGridLayoutManager -> layoutManager.findFirstVisibleItemPositions(null).contains(0) is LinearLayoutManager -> layoutManager.findFirstVisibleItemPosition() == 0 else -> false } fun RecyclerView.scrollToTop() = when (val layoutManager = safeLayoutManager) { is StaggeredGridLayoutManager -> layoutManager.scrollToPositionWithOffset(0, 0) is LinearLayoutManager -> layoutManager.scrollToPositionWithOffset(0, 0) else -> error("Unsupported layout manager: ${layoutManager.javaClass.name}") } fun RecyclerView.doAfterAnimations(action: () -> Unit) { postDelayed(10) { if (isAnimating) { val safeItemAnimator = requireNotNull(itemAnimator) { "RecyclerView is reporting isAnimating as true, but no itemAnimator is set" } safeItemAnimator.isRunning { doAfterAnimations(action) } } else { action() } } } fun RecyclerView.enableFastScroll() { val thumbColor = context.resolveColor(R.attr.colorFastscrollThumb) val trackColor = context.resolveColor(R.attr.colorFastscrollTrack) val pressedColor = context.resolveColor(R.attr.colorSecondary) val thumbDrawableSelector = StateListDrawable().apply { addState(intArrayOf(android.R.attr.state_pressed), ColorDrawable(pressedColor)) addState(intArrayOf(), ColorDrawable(thumbColor)) } val trackDrawable = ColorDrawable(trackColor) try { val initFastScrollerMethod = RecyclerView::class.java.getDeclaredMethod( "initFastScroller", StateListDrawable::class.java, Drawable::class.java, StateListDrawable::class.java, Drawable::class.java ).apply { isAccessible = true } initFastScrollerMethod.invoke( this, thumbDrawableSelector, trackDrawable, thumbDrawableSelector, trackDrawable ) } catch (error: Exception) { Timber.e(error, "Could not enable fast scroll") } }
gpl-3.0
b6d81f24f9723758fe1f32960ff3c18e
34.226891
108
0.728531
4.897196
false
false
false
false
google/xplat
j2kt/jre/java/common/javaemul/lang/JavaAbstractList.kt
1
2952
/* * Copyright 2022 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 javaemul.lang /** Bridge class for java.util.AbstractList. */ abstract class JavaAbstractList<E> : AbstractMutableList<E>(), JavaList<E> { override fun addAll(index: Int, c: Collection<E>) = super<JavaList>.addAll(index, c) override fun addAll(c: Collection<E>): Boolean = super<JavaList>.addAll(c) override fun contains(e: E): Boolean = super<JavaList>.contains(e) override fun containsAll(c: Collection<E>): Boolean = super<JavaList>.containsAll(c) override fun indexOf(e: E): Int = super<JavaList>.indexOf(e) override fun lastIndexOf(e: E): Int = super<JavaList>.lastIndexOf(e) override fun remove(e: E): Boolean = super<JavaList>.remove(e) override fun removeAll(c: Collection<E>): Boolean = super<JavaList>.removeAll(c) override fun retainAll(c: Collection<E>): Boolean = super<JavaList>.retainAll(c) override fun java_addAll(index: Int, c: MutableCollection<out E>): Boolean = super<AbstractMutableList>.addAll(index, c) override fun java_addAll(c: MutableCollection<out E>): Boolean = super<AbstractMutableList>.addAll(c) @Suppress("UNCHECKED_CAST") override fun java_contains(a: Any?): Boolean = super<AbstractMutableList>.contains(a as E) @Suppress("UNCHECKED_CAST") override fun java_containsAll(c: MutableCollection<out Any?>): Boolean = super<AbstractMutableList>.containsAll(c as MutableCollection<E>) @Suppress("UNCHECKED_CAST") override fun java_indexOf(a: Any?): Int = super<AbstractMutableList>.indexOf(a as E) @Suppress("UNCHECKED_CAST") override fun java_lastIndexOf(a: Any?): Int = super<AbstractMutableList>.lastIndexOf(a as E) @Suppress("UNCHECKED_CAST") override fun java_remove(a: Any?): Boolean = super<AbstractMutableList>.remove(a as E) @Suppress("UNCHECKED_CAST") override fun java_removeAll(c: MutableCollection<out Any?>): Boolean = super<AbstractMutableList>.removeAll(c as MutableCollection<E>) @Suppress("UNCHECKED_CAST") override fun java_retainAll(c: MutableCollection<out Any?>): Boolean = super<AbstractMutableList>.retainAll(c as MutableCollection<E>) override fun add(index: Int, element: E) { throw UnsupportedOperationException() } override fun set(index: Int, element: E): E { throw UnsupportedOperationException() } override fun removeAt(index: Int): E { throw UnsupportedOperationException() } }
apache-2.0
58772fa8d99d6745285507aff76ff45b
37.337662
94
0.73374
4.016327
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io/kotest/assertions/until/until.kt
1
2440
package io.kotest.assertions.until import io.kotest.assertions.Failures import kotlinx.coroutines.delay import kotlin.time.Duration import kotlin.time.ExperimentalTime import kotlin.time.MonoClock import kotlin.time.seconds interface UntilListener<in T> { fun onEval(t: T) companion object { val noop = object : UntilListener<Any?> { override fun onEval(t: Any?) {} } } } fun <T> untilListener(f: (T) -> Unit) = object : UntilListener<T> { override fun onEval(t: T) { f(t) } } /** * Executes a function until it returns true or the duration elapses. * * @param f the function to execute * @param duration the maximum amount of time to continue trying for success * @param interval the delay between invocations */ @UseExperimental(ExperimentalTime::class) suspend fun until( duration: Duration, interval: Interval = 1.seconds.fixed(), f: () -> Boolean ) = until(duration, interval, { it }, UntilListener.noop, f) @UseExperimental(ExperimentalTime::class) suspend fun <T> until( duration: Duration, predicate: (T) -> Boolean, f: () -> T ): T = until(duration, 1.seconds.fixed(), predicate, UntilListener.noop, f) @UseExperimental(ExperimentalTime::class) suspend fun <T> until( duration: Duration, interval: Interval, predicate: (T) -> Boolean, f: () -> T ): T = until(duration, interval, predicate = predicate, listener = UntilListener.noop, f = f) /** * Executes a function until the given predicate returns true or the duration elapses. * * @param f the function to execute * @param predicate passed the result of the function f to evaluate if successful * @param listener notified on each invocation of f * @param duration the maximum amount of time to continue trying for success * @param interval the delay between invocations */ @UseExperimental(ExperimentalTime::class) suspend fun <T> until( duration: Duration, interval: Interval, predicate: (T) -> Boolean, listener: UntilListener<T>, f: () -> T ): T { val end = MonoClock.markNow().plus(duration) var count = 0 while (end.hasNotPassedNow()) { val result = f() if (predicate(result)) { return result } else { listener.onEval(result) count++ } delay(interval.next(count).toLongMilliseconds()) } throw Failures.failure("Test failed after ${duration.toLongMilliseconds()}ms; attempted $count times") }
apache-2.0
c067ad07468717ca29440d005603a90f
27.705882
105
0.688115
3.891547
false
false
false
false
JackParisi/DroidBox
droidbox/src/main/java/com/github/giacomoparisi/droidbox/validator/rule/MatcherDroidValidatorRule.kt
1
1165
package com.github.giacomoparisi.droidbox.validator.rule import android.widget.TextView import com.github.giacomoparisi.droidbox.validator.helper.DroidEditTextHelper import com.github.giacomoparisi.droidbox.validator.rule.core.DroidValidatorRule /** * Created by Giacomo Parisi on 15/02/18. * https://github.com/giacomoParisi */ class MatcherDroidValidatorRule( view: TextView, value: TextView?, errorMessage: String, private val match: Boolean) : DroidValidatorRule<TextView, TextView?>(view, value, errorMessage) { public override fun isValid(view: TextView): Boolean { if (value == null || view.text.isNullOrEmpty() || view.text.isNullOrBlank()) { return true } return if (match) { view.text.toString() == value!!.text.toString() } else { view.text.toString() != value!!.text.toString() } } public override fun onValidationSucceeded(view: TextView) { DroidEditTextHelper.removeError(view) } public override fun onValidationFailed(view: TextView) { DroidEditTextHelper.setError(view, errorMessage) } }
apache-2.0
3b826dc188820029b154b80b767de682
29.684211
86
0.676395
4.396226
false
false
false
false
jiangkang/KTools
hybrid/src/main/java/com/jiangkang/hybrid/webview/NestedWebView.kt
1
3758
package com.jiangkang.hybrid.webview import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.webkit.WebView import androidx.core.view.NestedScrollingChild import androidx.core.view.NestedScrollingChildHelper import androidx.core.view.ViewCompat /** * 支持嵌套滑动的WebView */ class NestedWebView(context: Context, attrs: AttributeSet?) : WebView(context, attrs), NestedScrollingChild { private var mLastY = 0 private val mScrollOffset = IntArray(2) private val mScrollConsumed = IntArray(2) private var mNestedOffsetY = 0 private val mChildHelper: NestedScrollingChildHelper = NestedScrollingChildHelper(this) override fun onTouchEvent(ev: MotionEvent): Boolean { val event = MotionEvent.obtain(ev) val action = ev.actionMasked if (action == MotionEvent.ACTION_DOWN) { mNestedOffsetY = 0 } val eventY = event.y.toInt() event.offsetLocation(0f, mNestedOffsetY.toFloat()) when (action) { MotionEvent.ACTION_MOVE -> { var deltaY = mLastY - eventY if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) { deltaY -= mScrollConsumed[1] event.offsetLocation(0f, (-mScrollOffset[1]).toFloat()) mNestedOffsetY += mScrollOffset[1] } mLastY = eventY - mScrollOffset[1] if (dispatchNestedScroll(0, mScrollOffset[1], 0, deltaY, mScrollOffset)) { mLastY -= mScrollOffset[1] event.offsetLocation(0f, mScrollOffset[1].toFloat()) mNestedOffsetY += mScrollOffset[1] } } MotionEvent.ACTION_DOWN -> { mLastY = eventY startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL) } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> stopNestedScroll() else -> { } } // Execute event handler from parent class in all cases val eventHandled = super.onTouchEvent(event) // Recycle previously obtained event event.recycle() return eventHandled } // NestedScrollingChild override fun setNestedScrollingEnabled(enabled: Boolean) { mChildHelper.isNestedScrollingEnabled = enabled } override fun isNestedScrollingEnabled(): Boolean { return mChildHelper.isNestedScrollingEnabled } override fun startNestedScroll(axes: Int): Boolean { return mChildHelper.startNestedScroll(axes) } override fun stopNestedScroll() { mChildHelper.stopNestedScroll() } override fun hasNestedScrollingParent(): Boolean { return mChildHelper.hasNestedScrollingParent() } override fun dispatchNestedScroll(dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, offsetInWindow: IntArray?): Boolean { return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow) } override fun dispatchNestedPreScroll(dx: Int, dy: Int, consumed: IntArray?, offsetInWindow: IntArray?): Boolean { return mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow) } override fun dispatchNestedFling(velocityX: Float, velocityY: Float, consumed: Boolean): Boolean { return mChildHelper.dispatchNestedFling(velocityX, velocityY, consumed) } override fun dispatchNestedPreFling(velocityX: Float, velocityY: Float): Boolean { return mChildHelper.dispatchNestedPreFling(velocityX, velocityY) } init { isNestedScrollingEnabled = true } }
mit
d65cd4d7f478aa0bf500a14708c0fba7
36.45
147
0.6664
5.012048
false
false
false
false
vhromada/Catalog-Spring
src/main/kotlin/cz/vhromada/catalog/web/domain/ShowData.kt
1
891
package cz.vhromada.catalog.web.domain import cz.vhromada.catalog.entity.Show import cz.vhromada.common.entity.Time import java.io.Serializable import java.util.Objects /** * A class represents show data. * * @author Vladimir Hromada */ data class ShowData( /** * Show */ val show: Show, /** * Count of seasons */ val seasonsCount: Int, /** * Count of episodes */ val episodesCount: Int, /** * Total length */ val totalLength: Time) : Serializable { override fun equals(other: Any?): Boolean { if (this === other) { return true } return if (other !is ShowData) { false } else show == other.show } override fun hashCode(): Int { return Objects.hashCode(show) } }
mit
e75bf43b8eadaee1a6a3e079867ceeb7
17.5625
47
0.529742
4.367647
false
false
false
false
ysl3000/PathfindergoalAPI
Pathfinder_1_14/src/main/java/com/github/ysl3000/bukkit/pathfinding/craftbukkit/v1_14_R1/pathfinding/CraftPathfinderGoalWrapper.kt
1
553
package com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_14_R1.pathfinding import net.minecraft.server.v1_14_R1.PathfinderGoal class CraftPathfinderGoalWrapper( private val pathfinderGoal: com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderGoal) : PathfinderGoal() { override fun a() = pathfinderGoal.shouldExecute() override fun b() = pathfinderGoal.canContinueToUse() override fun c() = pathfinderGoal.init() override fun d() = pathfinderGoal.reset() override fun e() = pathfinderGoal.execute() }
mit
db7efb26de08b1c394d3d2223c6475ac
23.043478
122
0.748644
4.096296
false
false
false
false
Ph1b/MaterialAudiobookPlayer
playbackScreen/src/main/kotlin/voice/playbackScreen/BookPlayController.kt
1
6876
package voice.playbackScreen import android.os.Bundle import android.view.GestureDetector import android.view.MenuItem import android.view.MotionEvent import androidx.core.view.GestureDetectorCompat import androidx.core.view.isVisible import coil.load import com.google.android.material.slider.Slider import com.google.android.material.snackbar.Snackbar import com.squareup.anvil.annotations.ContributesTo import de.ph1b.audiobook.AppScope import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.getBookId import de.ph1b.audiobook.data.putBookId import de.ph1b.audiobook.rootComponentAs import kotlinx.coroutines.launch import timber.log.Timber import voice.common.PlayPauseDrawableSetter import voice.common.conductor.ViewBindingController import voice.common.conductor.clearAfterDestroyView import voice.common.formatTime import voice.playbackScreen.databinding.BookPlayBinding import voice.sleepTimer.SleepTimerDialogController import javax.inject.Inject import kotlin.time.Duration import kotlin.time.DurationUnit private const val NI_BOOK_ID = "niBookId" class BookPlayController(bundle: Bundle) : ViewBindingController<BookPlayBinding>(bundle, BookPlayBinding::inflate) { constructor(bookId: Book2.Id) : this(Bundle().apply { putBookId(NI_BOOK_ID, bookId) }) @Inject lateinit var viewModel: BookPlayViewModel private val bookId: Book2.Id = bundle.getBookId(NI_BOOK_ID)!! private var coverLoaded = false private var sleepTimerItem: MenuItem by clearAfterDestroyView() private var skipSilenceItem: MenuItem by clearAfterDestroyView() private var playPauseDrawableSetter by clearAfterDestroyView<PlayPauseDrawableSetter>() init { rootComponentAs<Component>().inject(this) this.viewModel.bookId = bookId } override fun BookPlayBinding.onBindingCreated() { coverLoaded = false playPauseDrawableSetter = PlayPauseDrawableSetter(play) setupClicks() setupSlider() setupToolbar() } override fun BookPlayBinding.onAttach() { lifecycleScope.launch { [email protected]().collect { [email protected](it) } } lifecycleScope.launch { [email protected] { handleViewEffect(it) } } } private fun handleViewEffect(effect: BookPlayViewEffect) { when (effect) { BookPlayViewEffect.BookmarkAdded -> { Snackbar.make(view!!, R.string.bookmark_added, Snackbar.LENGTH_SHORT) .show() } BookPlayViewEffect.ShowSleepTimeDialog -> { openSleepTimeDialog() } } } private fun BookPlayBinding.render(viewState: BookPlayViewState) { Timber.d("render $viewState") binding.title.text = viewState.title currentChapterText.text = viewState.chapterName currentChapterContainer.isVisible = viewState.chapterName != null previous.isVisible = viewState.showPreviousNextButtons next.isVisible = viewState.showPreviousNextButtons playedTime.text = formatTime( viewState.playedTime.inWholeMilliseconds, viewState.duration.inWholeMilliseconds ) maxTime.text = formatTime( viewState.duration.inWholeMilliseconds, viewState.duration.inWholeMilliseconds ) slider.valueTo = viewState.duration.toDouble(DurationUnit.MILLISECONDS).toFloat() if (!slider.isPressed) { slider.value = viewState.playedTime.toDouble(DurationUnit.MILLISECONDS).toFloat() } skipSilenceItem.isChecked = viewState.skipSilence playPauseDrawableSetter.setPlaying(viewState.playing) showLeftSleepTime(this, viewState.sleepTime) if (!coverLoaded) { coverLoaded = true val coverFile = viewState.cover cover.load(coverFile) { fallback(R.drawable.default_album_art) error(R.drawable.default_album_art) } } } private fun setupClicks() { binding.play.setOnClickListener { viewModel.playPause() } binding.rewind.setOnClickListener { viewModel.rewind() } binding.fastForward.setOnClickListener { viewModel.fastForward() } binding.previous.setOnClickListener { viewModel.previous() } binding.next.setOnClickListener { viewModel.next() } binding.currentChapterContainer.setOnClickListener { viewModel.onCurrentChapterClicked() } val detector = GestureDetectorCompat( activity, object : GestureDetector.SimpleOnGestureListener() { override fun onDoubleTap(e: MotionEvent?): Boolean { viewModel.playPause() return true } } ) binding.cover.isClickable = true @Suppress("ClickableViewAccessibility") binding.cover.setOnTouchListener { _, event -> detector.onTouchEvent(event) } } private fun setupSlider() { binding.slider.setLabelFormatter { formatTime(it.toLong(), binding.slider.valueTo.toLong()) } binding.slider.addOnChangeListener { slider, value, fromUser -> if (isAttached && !fromUser) { binding.playedTime.text = formatTime(value.toLong(), slider.valueTo.toLong()) } } binding.slider.addOnSliderTouchListener(object : Slider.OnSliderTouchListener { override fun onStartTrackingTouch(slider: Slider) { } override fun onStopTrackingTouch(slider: Slider) { val progress = slider.value.toLong() [email protected](progress) } }) } private fun setupToolbar() { val menu = binding.toolbar.menu sleepTimerItem = menu.findItem(R.id.action_sleep) skipSilenceItem = menu.findItem(R.id.action_skip_silence) binding.toolbar.setNavigationOnClickListener { router.popController(this) } binding.toolbar.setOnMenuItemClickListener { when (it.itemId) { R.id.action_settings -> { viewModel.onSettingsClicked() true } R.id.action_sleep -> { viewModel.toggleSleepTimer() true } R.id.action_time_lapse -> { viewModel.onPlaybackSpeedIconClicked() true } R.id.action_bookmark -> { viewModel.onBookmarkClicked() true } R.id.action_skip_silence -> { this.viewModel.toggleSkipSilence() true } else -> false } } } private fun showLeftSleepTime(binding: BookPlayBinding, duration: Duration) { val active = duration > Duration.ZERO sleepTimerItem.setIcon(if (active) R.drawable.alarm_off else R.drawable.alarm) binding.timerCountdownView.text = formatTime(duration.inWholeMilliseconds, duration.inWholeMilliseconds) binding.timerCountdownView.isVisible = active } private fun openSleepTimeDialog() { SleepTimerDialogController(bookId) .showDialog(router) } @ContributesTo(AppScope::class) interface Component { fun inject(target: BookPlayController) } }
lgpl-3.0
d30b1cd1e5c2b1f24aea2dfaeb0daae8
30.833333
117
0.720332
4.526662
false
false
false
false
robinverduijn/gradle
subprojects/instant-execution-report/src/main/kotlin/elmish/tree/TreeView.kt
1
4035
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package elmish.tree import data.mapAt import elmish.View import elmish.attributes import elmish.div import elmish.empty import elmish.li import elmish.ul object TreeView { data class Model<T>( val tree: Tree<T> ) sealed class Intent<T> { data class Toggle<T>(val focus: Tree.Focus<T>) : Intent<T>() } fun <T> view(model: Model<T>): View<Intent<T>> = viewTree<T, Intent<T>>(model.tree.focus()) { focus -> div( attributes { onClick { Intent.Toggle(focus) } }, focus.tree.label.toString() ) } fun <T> step(intent: Intent<T>, model: Model<T>): Model<T> = when (intent) { is Intent.Toggle -> model.copy( tree = intent.focus.update { copy(state = state.toggle()) } ) } } /** * A persistent tree view model. */ data class Tree<T>( val label: T, val children: List<Tree<T>> = emptyList(), val state: ViewState = ViewState.Collapsed ) { enum class ViewState { Collapsed, Expanded; fun toggle(): ViewState = when (this) { Collapsed -> Expanded Expanded -> Collapsed } } /** * Creates an updatable reference to this tree. */ fun focus(): Focus<T> = Focus.Original( this ) fun isNotEmpty(): Boolean = children.isNotEmpty() /** * Propagates changes to a particular node in the tree all the way * up to the root (the [focused][focus] tree). */ sealed class Focus<T> { abstract val tree: Tree<T> abstract fun update(f: Tree<T>.() -> Tree<T>): Tree<T> val children get() = tree.children.indices.asSequence().map(::child) fun child(index: Int): Focus<T> = Child( this, index, tree.children[index] ) data class Original<T>( override val tree: Tree<T> ) : Focus<T>() { override fun update(f: Tree<T>.() -> Tree<T>): Tree<T> = f(tree) } data class Child<T>( val parent: Focus<T>, val index: Int, override val tree: Tree<T> ) : Focus<T>() { override fun update(f: Tree<T>.() -> Tree<T>): Tree<T> = parent.update { copy(children = children.mapAt(index, f)) } } } } fun <T, I> viewTree( focus: Tree.Focus<T>, viewLabel: (Tree.Focus<T>) -> View<I> ): View<I> = ul( viewSubTree(focus, viewLabel) ) fun <T, I> viewSubTree( focus: Tree.Focus<T>, viewLabel: (Tree.Focus<T>) -> View<I> ): View<I> = focus.tree.run { li( viewLabel(focus), children.takeIf { state == Tree.ViewState.Expanded && it.isNotEmpty() }?.run { viewExpanded(focus, viewLabel) } ?: empty ) } fun <T, I> viewExpanded(focus: Tree.Focus<T>, viewLabel: Tree.Focus<T>.() -> View<I>): View<I> = ul(viewChildrenOf(focus, viewLabel)) fun <I, T> viewChildrenOf( focus: Tree.Focus<T>, viewLabel: (Tree.Focus<T>) -> View<I> ): List<View<I>> = viewSubTrees(focus.children, viewLabel) fun <I, T> viewSubTrees( subTrees: Sequence<Tree.Focus<T>>, viewLabel: (Tree.Focus<T>) -> View<I> ): List<View<I>> = subTrees .map { subTree -> viewSubTree(subTree, viewLabel) } .toList()
apache-2.0
bbccda34750aa9ac5aeb84e235144c72
23.603659
96
0.567782
3.658205
false
false
false
false
robinverduijn/gradle
subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/InstantExecutionHost.kt
1
11751
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.instantexecution import org.gradle.api.internal.BuildDefinition import org.gradle.api.internal.GradleInternal import org.gradle.api.internal.SettingsInternal import org.gradle.api.internal.initialization.ClassLoaderScope import org.gradle.api.internal.initialization.ScriptHandlerFactory import org.gradle.api.internal.project.IProjectFactory import org.gradle.api.internal.project.ProjectInternal import org.gradle.api.internal.project.ProjectStateRegistry import org.gradle.configuration.project.ConfigureProjectBuildOperationType import org.gradle.execution.plan.Node import org.gradle.groovy.scripts.StringScriptSource import org.gradle.initialization.BuildLoader import org.gradle.initialization.BuildOperatingFiringSettingsPreparer import org.gradle.initialization.BuildOperatingFiringTaskExecutionPreparer import org.gradle.initialization.BuildOperationSettingsProcessor import org.gradle.initialization.ClassLoaderScopeRegistry import org.gradle.initialization.DefaultProjectDescriptor import org.gradle.initialization.DefaultSettings import org.gradle.initialization.NotifyingBuildLoader import org.gradle.initialization.SettingsLocation import org.gradle.initialization.SettingsPreparer import org.gradle.initialization.SettingsProcessor import org.gradle.initialization.TaskExecutionPreparer import org.gradle.initialization.buildsrc.BuildSourceBuilder import org.gradle.internal.build.BuildState import org.gradle.internal.file.PathToFileResolver import org.gradle.internal.operations.BuildOperationCategory import org.gradle.internal.operations.BuildOperationContext import org.gradle.internal.operations.BuildOperationDescriptor import org.gradle.internal.operations.BuildOperationExecutor import org.gradle.internal.operations.RunnableBuildOperation import org.gradle.internal.reflect.Instantiator import org.gradle.internal.service.scopes.BuildScopeServiceRegistryFactory import org.gradle.plugin.management.internal.autoapply.AutoAppliedPluginRegistry import org.gradle.plugin.use.internal.PluginRequestApplicator import org.gradle.util.Path import java.io.File class InstantExecutionHost internal constructor( private val gradle: GradleInternal, private val classLoaderScopeRegistry: ClassLoaderScopeRegistry, private val projectFactory: IProjectFactory ) : DefaultInstantExecution.Host { private val startParameter = gradle.startParameter override val skipLoadingStateReason: String? get() = if (startParameter.isRefreshDependencies) { "--refresh-dependencies" } else { null } override val currentBuild: ClassicModeBuild = DefaultClassicModeBuild() override fun createBuild(rootProjectName: String): InstantExecutionBuild = DefaultInstantExecutionBuild(gradle, service(), rootProjectName) override fun <T> getService(serviceType: Class<T>): T = gradle.services.get(serviceType) override fun getSystemProperty(propertyName: String) = startParameter.systemPropertiesArgs[propertyName] override val requestedTaskNames: List<String> = startParameter.taskNames override val rootDir: File = startParameter.currentDir inner class DefaultClassicModeBuild : ClassicModeBuild { override val buildSrc: Boolean get() = gradle.parent != null && gradle.publicBuildPath.buildPath.name == BuildSourceBuilder.BUILD_SRC override val gradle: GradleInternal get() = [email protected] override val scheduledWork: List<Node> get() = gradle.taskGraph.scheduledWork override val rootProject: ProjectInternal get() = gradle.rootProject } inner class DefaultInstantExecutionBuild( override val gradle: GradleInternal, private val fileResolver: PathToFileResolver, rootProjectName: String ) : InstantExecutionBuild { init { gradle.run { settings = createSettings() // Fire build operation required by build scan to determine startup duration and settings evaluated duration val settingsPreparer = BuildOperatingFiringSettingsPreparer( SettingsPreparer { // Nothing to do // TODO:instant-execution - instead, create and attach the settings object }, service<BuildOperationExecutor>(), service<BuildDefinition>().fromBuild ) settingsPreparer.prepareSettings(this) setBaseProjectClassLoaderScope(coreScope) rootProject = createProject(null, rootProjectName) defaultProject = rootProject } } override fun createProject(path: String): ProjectInternal { val projectPath = Path.path(path) val name = projectPath.name return when { name != null -> createProject(projectPath.parent, name) else -> gradle.rootProject } } private fun InstantExecutionHost.createProject(parentPath: Path?, name: String): ProjectInternal { val projectDescriptor = DefaultProjectDescriptor( getProjectDescriptor(parentPath), name, rootDir, projectDescriptorRegistry, fileResolver ) return projectFactory.createProject( gradle, projectDescriptor, getProject(parentPath), coreAndPluginsScope.createChild(projectDescriptor.path), coreAndPluginsScope ) } override fun registerProjects() { // Ensure projects are registered for look up e.g. by dependency resolution service<ProjectStateRegistry>().registerProjects(service<BuildState>()) // Fire build operation required by build scans to determine build path (and settings execution time) // It may be better to instead point GE at the origin build that produced the cached task graph, // or replace this with a different event/op that carries this information and wraps some actual work val buildOperationExecutor = service<BuildOperationExecutor>() val settingsProcessor = BuildOperationSettingsProcessor( SettingsProcessor { gradle, _, _, _ -> gradle.settings }, buildOperationExecutor ) val rootProject = gradle.rootProject val settingsLocation = SettingsLocation(rootProject.projectDir, File(rootProject.projectDir, "settings.gradle")) settingsProcessor.process(gradle, settingsLocation, coreAndPluginsScope, startParameter) // Fire build operation required by build scans to determine the build's project structure (and build load time) val buildLoader = NotifyingBuildLoader(BuildLoader { _, _ -> }, buildOperationExecutor) buildLoader.load(gradle.settings, gradle) // Fire build operation required by build scans to determine the root path buildOperationExecutor.run(object : RunnableBuildOperation { override fun run(context: BuildOperationContext?) = Unit override fun description(): BuildOperationDescriptor.Builder { val project = gradle.rootProject val displayName = "Configure project " + project.identityPath return BuildOperationDescriptor.displayName(displayName) .operationType(BuildOperationCategory.CONFIGURE_PROJECT) .progressDisplayName(displayName) .details(ConfigureProjectBuildOperationType.DetailsImpl(project.projectPath, gradle.identityPath, project.rootDir)) } }) } override fun getProject(path: String): ProjectInternal = gradle.rootProject.project(path) override fun autoApplyPlugins() { if (!startParameter.isBuildScan) { return } // System properties are currently set as during settings script execution, so work around for now // TODO - extract system properties setup into some that can be reused for instant execution val buildScanUrl = getSystemProperty("com.gradle.scan.server") if (buildScanUrl != null) { System.setProperty("com.gradle.scan.server", buildScanUrl) } val rootProject = gradle.rootProject val pluginRequests = service<AutoAppliedPluginRegistry>().getAutoAppliedPlugins(rootProject) service<PluginRequestApplicator>().applyPlugins( pluginRequests, rootProject.buildscript, rootProject.pluginManager, rootProject.classLoaderScope ) } override fun scheduleNodes(nodes: Collection<Node>) { gradle.taskGraph.run { addNodes(nodes) populate() } // Fire build operation required by build scan to determine when task execution starts // Currently this operation is not around the actual task graph calculation/populate for instant execution (just to make this a smaller step) // This might be better done as a new build operation type BuildOperatingFiringTaskExecutionPreparer( TaskExecutionPreparer { // Nothing to do // TODO:instant-execution - perhaps move this so it wraps loading tasks from cache file }, service<BuildOperationExecutor>() ).prepareForTaskExecution(gradle) } private fun createSettings(): SettingsInternal = StringScriptSource("settings", "").let { settingsSource -> service<Instantiator>().newInstance( DefaultSettings::class.java, service<BuildScopeServiceRegistryFactory>(), gradle, coreScope, coreScope, service<ScriptHandlerFactory>().create(settingsSource, coreScope), rootDir, settingsSource, startParameter ) } } private val coreScope: ClassLoaderScope get() = classLoaderScopeRegistry.coreScope private val coreAndPluginsScope: ClassLoaderScope get() = classLoaderScopeRegistry.coreAndPluginsScope private fun getProject(parentPath: Path?) = parentPath?.let { gradle.rootProject.project(it.path) } private fun getProjectDescriptor(parentPath: Path?): DefaultProjectDescriptor? = parentPath?.let { projectDescriptorRegistry.getProject(it.path) } private val projectDescriptorRegistry get() = (gradle.settings as DefaultSettings).projectDescriptorRegistry }
apache-2.0
c3ccaff509c52c8314b347005fefcbf0
42.361624
153
0.679432
5.698836
false
false
false
false
cuebyte/rendition
src/test/kotlin/moe/cuebyte/rendition/mock/BookStr.kt
1
417
package moe.cuebyte.rendition.mock import moe.cuebyte.rendition.Model import moe.cuebyte.rendition.type.long import moe.cuebyte.rendition.type.string object BookStr : Model("book_str", { it["id"] = string().primaryKey().auto() it["author"] = string().index() it["publish"] = string().index() it["words"] = long().index() it["sales"] = long().index() it["introduce"] = string() it["date"] = string() })
lgpl-3.0
07df894fe9bee7de1be7a63bbbf43657
26.866667
41
0.664269
3.362903
false
false
true
false
xfournet/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/DirectoryChangesGroupingPolicy.kt
1
3762
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder.DIRECTORY_CACHE import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder.PATH_NODE_BUILDER import javax.swing.tree.DefaultTreeModel class DirectoryChangesGroupingPolicy(val project: Project, val model: DefaultTreeModel) : BaseChangesGroupingPolicy() { private val innerPolicy = ChangesGroupingPolicyFactory.getInstance(project)?.createGroupingPolicy(model) override fun getParentNodeFor(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*> { DIRECTORY_POLICY.set(subtreeRoot, this) val grandParent = nextPolicy?.getParentNodeFor(nodePath, subtreeRoot) ?: subtreeRoot HIERARCHY_UPPER_BOUND.set(subtreeRoot, grandParent) CACHING_ROOT.set(subtreeRoot, getCachingRoot(grandParent, subtreeRoot)) return getParentNodeRecursive(nodePath, subtreeRoot) } private fun getParentNodeRecursive(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>) = getParentFromInnerPolicy(nodePath, subtreeRoot) ?: getParentNodeInternal(nodePath, subtreeRoot) @JvmName("getParentNodeInternal") internal fun getParentNodeInternal(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*> { generateSequence(nodePath.parent) { it.parent }.forEach { parentPath -> val cachingRoot = getCachingRoot(subtreeRoot) DIRECTORY_CACHE.getValue(cachingRoot)[parentPath.key]?.let { if (HIERARCHY_UPPER_BOUND.get(subtreeRoot) == it) { GRAND_PARENT_CANDIDATE.set(subtreeRoot, it) try { return getParentFromInnerPolicy(parentPath, subtreeRoot) ?: getPathNode(parentPath, subtreeRoot) ?: it } finally { GRAND_PARENT_CANDIDATE.set(subtreeRoot, null) } } return it } getPathNode(parentPath, subtreeRoot)?.let { return it } } return subtreeRoot } private fun getParentFromInnerPolicy(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? { innerPolicy?.getParentNodeFor(nodePath, subtreeRoot)?.let { it.markAsHelperNode() return it } return null } private fun getPathNode(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? { PATH_NODE_BUILDER.getRequired(subtreeRoot).apply(nodePath)?.let { it.markAsHelperNode() val grandParent = GRAND_PARENT_CANDIDATE.get(subtreeRoot) ?: getParentNodeRecursive(nodePath, subtreeRoot) val cachingRoot = getCachingRoot(subtreeRoot) model.insertNodeInto(it, grandParent, grandParent.childCount) DIRECTORY_CACHE.getValue(cachingRoot)[nodePath.key] = it return it } return null } class Factory(val project: Project) : ChangesGroupingPolicyFactory() { override fun createGroupingPolicy(model: DefaultTreeModel) = DirectoryChangesGroupingPolicy(project, model) } companion object { @JvmField internal val DIRECTORY_POLICY = Key.create<DirectoryChangesGroupingPolicy>("ChangesTree.DirectoryPolicy") internal val GRAND_PARENT_CANDIDATE = Key.create<ChangesBrowserNode<*>?>("ChangesTree.GrandParentCandidate") private val HIERARCHY_UPPER_BOUND = Key.create<ChangesBrowserNode<*>?>("ChangesTree.HierarchyUpperBound") internal val CACHING_ROOT = Key.create<ChangesBrowserNode<*>?>("ChangesTree.CachingRoot") internal fun getCachingRoot(subtreeRoot: ChangesBrowserNode<*>) = CACHING_ROOT.get(subtreeRoot) ?: subtreeRoot } }
apache-2.0
bc3d8afe32158f163a9ac227941a0afe
43.797619
140
0.753323
4.593407
false
false
false
false
mattak/KotlinMoment
src/main/kotlin/me/mattak/moment/Moment.kt
1
6139
package me.mattak.moment import java.text.SimpleDateFormat import java.util.* /** * Moment * Created by mattak on 15/09/02. */ public class Moment( val date: Date = Date(), val timeZone: TimeZone = TimeZone.getDefault(), val locale: Locale = Locale.getDefault() ) : Comparable<Moment> { val year: Int get() = getCalendarNumber(Calendar.YEAR) val month: Int get() = getCalendarNumber(Calendar.MONTH) + 1 // 0-11 val day: Int get() = getCalendarNumber(Calendar.DAY_OF_MONTH) val hour: Int get() = getCalendarNumber(Calendar.HOUR_OF_DAY) val minute: Int get() = getCalendarNumber(Calendar.MINUTE) val second: Int get() = getCalendarNumber(Calendar.SECOND) val millisecond: Int get() = getCalendarNumber(Calendar.MILLISECOND) val weekday: Int get() = getCalendarNumber(Calendar.DAY_OF_WEEK) val weekdayName: String get() = getFormatString("EEEE") val weekdayOrdinal: Int get() = getCalendarNumber(Calendar.DAY_OF_WEEK) val weekOfYear: Int get() = getCalendarNumber(Calendar.WEEK_OF_YEAR) val quarter: Int get() = getCalendarNumber(Calendar.MONTH) / 3 + 1 val epoch: Long get() = getCalendar().timeInMillis / 1000 fun get(unit: TimeUnit): Int { when (unit) { TimeUnit.MILLISECONDS -> return millisecond TimeUnit.SECONDS -> return second TimeUnit.MINUTES -> return minute TimeUnit.HOURS -> return hour TimeUnit.DAYS -> return day TimeUnit.MONTHS -> return month TimeUnit.QUARTERS -> return quarter TimeUnit.YEARS -> return year } } fun format(dateFormat: String = "yyyy-MM-dd HH:mm:ss ZZZZ"): String { return getFormatString(dateFormat) } fun add(value: Long, unit: TimeUnit): Moment { val calendar = getCalendar() when (unit) { TimeUnit.MILLISECONDS -> { calendar.timeInMillis = calendar.timeInMillis + value return Moment(calendar.time, timeZone, locale) } TimeUnit.SECONDS -> { calendar.add(Calendar.SECOND, value.toInt()) return Moment(calendar.time, timeZone, locale) } TimeUnit.MINUTES -> { calendar.add(Calendar.MINUTE, value.toInt()) return Moment(calendar.time, timeZone, locale) } TimeUnit.HOURS -> { calendar.add(Calendar.HOUR_OF_DAY, value.toInt()) return Moment(calendar.time, timeZone, locale) } TimeUnit.DAYS -> { calendar.add(Calendar.DAY_OF_YEAR, value.toInt()) return Moment(calendar.time, timeZone, locale) } TimeUnit.MONTHS -> { calendar.add(Calendar.MONTH, value.toInt()) return Moment(calendar.time, timeZone, locale) } TimeUnit.QUARTERS -> { calendar.add(Calendar.MONTH, value.toInt() * 3) return Moment(calendar.time, timeZone, locale) } TimeUnit.YEARS -> { calendar.add(Calendar.YEAR, value.toInt()) return Moment(calendar.time, timeZone, locale) } } } fun add(value: Duration): Moment { return add(value.interval, TimeUnit.MILLISECONDS) } fun subtract(value: Long, unit: TimeUnit): Moment { return add(-value, unit) } fun subtract(duration: Duration): Moment { return add(-duration.interval, TimeUnit.MILLISECONDS) } fun isCloseTo(moment: Moment, precision: Long): Boolean { val delta = intervalSince(moment) return Math.abs(delta.millisec) <= precision } fun startOf(unit: TimeUnit): Moment { val calendar = getCalendar() if (unit.order == TimeUnit.MILLISECONDS.order) { return this } if (unit.order <= TimeUnit.YEARS.order) { calendar.set(Calendar.MONTH, 0) } if (unit.order <= TimeUnit.QUARTERS.order) { val month = calendar.get(Calendar.MONTH) val startMonth = (month / 3) * 3 calendar.set(Calendar.MONTH, startMonth) } if (unit.order <= TimeUnit.MONTHS.order) { calendar.set(Calendar.DAY_OF_MONTH, 1) } if (unit.order <= TimeUnit.DAYS.order) { calendar.set(Calendar.HOUR_OF_DAY, 0) } if (unit.order <= TimeUnit.HOURS.order) { calendar.set(Calendar.MINUTE, 0) } if (unit.order <= TimeUnit.MINUTES.order) { calendar.set(Calendar.SECOND, 0) } if (unit.order <= TimeUnit.SECONDS.order) { calendar.set(Calendar.MILLISECOND, 0) } return Moment(calendar.time, timeZone, locale) } fun endOf(unit: TimeUnit): Moment { return startOf(unit).add(1, unit).subtract(1.milliseconds) } fun intervalSince(moment: Moment): Duration { val millisec: Long = (date.getTime() - moment.date.getTime()) return Duration(millisec) } override fun equals(other: Any?): Boolean { if (other is Moment) { return date.equals(other.date) } return false } override fun compareTo(other: Moment): Int { return this.date.compareTo(other.date) } override fun toString(): String { return format() } private fun getCalendar(): Calendar { val cal = Calendar.getInstance(timeZone, locale) cal.setTime(date) return cal } private fun getDateFormat(dateFormat: String): SimpleDateFormat { val format = SimpleDateFormat(dateFormat, locale) format.timeZone = timeZone return format } private fun getCalendarNumber(type: Int): Int { return getCalendar().get(type) } private fun getFormatString(dateFormat: String): String { return getDateFormat(dateFormat).format(date) } }
apache-2.0
e1eba5fd8822eeba7eece1b14b119b28
29.098039
73
0.580713
4.410201
false
false
false
false
petrbalat/jlib
src/main/java/cz/softdeluxe/jlib/stringUtils.kt
1
1879
package cz.softdeluxe.jlib import java.security.SecureRandom import java.text.Normalizer import java.time.LocalDate import java.time.LocalDateTime import java.util.* import java.util.concurrent.ThreadLocalRandom import java.util.regex.Pattern inline val random: ThreadLocalRandom get() = ThreadLocalRandom.current() private val secureRandom = SecureRandom() fun randomString(length: Int): String { val uuid = UUID.randomUUID().toString().replace("-", "") return if (length < uuid.length) uuid.substring(0, length) else uuid } fun randomLocalDate(maxYear: Int = 2100): LocalDate { return LocalDate.of(random.nextInt(0, maxYear), random.nextInt(1, 12), random.nextInt(1, 29)) } fun randomLocalDateTime(maxYear: Int = 2100): LocalDateTime { return randomLocalDate().atStartOfDay() } fun String.maxSize(maxSize:Int): String { return if(maxSize >= length) this else this.substring(0, maxSize) } fun String.removeDiakritiku(): String { val normalize = Normalizer.normalize(this, Normalizer.Form.NFD) return normalize.filter { it <= '\u007F' } } val regexpNonNumeric = Regex("[^\\p{L}\\p{Nd}]+") fun String.removeNonAlphaNorNumeric(): String { return this.replace(regexpNonNumeric, "") } val regexpNotAlowedInFileName = Regex("[^a-zA-Z0-9.-]") fun String.removeNotAlowedInFileName(): String { return this.replace(regexpNotAlowedInFileName, "") } fun String?.emptyToNull(): String? = if (this.isNullOrEmpty()) null else this fun String?.blankToNull(): String? = if (this.isNullOrBlank()) null else this fun String.isInteger(): Boolean = toIntOrNull() != null private val emailmPattern = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+") fun parseEmail(str: String):Sequence<String> { val matcher = emailmPattern.matcher(str) return generateSequence { if(matcher.find()) matcher.group() else null } }
apache-2.0
b974eac610f28a0e6fe14d9d06fb41e5
30.333333
97
0.723789
3.634429
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/FrostApp.kt
1
3644
/* * Copyright 2018 Allan Wang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pitchedapps.frost import android.app.Activity import android.app.Application import android.os.Bundle import android.util.Log import ca.allanwang.kau.logging.KL import ca.allanwang.kau.utils.buildIsLollipopAndUp import com.github.piasy.biv.BigImageViewer import com.github.piasy.biv.loader.glide.GlideImageLoader import com.pitchedapps.frost.db.CookieDao import com.pitchedapps.frost.db.NotificationDao import com.pitchedapps.frost.facebook.requests.httpClient import com.pitchedapps.frost.injectors.ThemeProvider import com.pitchedapps.frost.prefs.Prefs import com.pitchedapps.frost.services.scheduleNotificationsFromPrefs import com.pitchedapps.frost.services.setupNotificationChannels import com.pitchedapps.frost.utils.FrostPglAdBlock import com.pitchedapps.frost.utils.L import dagger.hilt.android.HiltAndroidApp import java.util.Random import javax.inject.Inject /** Created by Allan Wang on 2017-05-28. */ @HiltAndroidApp class FrostApp : Application() { @Inject lateinit var prefs: Prefs @Inject lateinit var themeProvider: ThemeProvider @Inject lateinit var cookieDao: CookieDao @Inject lateinit var notifDao: NotificationDao override fun onCreate() { super.onCreate() if (!buildIsLollipopAndUp) return // not supported initPrefs() L.i { "Begin Frost for Facebook" } FrostPglAdBlock.init(this) setupNotificationChannels(this, themeProvider) scheduleNotificationsFromPrefs(prefs) BigImageViewer.initialize(GlideImageLoader.with(this, httpClient)) if (BuildConfig.DEBUG) { registerActivityLifecycleCallbacks( object : ActivityLifecycleCallbacks { override fun onActivityPaused(activity: Activity) {} override fun onActivityResumed(activity: Activity) {} override fun onActivityStarted(activity: Activity) {} override fun onActivityDestroyed(activity: Activity) { L.d { "Activity ${activity.localClassName} destroyed" } } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityStopped(activity: Activity) {} override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { L.d { "Activity ${activity.localClassName} created" } } } ) } } private fun initPrefs() { prefs.deleteKeys("search_bar", "shown_release", "experimental_by_default") KL.shouldLog = { BuildConfig.DEBUG } L.shouldLog = { when (it) { Log.VERBOSE -> BuildConfig.DEBUG Log.INFO, Log.ERROR -> true else -> BuildConfig.DEBUG || prefs.verboseLogging } } prefs.verboseLogging = false if (prefs.installDate == -1L) { prefs.installDate = System.currentTimeMillis() } if (prefs.identifier == -1) { prefs.identifier = Random().nextInt(Int.MAX_VALUE) } prefs.lastLaunch = System.currentTimeMillis() } }
gpl-3.0
abea844a7a3fd08669e227b49c735543
31.828829
91
0.727223
4.327791
false
false
false
false
ybonjour/test-store
backend/src/main/kotlin/ch/yvu/teststore/common/CassandraRepository.kt
1
954
package ch.yvu.teststore.common import com.datastax.driver.mapping.Mapper.Option.saveNullFields import com.datastax.driver.mapping.MappingManager abstract class CassandraRepository<M : Model>(val mappingManager: MappingManager, val table: String, val modelClass: Class<M>) { val session = mappingManager.session val mapper = mappingManager.mapper(modelClass) var pagedResultFetcher = PagedResultFetcher(session, mapper) var maxRowsResultFetcher = MaxRowsResultFetcher(pagedResultFetcher) open fun save(item: M): M { mapper.save(item, saveNullFields(false)) return item } open fun deleteAll() { mapper.deleteQuery("DELETE FROM $table") } open fun findAll(): List<M> { val results = session.execute("SELECT * FROM $table") return mapper.map(results).all().toList() } open fun count(): Long { throw UnsupportedOperationException("not yet implemented") } }
mit
33a79d92a99818fee2111ab7032808b6
31.931034
128
0.708595
4.184211
false
false
false
false
square/curtains
curtains/src/androidTest/java/curtains/test/OnWindowFocusChangedListenersTest.kt
1
3351
package curtains.test import android.app.AlertDialog import androidx.lifecycle.Lifecycle import androidx.test.core.app.ActivityScenario import curtains.test.utilities.OnActivityCreated import curtains.OnWindowFocusChangedListener import curtains.onWindowFocusChangedListeners import curtains.test.utilities.TestActivity import curtains.test.utilities.application import curtains.test.utilities.launchWaitingForFocus import curtains.test.utilities.registerUntilClosed import curtains.test.utilities.BlockingQueueSubject.Companion.assertThat import org.junit.Test import java.util.concurrent.ArrayBlockingQueue class OnWindowFocusChangedListenersTest { @Test fun activity_focus_gained_on_activity_resumed() { val activityWindowFocusChanged = ArrayBlockingQueue<Boolean>(1) application.registerUntilClosed(OnActivityCreated { activity, _ -> if (activity !is TestActivity) { return@OnActivityCreated } activity.window.onWindowFocusChangedListeners += object : OnWindowFocusChangedListener { override fun onWindowFocusChanged(hasFocus: Boolean) { activity.window.onWindowFocusChangedListeners -= this activityWindowFocusChanged.put(hasFocus) } } }).use { ActivityScenario.launch(TestActivity::class.java).use { assertThat(activityWindowFocusChanged).polls(true) } } } @Test fun activity_focus_lost_on_activity_paused() { val activityWindowFocusChanged = ArrayBlockingQueue<Boolean>(1) launchWaitingForFocus(TestActivity::class).use { scenario -> scenario.onActivity { activity -> activity.window.onWindowFocusChangedListeners += object : OnWindowFocusChangedListener { override fun onWindowFocusChanged(hasFocus: Boolean) { activity.window.onWindowFocusChangedListeners -= this activityWindowFocusChanged.put(hasFocus) } } } scenario.moveToState(Lifecycle.State.STARTED) assertThat(activityWindowFocusChanged).polls(false) } } @Test fun activity_focus_lost_on_dialog_showed() { val activityWindowFocusChanged = ArrayBlockingQueue<Boolean>(1) launchWaitingForFocus(TestActivity::class).use { scenario -> scenario.onActivity { activity -> activity.window.onWindowFocusChangedListeners += object : OnWindowFocusChangedListener { override fun onWindowFocusChanged(hasFocus: Boolean) { activity.window.onWindowFocusChangedListeners -= this activityWindowFocusChanged.put(hasFocus) } } AlertDialog.Builder(activity).show() } assertThat(activityWindowFocusChanged).polls(false) } } @Test fun dialog_focus_gained_on_dialog_showed() { val dialogWindowFocusChanged = ArrayBlockingQueue<Boolean>(1) launchWaitingForFocus(TestActivity::class).use { scenario -> scenario.onActivity { activity -> val dialog = AlertDialog.Builder(activity).show() dialog.window!!.onWindowFocusChangedListeners += object : OnWindowFocusChangedListener { override fun onWindowFocusChanged(hasFocus: Boolean) { dialog.window!!.onWindowFocusChangedListeners -= this dialogWindowFocusChanged.put(hasFocus) } } } assertThat(dialogWindowFocusChanged).polls(true) } } }
apache-2.0
f4eb591335e55989c250cd2229044bd2
36.662921
96
0.73023
5.108232
false
true
false
false
roylanceMichael/yaorm
yaorm/src/main/java/org/roylance/yaorm/models/TypeModel.kt
1
1872
package org.roylance.yaorm.models import org.roylance.yaorm.YaormModel class TypeModel( val columnName: String, val index: Int) { private var boolCount: Int = 0 private var doubleCount: Int = 0 private var intCount: Int = 0 private var strCount: Int = 0 private var maxStrSize: Int = 0 fun addTest(item: String) { if (isInt(item)) { this.intCount++ } else if (isDouble(item)) { this.doubleCount++ } else if (isBoolean(item)) { this.boolCount++ } else { this.strCount++ if (item.length > this.maxStrSize) { this.maxStrSize = item.length } } } fun buildColumnDefinition(): YaormModel.ColumnDefinition { return YaormModel.ColumnDefinition.newBuilder() .setName(this.columnName) .setOrder(this.index) .setType(this.calculateType()) .build() } private fun calculateType(): YaormModel.ProtobufType { if (this.strCount > 0) { return YaormModel.ProtobufType.STRING } else if (this.doubleCount > 0) { return YaormModel.ProtobufType.DOUBLE } else if (this.intCount > 0) { return YaormModel.ProtobufType.INT64 } return YaormModel.ProtobufType.BOOL } companion object { private const val LowercaseTrue = "true" private const val LowercaseFalse = "false" fun isBoolean(item: String): Boolean { val lowercaseItem = item.toLowerCase() return lowercaseItem == LowercaseTrue || lowercaseItem == LowercaseFalse } fun isInt(item: String): Boolean { if (item.isEmpty()) { return true } return try { item.toInt() true } catch (e: Exception) { false } } fun isDouble(item: String): Boolean { return try { item.toDouble() true } catch (e: Exception) { false } } } }
mit
a1bd818f9ef27fdf6993844d95b7a0be
22.708861
78
0.61485
4.043197
false
false
false
false