repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
VerifAPS/verifaps-lib
absintsfc/src/main/kotlin/AbstractIntEqSfcApp.kt
1
3150
import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.parameters.options.required import com.github.ajalt.clikt.parameters.types.file import edu.kit.iti.formal.automation.IEC61131Facade import edu.kit.iti.formal.automation.builtin.BuiltinLoader import edu.kit.iti.formal.automation.st.ast.FunctionBlockDeclaration import edu.kit.iti.formal.automation.st.ast.PouExecutable import edu.kit.iti.formal.automation.st0.MultiCodeTransformation import edu.kit.iti.formal.automation.st0.TransformationState import edu.kit.iti.formal.automation.st0.trans.* import java.io.File import java.io.PrintWriter fun main(args: Array<String>) = AbstractIntEqSfcApp().main(args) /** * * @author Alexander Weigl * @version 1 (20.11.18) */ class AbstractIntEqSfcApp : CliktCommand() { val sfcName by option("--name", "-n", metavar = "IDENTIFIER", help = "name of the SFC") .default("Crane") val leftFile by option("--left", "-l") .file() .required() val rightFile by option("--right", "-r") .file() .required() val output: File by option("--output").file().default(File("output.dot")) override fun run() { AbstractIntEqSfc(sfcName, leftFile, rightFile, output).run() } } class AbstractIntEqSfc(val sfcName: String, val leftFile: File, val rightFile: File, val outputFile: File) : Runnable { override fun run() { val leftSfc = getSfc(leftFile) val rightSfc = getSfc(rightFile) val diffSfc = ConstructDifferenceSfc(leftSfc, rightSfc, true).call() val analyzer = AbstractInterpretationSfc(diffSfc, leftSfc.scope, rightSfc.scope) analyzer.run() outputFile.bufferedWriter().use { diffSfc.toDot(PrintWriter(it)) } //view(diffSfc) } private fun getSfc(file: File): FunctionBlockDeclaration { val pous = IEC61131Facade.file(file, true) pous.addAll(BuiltinLoader.loadDefault()) IEC61131Facade.resolveDataTypes(pous) val sfc = pous.find { it.name == sfcName } ?: throw IllegalArgumentException("The given POU name '$sfcName' was not found in $file. " + "Found: ${pous.map { it.name }}") val network = (sfc as? PouExecutable)?.sfcBody ?: throw IllegalArgumentException("The given POU is not an SFC in $file.") val fb = sfc as? FunctionBlockDeclaration ?: throw IllegalArgumentException("Only Function Blocks are supported.") val ce = MultiCodeTransformation(TimerSimplifier(), ActionEmbedder(), FBEmbeddVariables(), EMBEDDING_BODY_PIPELINE) fb.actions.forEach { act -> val state = TransformationState(fb.scope, act.stBody!!) val nState = ce.transform(state) act.stBody = nState.stBody } FBRemoveInstance().transform(TransformationState(fb)) return fb } }
gpl-3.0
f4027e657cd591a7e823af3bb527a8a0
35.218391
123
0.653016
4.043646
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/dsl/components/LiftComponent.kt
1
3026
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.dsl.components import com.almasb.fxgl.dsl.FXGL import com.almasb.fxgl.entity.component.Component import com.almasb.fxgl.time.LocalTimer import javafx.util.Duration /** * Moves the entity up/down and/or left/right. * * @author Almas Baimagambetov (AlmasB) ([email protected]) */ class LiftComponent @JvmOverloads constructor(timer: LocalTimer = FXGL.newLocalTimer()) : Component() { private val liftDataX = LiftData(timer) private val liftDataY = LiftData(timer) var isGoingRight: Boolean get() = liftDataX.isGoingPositive set(value) { liftDataX.isGoingPositive = value } var isGoingUp: Boolean get() = !liftDataY.isGoingPositive set(value) { liftDataY.isGoingPositive = !value } override fun onAdded() { liftDataX.initTimer() liftDataY.initTimer() } override fun onUpdate(tpf: Double) { var dx = 0.0 var dy = 0.0 if (liftDataX.isOn) { dx = liftDataX.update(tpf) } if (liftDataY.isOn) { dy = liftDataY.update(tpf) } entity.translate(dx, dy) } fun xAxisDistanceDuration(distance: Double, duration: Duration) = this.apply { liftDataX.enable(distance, duration, distance / duration.toSeconds()) } fun xAxisSpeedDuration(speed: Double, duration: Duration) = this.apply { liftDataX.enable(speed * duration.toSeconds(), duration, speed) } fun xAxisSpeedDistance(speed: Double, distance: Double) = this.apply { liftDataX.enable(distance, Duration.seconds(distance / speed), speed) } fun yAxisDistanceDuration(distance: Double, duration: Duration) = this.apply { liftDataY.enable(distance, duration, distance / duration.toSeconds()) } fun yAxisSpeedDuration(speed: Double, duration: Duration) = this.apply { liftDataY.enable(speed * duration.toSeconds(), duration, speed) } fun yAxisSpeedDistance(speed: Double, distance: Double) = this.apply { liftDataY.enable(distance, Duration.seconds(distance / speed), speed) } override fun isComponentInjectionRequired(): Boolean = false } private class LiftData(val timer: LocalTimer) { var isOn = false // moving in the direction of the axis var isGoingPositive = true var distance = 0.0 var duration: Duration = Duration.ZERO var speed = 0.0 fun initTimer() { timer.capture() } fun enable(distance: Double, duration: Duration, speed: Double) { this.distance = distance this.duration = duration this.speed = speed isOn = true } fun update(tpf: Double): Double { if (timer.elapsed(duration)) { isGoingPositive = !isGoingPositive timer.capture() } return if (isGoingPositive) speed * tpf else -speed * tpf } }
mit
a7b10090fc6ab7c7840073bc600e177b
26.518182
83
0.652677
3.950392
false
false
false
false
ajalt/clikt
clikt/src/commonTest/kotlin/com/github/ajalt/clikt/parameters/types/ChoiceTest.kt
1
8992
package com.github.ajalt.clikt.parameters.types import com.github.ajalt.clikt.core.BadParameterValue import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.multiple import com.github.ajalt.clikt.parameters.arguments.optional import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.testing.TestCommand import com.github.ajalt.clikt.testing.parse import io.kotest.assertions.throwables.shouldThrow import io.kotest.data.blocking.forAll import io.kotest.data.row import io.kotest.matchers.shouldBe import kotlin.js.JsName import kotlin.test.Test class ChoiceTypeTest { private enum class TestEnum { A, B } @Test @JsName("choice_option_strings") fun `choice option strings`() { class C : TestCommand() { val x by option("-x", "--xx").choice("foo", "bar") } C().apply { parse("-xfoo") x shouldBe "foo" } C().apply { parse("--xx=bar") x shouldBe "bar" } shouldThrow<BadParameterValue> { C().parse("--xx baz") } .message shouldBe "Invalid value for \"--xx\": invalid choice: baz. (choose from foo, bar)" shouldThrow<BadParameterValue> { C().parse("--xx FOO") } .message shouldBe "Invalid value for \"--xx\": invalid choice: FOO. (choose from foo, bar)" } @Test @JsName("choice_option_map") fun `choice option map`() { class C : TestCommand() { val x by option("-x", "--xx") .choice("foo" to 1, "bar" to 2) } C().apply { parse("-xfoo") x shouldBe 1 } C().apply { parse("--xx=bar") x shouldBe 2 } shouldThrow<BadParameterValue> { C().parse("-x baz") } .message shouldBe "Invalid value for \"-x\": invalid choice: baz. (choose from foo, bar)" shouldThrow<BadParameterValue> { C().parse("--xx=baz") } .message shouldBe "Invalid value for \"--xx\": invalid choice: baz. (choose from foo, bar)" shouldThrow<BadParameterValue> { C().parse("-x FOO") } .message shouldBe "Invalid value for \"-x\": invalid choice: FOO. (choose from foo, bar)" } @Test @JsName("choice_option_insensitive") fun `choice option insensitive`() { class C : TestCommand() { val x by option("-x").choice("foo", "bar", ignoreCase = true) val y by option("-y").choice("foo" to 1, "bar" to 2, ignoreCase = true) } C().apply { parse("-xFOO -yFOO") x shouldBe "foo" y shouldBe 1 } C().apply { parse("-xbar -ybAR") x shouldBe "bar" y shouldBe 2 } shouldThrow<BadParameterValue> { C().parse("-xbaz") } .message shouldBe "Invalid value for \"-x\": invalid choice: baz. (choose from foo, bar)" } @Test @JsName("choice_argument_strings") fun `choice argument strings`() { class C : TestCommand() { val x by argument().choice("foo", "bar") override fun run_() { registeredArguments()[0].name shouldBe "X" } } C().apply { parse("foo") x shouldBe "foo" } C().apply { parse("bar") x shouldBe "bar" } shouldThrow<BadParameterValue> { C().parse("baz") } .message shouldBe "Invalid value for \"X\": invalid choice: baz. (choose from foo, bar)" shouldThrow<BadParameterValue> { C().parse("FOO") } .message shouldBe "Invalid value for \"X\": invalid choice: FOO. (choose from foo, bar)" } @Test @JsName("choice_argument_map") fun `choice argument map`() { class C : TestCommand() { val x by argument().choice("foo" to 1, "bar" to 2) override fun run_() { registeredArguments()[0].name shouldBe "X" } } C().apply { parse("foo") x shouldBe 1 } C().apply { parse("bar") x shouldBe 2 } shouldThrow<BadParameterValue> { C().parse("baz") } .message shouldBe "Invalid value for \"X\": invalid choice: baz. (choose from foo, bar)" shouldThrow<BadParameterValue> { C().parse("FOO") } .message shouldBe "Invalid value for \"X\": invalid choice: FOO. (choose from foo, bar)" } @Test @JsName("choice_argument_insensitive") fun `choice argument insensitive`() { class C : TestCommand() { val x by argument().choice("foo", "bar", ignoreCase = true) val y by argument().choice("foo" to 1, "bar" to 2, ignoreCase = true) } C().apply { parse("FOO FOO") x shouldBe "foo" y shouldBe 1 } C().apply { parse("bar bAR") x shouldBe "bar" y shouldBe 2 } shouldThrow<BadParameterValue> { C().parse("baz qux") } .message shouldBe "Invalid value for \"X\": invalid choice: baz. (choose from foo, bar)" } @Test @JsName("enum_option") fun `enum option`() = forAll( row("", null), row("--xx A", TestEnum.A), row("--xx a", TestEnum.A), row("--xx=A", TestEnum.A), row("-xB", TestEnum.B), row("-xb", TestEnum.B) ) { argv, expected -> class C : TestCommand() { val x by option("-x", "--xx").enum<TestEnum>() override fun run_() { x shouldBe expected } } C().parse(argv) } @Test @JsName("enum_option_key") fun `enum option key`() = forAll( row("", null), row("-xAz", TestEnum.A), row("-xaZ", TestEnum.A), row("-xBz", TestEnum.B), row("-xBZ", TestEnum.B) ) { argv, expected -> class C : TestCommand() { val x by option("-x").enum<TestEnum> { it.name + "z" } override fun run_() { x shouldBe expected } } C().parse(argv) } @Test @JsName("enum_option_error") fun `enum option error`() { @Suppress("unused") class C : TestCommand() { val foo by option().enum<TestEnum>(ignoreCase = false) } shouldThrow<BadParameterValue> { C().parse("--foo bar") } .message shouldBe "Invalid value for \"--foo\": invalid choice: bar. (choose from A, B)" shouldThrow<BadParameterValue> { C().parse("--foo a") } .message shouldBe "Invalid value for \"--foo\": invalid choice: a. (choose from A, B)" } @Test @JsName("enum_option_with_default") fun `enum option with default`() = forAll( row("", TestEnum.B), row("--xx A", TestEnum.A), row("--xx=A", TestEnum.A), row("-xA", TestEnum.A) ) { argv, expected -> class C : TestCommand() { val x by option("-x", "--xx").enum<TestEnum>().default(TestEnum.B) override fun run_() { x shouldBe expected } } C().parse(argv) } @Test @JsName("enum_argument") fun `enum argument`() = forAll( row("", null, emptyList()), row("A", TestEnum.A, emptyList()), row("b", TestEnum.B, emptyList()), row("A a B", TestEnum.A, listOf(TestEnum.A, TestEnum.B)) ) { argv, ex, ey -> class C : TestCommand() { val x by argument().enum<TestEnum>().optional() val y by argument().enum<TestEnum>().multiple() override fun run_() { x shouldBe ex y shouldBe ey } } C().parse(argv) } @Test @JsName("enum_argument_key") fun `enum argument key`() = forAll( row("", emptyList()), row("az", listOf(TestEnum.A)), row("AZ", listOf(TestEnum.A)), row("aZ Bz", listOf(TestEnum.A, TestEnum.B)) ) { argv, ex -> class C : TestCommand() { val x by argument().enum<TestEnum> { it.name + "z" }.multiple() override fun run_() { x shouldBe ex } } C().parse(argv) } @Test @JsName("enum_argument_error") fun `enum argument error`() { @Suppress("unused") class C : TestCommand() { val foo by argument().enum<TestEnum>(ignoreCase = false) } shouldThrow<BadParameterValue> { C().parse("bar") } .message shouldBe "Invalid value for \"FOO\": invalid choice: bar. (choose from A, B)" shouldThrow<BadParameterValue> { C().parse("a") } .message shouldBe "Invalid value for \"FOO\": invalid choice: a. (choose from A, B)" } }
apache-2.0
aa22f38f3b1f80dab2217641637dda47
29.174497
103
0.524244
4.215659
false
true
false
false
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/basicsknowledge/19.TryCatchExample.kt
1
656
package com.zj.example.kotlin.basicsknowledge /** * * CreateTime: 17/9/14 08:47 * @author 郑炯 */ fun main(vararg args: String) { try { var a = args[0].toInt() var b = args[1].toInt() a / b } catch (e: ArrayIndexOutOfBoundsException) { println("请输入一个两个整数") } finally { println("finaly") } /** * 把try catch当成表达式来使用 */ var result = try { 0 / 0 } catch (e: ArithmeticException) { 0//返回值0 } finally { //注意finally是不会返回值的 1 } println("result=$result")//输出result=0 }
mit
1c2e00853e5085ebaa06dccba0f1dcfe
16.848485
49
0.52381
3.438596
false
false
false
false
danirod/rectball
app/src/main/java/es/danirod/rectball/scene2d/ui/StatsTable.kt
1
8751
/* * This file is part of Rectball * Copyright (C) 2015-2017 Dani Rodríguez * * 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 es.danirod.rectball.scene2d.ui import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.scenes.scene2d.ui.Image import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle import com.badlogic.gdx.scenes.scene2d.ui.Table import com.badlogic.gdx.utils.Align import es.danirod.rectball.RectballGame import es.danirod.rectball.android.R import es.danirod.rectball.android.settings.SettingsManager import java.util.* class StatsTable(private val game: RectballGame, private val title: LabelStyle, private val data: LabelStyle) : Table() { private val context = game.context init { defaults().padBottom(30f).padRight(10f) add(addBestScores()).fillX().expandX().row() add(addTotalData()).fillX().expandX().row() add(addColorData()).fillX().expandX().row() add(addSizesData()).fillX().expandX().row() } private fun addBestScores(): Table { val best = Table() best.add(Label(context.getString(R.string.statistics_best_data), this.title)).colspan(2).row() if (game.context.settings.preferences.getLong(SettingsManager.TAG_HIGH_SCORE, 0L) == 0L && game.context.settings.preferences.getLong(SettingsManager.TAG_HIGH_TIME, 0L) == 0L) { val noData = Label(context.getString(R.string.statistics_no_data), game.skin) noData.setAlignment(Align.center) best.add(noData).colspan(2).fillX().expandX().padTop(10f).padBottom(10f).row() return best } val highScore = game.context.settings.preferences.getLong(SettingsManager.TAG_HIGH_SCORE, 0L) if (highScore > 0) append(best, context.getString(R.string.statistics_best_score), highScore.toString()) val highTime = game.context.settings.preferences.getLong(SettingsManager.TAG_HIGH_TIME, 0L) if (highTime > 0) append(best, context.getString(R.string.statistics_best_time), secondsToTime(highTime)) return best } private fun addTotalData(): Table { val total = Table() total.add(Label(context.getString(R.string.statistics_total), title)).colspan(2).row() val data = totalStatistics if (data.isEmpty()) { val noData = Label(context.getString(R.string.statistics_no_data), game.skin) noData.setAlignment(Align.center) total.add(noData).colspan(2).fillX().expandX().padTop(10f).padBottom(10f).row() } else { data.forEach { (key, value) -> if (value > 0) append(total, key, value.toString()) } } return total } private fun addColorData(): Table { val color = Table() val stats = sortStatsMap(colorStatistics) if (stats.isEmpty()) { color.add(Label(context.getString(R.string.statistics_color), title)).row() val noData = Label(context.getString(R.string.statistics_no_data), game.skin) noData.setAlignment(Align.center) color.add(noData).fillX().expandX().padTop(10f).padBottom(10f).row() } else { color.add(Label(context.getString(R.string.statistics_color), title)).colspan(stats.size).row() color.defaults().expandX().fillX().align(Align.center).size(60f).padTop(5f) for ((key, _) in stats) { color.add(Image(game.ballAtlas.findRegion("ball_$key"))) } color.row() for ((_, value) in stats) { val label = Label(value.toString(), data) label.setAlignment(Align.center) color.add(label) } color.row() } return color } private fun addSizesData(): Table { val sizes = Table() val stats = sortStatsMap(sizesStatistics) sizes.add(Label(context.getString(R.string.statistics_sizes), this.title)).colspan(3).row() /* No data. */ if (stats.isEmpty()) { val noData = Label(context.getString(R.string.statistics_no_data), game.skin) noData.setAlignment(Align.center) sizes.add(noData).colspan(3).fillX().expandX().padTop(10f).padBottom(10f).row() return sizes } val bar = game.skin.newDrawable("pixel", Color.WHITE) // Highest value is used to calculate the relative percentage of each row. val highestValue = stats.values.maxOrNull() ?: 0 for ((key, value) in stats) { val percentage = value.toFloat() / highestValue sizes.add(Label(key, data)).align(Align.left).fillX() sizes.add(Label(value.toString(), data)).align(Align.right).padRight(10f).expandX() sizes.add(Image(bar)).width(240 * percentage).padLeft(240 * (1 - percentage)).padBottom(5f).fill().row() } return sizes } /** A map that pairs an statistic label into the value for that statistic label. */ private val totalStatistics: Map<String, Long> get() = mapOf( context.getString(R.string.statistics_total_score) to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_SCORE, 0L), context.getString(R.string.statistics_total_combinations) to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_COMBINATIONS, 0L), context.getString(R.string.statistics_total_balls) to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_BALLS, 0L), context.getString(R.string.statistics_total_games) to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_GAMES, 0L), context.getString(R.string.statistics_best_time) to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_TIME, 0L), context.getString(R.string.statistics_total_perfect) to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_PERFECTS, 0L), context.getString(R.string.statistics_total_hints) to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_HINTS, 0L) ).filterValues { it > 0 } /** A map that pairs a color to the number of times a combination of that color was made. */ private val colorStatistics: Map<String, Long> get() = mapOf( "red" to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_COLOR_RED, 0L), "green" to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_COLOR_GREEN, 0L), "blue" to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_COLOR_BLUE, 0L), "yellow" to game.context.settings.preferences.getLong(SettingsManager.TAG_TOTAL_COLOR_YELLOW, 0L) ).filterValues { it > 0 } /** A map that pairs a combination size ("2x3", "3x4"...) to the number of times that combination was made. */ private val sizesStatistics: Map<String, Long> get() = game.context.settings.sizeStatistics /** Converts the decimal [seconds] number of seconds to a sexagesimal value. */ private fun secondsToTime(seconds: Long): String { val hrs = seconds / 3600 val min = seconds % 3600 / 60 val sec = seconds % 3600 % 60 return when { hrs != 0L -> String.format(Locale.getDefault(), "%d:%02d:%02d", hrs, min, sec) min != 0L -> String.format(Locale.getDefault(), "%d:%02d", min, sec) else -> String.format(Locale.getDefault(), "%d", sec) } } /** Sorts a [statistics] map by score, highest scores come first. */ private fun sortStatsMap(statistics: Map<String, Long>): Map<String, Long> = statistics.toList().sortedBy { it.second }.reversed().toMap() /** Appends a statistic composed by the label [name] and the value [value] to a [table]. */ private fun append(table: Table, name: String, value: String) { table.add(Label(name, data)).align(Align.left).fillX() table.add(Label(value, data)).align(Align.right).expandX().row() } }
gpl-3.0
ba2a10bb53c9da3f03bb285c193e52b4
47.076923
163
0.658057
3.899287
false
false
false
false
BracketCove/PosTrainer
app/src/test/java/com/bracketcove/postrainer/TestData.kt
1
451
package com.bracketcove.postrainer import com.wiseassblog.domain.domainmodel.Reminder internal fun getReminder( id: String? = "8675309", title: String = "Lunch Break", active: Boolean = true, vibrateOnly: Boolean = false, renewAutomatically: Boolean = false, hourOfDay: Int = 12, minuteOfDay: Int = 30 ) = Reminder( id, title, active, vibrateOnly, renewAutomatically, hourOfDay, minuteOfDay )
apache-2.0
972806b7d18d0c875c43b59bcb5617c5
20.47619
50
0.674058
3.95614
false
false
false
false
square/kotlinpoet
interop/ksp/src/main/kotlin/com/squareup/kotlinpoet/ksp/utils.kt
1
2119
/* * Copyright (C) 2021 Square, 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.kotlinpoet.ksp import com.google.devtools.ksp.isLocal import com.google.devtools.ksp.symbol.KSDeclaration import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.LambdaTypeName import com.squareup.kotlinpoet.ParameterizedTypeName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName internal fun TypeName.rawType(): ClassName { return findRawType() ?: throw IllegalArgumentException("Cannot get raw type from $this") } internal fun TypeName.findRawType(): ClassName? { return when (this) { is ClassName -> this is ParameterizedTypeName -> rawType is LambdaTypeName -> { var count = parameters.size if (receiver != null) { count++ } val functionSimpleName = if (count >= 23) { "FunctionN" } else { "Function$count" } ClassName("kotlin.jvm.functions", functionSimpleName) } else -> null } } internal fun ClassName.withTypeArguments(arguments: List<TypeName>): TypeName { return if (arguments.isEmpty()) { this } else { this.parameterizedBy(arguments) } } internal fun KSDeclaration.toClassNameInternal(): ClassName { require(!isLocal()) { "Local/anonymous classes are not supported!" } val pkgName = packageName.asString() val typesString = checkNotNull(qualifiedName).asString().removePrefix("$pkgName.") val simpleNames = typesString .split(".") return ClassName(pkgName, simpleNames) }
apache-2.0
e2d1fc282b3fe420d9e3a3722ab3ac4e
30.161765
90
0.72487
4.433054
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/correios/CorreiosClient.kt
1
2445
package net.perfectdreams.loritta.cinnamon.discord.utils.correios import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.content.* import io.ktor.http.* import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import net.perfectdreams.loritta.cinnamon.discord.utils.correios.entities.CorreiosResponse import net.perfectdreams.loritta.cinnamon.discord.utils.correios.exceptions.InvalidTrackingIdException import net.perfectdreams.loritta.common.utils.JsonIgnoreUnknownKeys import java.io.Closeable class CorreiosClient : Closeable { companion object { val CORREIOS_PACKAGE_REGEX = Regex("[A-Z]{2}[0-9]{9}[A-Z]{2}") } val http = HttpClient { expectSuccess = false } /** * Gets package tracking information about the [trackingIds] * * @param trackingIds list of tracking IDs, Correios doesn't seem to limit how many packages you can track at the same time * @return the request response * @throws InvalidTrackingIdException if any of the [trackingIds] do not match the [CORREIOS_PACKAGE_REGEX] RegEx */ suspend fun getPackageInfo(vararg trackingIds: String): CorreiosResponse { // Validate tracking IDs for (trackingId in trackingIds) if (!trackingId.matches(CORREIOS_PACKAGE_REGEX)) throw InvalidTrackingIdException(trackingId) // Eu encontrei a API REST do Correios usando engenharia reversa(tm) no SRO Mobile val httpResponse = http.post("http://webservice.correios.com.br/service/rest/rastro/rastroMobile") { userAgent("Dalvik/2.1.0 (Linux; U; Android 7.1.2; MotoG3-TE Build/NJH47B)") accept(ContentType.Application.Json) // Não importa qual é o usuário/senha/token, ele sempre retorna algo válido setBody( TextContent( "<rastroObjeto><usuario>LorittaBot</usuario><senha>LorittaSuperFofa</senha><tipo>L</tipo><resultado>T</resultado>${trackingIds.joinToString(prefix = "<objetos>", postfix = "</objetos>", separator = "")}<lingua>101</lingua><token>Loritta-Discord</token></rastroObjeto>", ContentType.Application.Xml ) ) } val r = httpResponse.bodyAsText() return JsonIgnoreUnknownKeys.decodeFromString(r) } override fun close() { http.close() } }
agpl-3.0
c3616661455a2b61fdc53ab807044aad
41.103448
289
0.690291
3.982055
false
false
false
false
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/extensions/VectorHex.kt
1
409
package xyz.jmullin.drifter.extensions import xyz.jmullin.drifter.geometry.VectorHex /** * Convenience methods for [[VectorHex]]s. */ fun Vh(q: Float, r: Float, s: Float) = VectorHex(q, r, s) fun Vh(q: Int, r: Int, s: Int) = VectorHex(q, r, s) fun Vh(q: Float, s: Float) = VectorHex(q, s) fun Vh(q: Int, s: Int) = VectorHex(q, s) fun Vho(x: Int, y: Int) = VectorHex(x.toFloat(), y - (x + (x and 1)) / 2f)
mit
65eafdde9217ab11e73fd30031e7af08
33.166667
75
0.638142
2.55625
false
false
false
false
owntracks/android
project/app/src/main/java/org/owntracks/android/ui/preferences/ExperimentalFragment.kt
1
1453
package org.owntracks.android.ui.preferences import android.os.Bundle import androidx.preference.SwitchPreferenceCompat import dagger.hilt.android.AndroidEntryPoint import org.owntracks.android.R import org.owntracks.android.support.Preferences.Companion.EXPERIMENTAL_FEATURES import javax.inject.Inject @AndroidEntryPoint class ExperimentalFragment @Inject constructor() : AbstractPreferenceFragment() { override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) { super.onCreatePreferencesFix(savedInstanceState, rootKey) setPreferencesFromResource(R.xml.preferences_experimental, rootKey) EXPERIMENTAL_FEATURES.forEach { feature -> SwitchPreferenceCompat(requireContext()).apply { title = feature isChecked = preferences.isExperimentalFeatureEnabled(feature) isIconSpaceReserved = false setOnPreferenceClickListener { val newFeatures = preferences.experimentalFeatures.toMutableSet() if ((it as SwitchPreferenceCompat).isChecked) { newFeatures.add(feature) } else { newFeatures.remove(feature) } preferences.experimentalFeatures = newFeatures true } preferenceScreen.addPreference(this) } } } }
epl-1.0
816e8d7c517204a2d3a44ee181ccb2d2
40.514286
88
0.65382
6.15678
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/global_search/CatalogueSearchPresenter.kt
2
8016
package eu.kanade.tachiyomi.ui.catalogue.global_search import android.os.Bundle import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.LoginSource import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import eu.kanade.tachiyomi.ui.catalogue.browse.BrowseCataloguePresenter import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subjects.PublishSubject import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * Presenter of [CatalogueSearchController] * Function calls should be done from here. UI calls should be done from the controller. * * @param sourceManager manages the different sources. * @param db manages the database calls. * @param preferencesHelper manages the preference calls. */ open class CatalogueSearchPresenter( val initialQuery: String? = "", val sourceManager: SourceManager = Injekt.get(), val db: DatabaseHelper = Injekt.get(), val preferencesHelper: PreferencesHelper = Injekt.get() ) : BasePresenter<CatalogueSearchController>() { /** * Enabled sources. */ val sources by lazy { getEnabledSources() } /** * Query from the view. */ var query = "" private set /** * Fetches the different sources by user settings. */ private var fetchSourcesSubscription: Subscription? = null /** * Subject which fetches image of given manga. */ private val fetchImageSubject = PublishSubject.create<Pair<List<Manga>, Source>>() /** * Subscription for fetching images of manga. */ private var fetchImageSubscription: Subscription? = null override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) // Perform a search with previous or initial state search(savedState?.getString(BrowseCataloguePresenter::query.name) ?: initialQuery.orEmpty()) } override fun onDestroy() { fetchSourcesSubscription?.unsubscribe() fetchImageSubscription?.unsubscribe() super.onDestroy() } override fun onSave(state: Bundle) { state.putString(BrowseCataloguePresenter::query.name, query) super.onSave(state) } /** * Returns a list of enabled sources ordered by language and name. * * @return list containing enabled sources. */ protected open fun getEnabledSources(): List<CatalogueSource> { val languages = preferencesHelper.enabledLanguages().getOrDefault() val hiddenCatalogues = preferencesHelper.hiddenCatalogues().getOrDefault() return sourceManager.getCatalogueSources() .filter { it.lang in languages } .filterNot { it is LoginSource && !it.isLogged() } .filterNot { it.id.toString() in hiddenCatalogues } .sortedBy { "(${it.lang}) ${it.name}" } } /** * Initiates a search for mnaga per catalogue. * * @param query query on which to search. */ fun search(query: String) { // Return if there's nothing to do if (this.query == query) return // Update query this.query = query // Create image fetch subscription initializeFetchImageSubscription() // Create items with the initial state val initialItems = sources.map { CatalogueSearchItem(it, null) } var items = initialItems fetchSourcesSubscription?.unsubscribe() fetchSourcesSubscription = Observable.from(sources) .flatMap({ source -> source.fetchSearchManga(1, query, FilterList()) .subscribeOn(Schedulers.io()) .onExceptionResumeNext(Observable.empty()) // Ignore timeouts. .map { it.mangas.take(10) } // Get at most 10 manga from search result. .map { it.map { networkToLocalManga(it, source.id) } } // Convert to local manga. .doOnNext { fetchImage(it, source) } // Load manga covers. .map { CatalogueSearchItem(source, it.map { CatalogueSearchCardItem(it) }) } }, 5) .observeOn(AndroidSchedulers.mainThread()) // Update matching source with the obtained results .map { result -> items.map { item -> if (item.source == result.source) result else item } } // Update current state .doOnNext { items = it } // Deliver initial state .startWith(initialItems) .subscribeLatestCache({ view, manga -> view.setItems(manga) }, { _, error -> Timber.e(error) }) } /** * Initialize a list of manga. * * @param manga the list of manga to initialize. */ private fun fetchImage(manga: List<Manga>, source: Source) { fetchImageSubject.onNext(Pair(manga, source)) } /** * Subscribes to the initializer of manga details and updates the view if needed. */ private fun initializeFetchImageSubscription() { fetchImageSubscription?.unsubscribe() fetchImageSubscription = fetchImageSubject.observeOn(Schedulers.io()) .flatMap { val source = it.second Observable.from(it.first).filter { it.thumbnail_url == null && !it.initialized } .map { Pair(it, source) } .concatMap { getMangaDetailsObservable(it.first, it.second) } .map { Pair(source as CatalogueSource, it) } } .onBackpressureBuffer() .observeOn(AndroidSchedulers.mainThread()) .subscribe({ (source, manga) -> @Suppress("DEPRECATION") view?.onMangaInitialized(source, manga) }, { error -> Timber.e(error) }) } /** * Returns an observable of manga that initializes the given manga. * * @param manga the manga to initialize. * @return an observable of the manga to initialize */ private fun getMangaDetailsObservable(manga: Manga, source: Source): Observable<Manga> { return source.fetchMangaDetails(manga) .flatMap { networkManga -> manga.copyFrom(networkManga) manga.initialized = true db.insertManga(manga).executeAsBlocking() Observable.just(manga) } .onErrorResumeNext { Observable.just(manga) } } /** * Returns a manga from the database for the given manga from network. It creates a new entry * if the manga is not yet in the database. * * @param sManga the manga from the source. * @return a manga from the database. */ private fun networkToLocalManga(sManga: SManga, sourceId: Long): Manga { var localManga = db.getManga(sManga.url, sourceId).executeAsBlocking() if (localManga == null) { val newManga = Manga.create(sManga.url, sManga.title, sourceId) newManga.copyFrom(sManga) val result = db.insertManga(newManga).executeAsBlocking() newManga.id = result.insertedId() localManga = newManga } return localManga } }
apache-2.0
2b32c8d1066994345b3b71408148c78e
36.288372
109
0.616517
4.945096
false
false
false
false
vanniktech/Emoji
generator/template/CategoryChunk.kt
1
889
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * 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.vanniktech.emoji.<%= package %>.category import com.vanniktech.emoji.<%= package %>.<%= name %> internal object <%= category %>CategoryChunk<%= index %> { internal val EMOJIS: List<<%= name %>> = listOf( <%= data %> ) }
apache-2.0
967fcd89a1d446b2074b1be243843fcb
34.48
78
0.704622
3.995495
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/jvmMain/kotlin/io/kotest/assertions/ErrorCollector.kt
1
1165
package io.kotest.assertions import java.util.Stack actual object ErrorCollector { private val clueContext = object : ThreadLocal<Stack<Any>>() { override fun initialValue(): Stack<Any> = Stack() } private val failures = object : ThreadLocal<MutableList<Throwable>>() { override fun initialValue(): MutableList<Throwable> = mutableListOf() } private val collectionMode = object : ThreadLocal<ErrorCollectionMode>() { override fun initialValue() = ErrorCollectionMode.Hard } actual fun setCollectionMode(mode: ErrorCollectionMode) = collectionMode.set(mode) actual fun getCollectionMode(): ErrorCollectionMode = collectionMode.get() actual fun pushClue(clue: Any) { clueContext.get().push(clue) } actual fun popClue() { clueContext.get().pop() } actual fun clueContext(): List<Any> = clueContext.get() actual fun errors(): List<Throwable> = failures.get().toList() /** * Adds the given error to the current context. */ actual fun pushError(t: Throwable) { failures.get().add(t) } /** * Clears all errors from the current context. */ actual fun clear() = failures.get().clear() }
apache-2.0
11c68a7c5f38b5e7b2be85effec5f01c
24.326087
84
0.696137
4.145907
false
false
false
false
Shynixn/PetBlocks
petblocks-bukkit-plugin/petblocks-bukkit-nms-108R3/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/service/Particle18R1ServiceImpl.kt
1
10525
@file:Suppress("UNCHECKED_CAST") package com.github.shynixn.petblocks.bukkit.logic.business.service import com.github.shynixn.petblocks.api.business.enumeration.ParticleType import com.github.shynixn.petblocks.api.business.enumeration.Version import com.github.shynixn.petblocks.api.business.service.ConfigurationService import com.github.shynixn.petblocks.api.business.service.LoggingService import com.github.shynixn.petblocks.api.business.service.ParticleService import com.github.shynixn.petblocks.api.persistence.entity.Particle import com.github.shynixn.petblocks.bukkit.logic.business.extension.sendPacket import com.google.inject.Inject import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.Material import org.bukkit.entity.Player import java.lang.reflect.Method import java.util.logging.Level /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class Particle18R1ServiceImpl @Inject constructor( private val logger: LoggingService, private val configurationService: ConfigurationService, private val version: Version ) : ParticleService { private val getIdFromMaterialMethod: Method = { Material::class.java.getDeclaredMethod("getId") }.invoke() /** * Plays the given [particle] at the given [location] for the given [player] or * all players in the world if the config option all alwaysVisible is enabled. */ override fun <L, P> playParticle(location: L, particle: Particle, player: P) { require(player is Player) { "Player has to be a BukkitPlayer!" } val canOtherPlayersSeeParticles = configurationService.findValue<Boolean>("global-configuration.particles-other-players") if (canOtherPlayersSeeParticles) { playParticle(location, particle, player.world.players) } else { playParticle(location, particle, listOf(player)) } } /** * Plays the given [particle] at the given [location] for the given [players]. */ private fun <L, P> playParticle(location: L, particle: Particle, players: Collection<P>) { require(location is Location) { "Location has to be a BukkitLocation!" } val partType = findParticleType(particle.typeName) if (partType == ParticleType.NONE) { return } val targets = (players as Collection<Player>).toTypedArray() if (partType == ParticleType.REDSTONE || partType == ParticleType.NOTE) { particle.amount = 0 particle.speed = 1.0f.toDouble() } val internalParticleType = getInternalEnumValue(partType) var additionalPayload: IntArray? = null if (particle.materialName != null) { additionalPayload = if (partType == ParticleType.ITEM_CRACK) { intArrayOf( getIdFromMaterialMethod.invoke(Material.getMaterial(particle.materialName!!)) as Int, particle.data ) } else if (particle.materialName!!.toIntOrNull() != null) { intArrayOf( particle.materialName!!.toInt(), (particle.data shl 12) ) } else { intArrayOf( getIdFromMaterialMethod.invoke(Material.getMaterial(particle.materialName!!)) as Int, (particle.data shl 12) ) } } val packet = if (partType == ParticleType.REDSTONE) { var red = particle.colorRed.toFloat() / 255.0F if (red <= 0) { red = Float.MIN_VALUE } val constructor = Class.forName( "net.minecraft.server.VERSION.PacketPlayOutWorldParticles".replace( "VERSION", version.bukkitId ) ) .getDeclaredConstructor( internalParticleType.javaClass, Boolean::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Int::class.javaPrimitiveType, IntArray::class.java ) constructor.newInstance( internalParticleType, isLongDistance(location, targets), location.x.toFloat(), location.y.toFloat(), location.z.toFloat(), red, particle.colorGreen.toFloat() / 255.0f, particle.colorBlue.toFloat() / 255.0f, particle.speed.toFloat(), particle.amount, additionalPayload ) } else { val constructor = Class.forName( "net.minecraft.server.VERSION.PacketPlayOutWorldParticles".replace( "VERSION", version.bukkitId ) ) .getDeclaredConstructor( internalParticleType.javaClass, Boolean::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Float::class.javaPrimitiveType, Int::class.javaPrimitiveType, IntArray::class.java ) constructor.newInstance( internalParticleType, isLongDistance(location, targets), location.x.toFloat(), location.y.toFloat(), location.z.toFloat(), particle.offSetX.toFloat(), particle.offSetY.toFloat(), particle.offSetZ.toFloat(), particle.speed.toFloat(), particle.amount, additionalPayload ) } try { players.forEach { p -> p.sendPacket(packet) } } catch (e: Exception) { Bukkit.getServer().logger.log(Level.WARNING, "Failed to send particle.", e) } } /** * Finds the version dependent class. */ private fun findClazz(name: String): Class<*> { return Class.forName(name.replace("VERSION", version.bukkitId)) } private fun isLongDistance(location: Location, players: Array<out Player>): Boolean { return players.any { location.world!!.name == it.location.world!!.name && it.location.distanceSquared(location) > 65536 } } /** * Finds the particle type. */ private fun findParticleType(item: String): ParticleType { ParticleType.values().forEach { p -> if (p.name == item || p.gameId_18 == item || p.gameId_113 == item || p.minecraftId_112 == item) { return p } } return ParticleType.NONE } private fun getInternalEnumValue(particle: ParticleType): Any { try { return when { version.isVersionLowerThan(Version.VERSION_1_13_R1) -> { val clazz = Class.forName("net.minecraft.server.VERSION.EnumParticle".replace("VERSION", version.bukkitId)) val method = clazz.getDeclaredMethod("valueOf", String::class.java) method.invoke(null, particle.name) } version == Version.VERSION_1_13_R1 -> { val minecraftKey = findClazz("net.minecraft.server.VERSION.MinecraftKey").getDeclaredConstructor(String::class.java) .newInstance(particle.gameId_113) val registry = findClazz("net.minecraft.server.VERSION.Particle").getDeclaredField("REGISTRY").get(null) findClazz("net.minecraft.server.VERSION.RegistryMaterials").getDeclaredMethod( "get", Any::class.java ).invoke(registry, minecraftKey) } else -> { val minecraftKey = findClazz("net.minecraft.server.VERSION.MinecraftKey").getDeclaredConstructor(String::class.java) .newInstance(particle.gameId_113) val registry = findClazz("net.minecraft.server.VERSION.IRegistry").getDeclaredField("PARTICLE_TYPE").get(null) findClazz("net.minecraft.server.VERSION.RegistryMaterials").getDeclaredMethod( "get", findClazz("net.minecraft.server.VERSION.MinecraftKey") ) .invoke(registry, minecraftKey) } } } catch (e: Exception) { logger.warn("Failed to load enum value.", e) throw RuntimeException(e) } } }
apache-2.0
c5a8c56a7a359a8a102e341115bf62d1
39.637066
129
0.584798
5.082086
false
false
false
false
square/leakcanary
leakcanary-android-instrumentation/src/main/java/leakcanary/internal/InstrumentationHeapAnalyzer.kt
2
3157
package leakcanary.internal import android.os.SystemClock import java.io.File import shark.ConstantMemoryMetricsDualSourceProvider import shark.FileSourceProvider import shark.HeapAnalysis import shark.HeapAnalysisException import shark.HeapAnalysisFailure import shark.HeapAnalysisSuccess import shark.HeapAnalyzer import shark.HprofHeapGraph import shark.HprofHeapGraph.Companion.openHeapGraph import shark.LeakingObjectFinder import shark.MetadataExtractor import shark.ObjectInspector import shark.OnAnalysisProgressListener import shark.ProguardMapping import shark.ReferenceMatcher import shark.SharkLog /** * Sets up [HeapAnalyzer] for instrumentation tests and delegates heap analysis. */ internal class InstrumentationHeapAnalyzer( val leakingObjectFinder: LeakingObjectFinder, val referenceMatchers: List<ReferenceMatcher>, val computeRetainedHeapSize: Boolean, val metadataExtractor: MetadataExtractor, val objectInspectors: List<ObjectInspector>, val proguardMapping: ProguardMapping? ) { fun analyze(heapDumpFile: File): HeapAnalysis { var lastStepUptimeMs = -1L val heapAnalyzer = HeapAnalyzer { newStep -> val now = SystemClock.uptimeMillis() val lastStepString = if (lastStepUptimeMs != -1L) { val lastStepDurationMs = now - lastStepUptimeMs val lastStep = OnAnalysisProgressListener.Step.values()[newStep.ordinal - 1] "${lastStep.humanReadableName} took $lastStepDurationMs ms, now " } else { "" } SharkLog.d { "${lastStepString}working on ${newStep.humanReadableName}" } lastStepUptimeMs = now } val sourceProvider = ConstantMemoryMetricsDualSourceProvider(FileSourceProvider(heapDumpFile)) val closeableGraph = try { sourceProvider.openHeapGraph(proguardMapping) } catch (throwable: Throwable) { return HeapAnalysisFailure( heapDumpFile = heapDumpFile, createdAtTimeMillis = System.currentTimeMillis(), analysisDurationMillis = 0, exception = HeapAnalysisException(throwable) ) } return closeableGraph .use { graph -> val result = heapAnalyzer.analyze( heapDumpFile = heapDumpFile, graph = graph, leakingObjectFinder = leakingObjectFinder, referenceMatchers = referenceMatchers, computeRetainedHeapSize = computeRetainedHeapSize, objectInspectors = objectInspectors, metadataExtractor = metadataExtractor ) if (result is HeapAnalysisSuccess) { val lruCacheStats = (graph as HprofHeapGraph).lruCacheStats() val randomAccessStats = "RandomAccess[" + "bytes=${sourceProvider.randomAccessByteReads}," + "reads=${sourceProvider.randomAccessReadCount}," + "travel=${sourceProvider.randomAccessByteTravel}," + "range=${sourceProvider.byteTravelRange}," + "size=${heapDumpFile.length()}" + "]" val stats = "$lruCacheStats $randomAccessStats" result.copy(metadata = result.metadata + ("Stats" to stats)) } else result } } }
apache-2.0
3c7cd5b80781ed37d5e736dffe908851
35.287356
98
0.711752
5.192434
false
false
false
false
diyaakanakry/Diyaa
ConvertDataType.kt
1
376
fun main(args:Array<String>){ var n1:Int=10 var n2:Int? var n2Str:String="12" n2=n2Str.toInt() var n2Float:Float? n2Float=n2Str.toFloat() println("n1:"+ n1) println("n2:"+ n2) println("n2Float:"+ n2Float.toString()) var xpi:Double=3.14 println("xpi:"+ xpi) var IntPi:Int=xpi.toInt() println("IntPi:"+ IntPi.toString()) }
unlicense
fe44d94f8887746392a9da80a81ad326
18.842105
43
0.598404
2.593103
false
false
false
false
xfournet/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/CreateMemberAction.kt
1
1282
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.annotator.intentions.elements import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.jvm.JvmClass import com.intellij.lang.jvm.actions.ActionRequest import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.createSmartPointer internal abstract class CreateMemberAction( target: PsiClass, protected open val request: ActionRequest ) : IntentionAction { private val myTargetPointer = target.createSmartPointer() override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean { return myTargetPointer.element != null && request.isValid } protected val target: PsiClass get() = requireNotNull(myTargetPointer.element) { "Don't access this property if isAvailable() returned false" } open fun getTarget(): JvmClass = target override fun getElementToMakeWritable(currentFile: PsiFile): PsiElement? = target override fun startInWriteAction(): Boolean = true }
apache-2.0
8aa35add00f277d466f15f2e7c834957
35.628571
140
0.790172
4.498246
false
false
false
false
ac-opensource/Matchmaking-App
app/src/main/java/com/youniversals/playupgo/main/MatchListAdapter.kt
1
3883
package com.youniversals.playupgo.main import android.content.Context import android.support.annotation.LayoutRes import android.text.format.DateUtils import android.util.AttributeSet import android.view.View import android.widget.LinearLayout import com.airbnb.epoxy.EpoxyAdapter import com.airbnb.epoxy.EpoxyModel import com.youniversals.playupgo.R import com.youniversals.playupgo.data.Match import kotlinx.android.synthetic.main.match_list_view_item.view.* /** * YOYO HOLDINGS * @author A-Ar Andrew Concepcion * @version * @since 28/12/2016 */ class MatchListAdapter(var onClickListener: View.OnClickListener) : EpoxyAdapter() { private var selectedPosition: Int = 0 init { // addModels(CreateMatchModel("My Photos")) } fun addMatches(matches: Collection<Match>?) { matches?.forEach { addModel(MatchModel(it, onClickListener)) } if (matches == null || matches.isEmpty()) { addModel(NoMatchFoundModel()) } addModel(AddMatchModel(onClickListener)) } } class MatchModel(private val match: Match, private val onClickListener: View.OnClickListener) : EpoxyModel<MatchView>() { init { id(match.id) } @LayoutRes public override fun getDefaultLayout(): Int { return R.layout.match_model } override fun bind(matchView: MatchView?) { matchView?.data = match matchView?.title = match.title matchView?.date = DateUtils.getRelativeTimeSpanString(match.date, System.currentTimeMillis(), 0).toString() matchView?.distance = "" matchView?.setOnClickListener(onClickListener) } override fun unbind(sportView: MatchView?) { super.unbind(sportView) sportView?.setOnClickListener(null) } } class MatchView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) { var matchCard: View? = null var data: Match? = null var title: String? = null set(value) { field = value matchTitleTextView.text = value } var distance: String? = null set(value) { field = value distanceTextView.text = value } var date: String? = null set(value) { field = value matchDateTextView.text = value } init { init() } private fun init() { orientation = LinearLayout.VERTICAL View.inflate(context, R.layout.match_list_view_item, this) matchCard = matchCardView } fun clear() { } } class NoMatchFoundModel : EpoxyModel<NoMatchFoundView>() { init { id(0) } override fun getDefaultLayout(): Int { return R.layout.match_model_nothing_found } } class AddMatchModel(private val onClickListener: View.OnClickListener) : EpoxyModel<AddMatchView>() { init { id(1) } override fun getDefaultLayout(): Int { return R.layout.match_model_add_new } override fun bind(addMatchView: AddMatchView?) { addMatchView?.setOnClickListener(onClickListener) } override fun unbind(addMatchView: AddMatchView?) { super.unbind(addMatchView) addMatchView?.setOnClickListener(null) } } class NoMatchFoundView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) { init { init() } private fun init() { orientation = LinearLayout.VERTICAL View.inflate(context, R.layout.match_list_view_item_no_match_found, this) } fun clear() { } } class AddMatchView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) { init { init() } private fun init() { orientation = LinearLayout.VERTICAL View.inflate(context, R.layout.match_list_view_item_add_new_match, this) } fun clear() { } }
agpl-3.0
d31d2406eb98a879a541d0e4f0f0a399
22.676829
121
0.64615
4.161844
false
false
false
false
chris-wu2015/MoneyGiftAssistant
moneyGiftAssistant/src/main/java/com/alphago/moneypacket/utils/UpdateTask.kt
1
4194
//package com.alphago.moneypacket.utils // //import android.content.Context //import android.content.Intent //import android.content.pm.PackageInfo //import android.net.Uri //import android.os.AsyncTask //import android.widget.Toast //import org.apache.http.HttpResponse //import org.apache.http.StatusLine //import org.apache.http.client.HttpClient //import org.apache.http.client.methods.HttpGet //import org.apache.http.impl.client.DefaultHttpClient //import org.json.JSONObject //import com.alphago.moneypacket.R //import com.alphago.moneypacket.activities.SettingsActivity //import com.alphago.moneypacket.activities.WebViewActivity // //import java.io.ByteArrayOutputStream //import java.io.IOException // ///** // * Created by Zhongyi on 1/20/16. // * Util for app update task. // */ //class UpdateTask(private val context: Context, private val isUpdateOnRelease: Boolean) : AsyncTask<String, String, String>() { // // init { // if (this.isUpdateOnRelease) Toast.makeText(context, context.getString(R.string.checking_new_version), Toast.LENGTH_SHORT).show() // } // // override fun doInBackground(vararg uri: String): String? { // val httpclient = DefaultHttpClient() // val response: HttpResponse // var responseString: String? = null // try { // response = httpclient.execute(HttpGet(uri[0])) // val statusLine = response.getStatusLine() // if (statusLine.getStatusCode() === 200) { // val out = ByteArrayOutputStream() // response.getEntity().writeTo(out) // responseString = out.toString() // out.close() // } else { // // Close the connection. // response.getEntity().getContent().close() // throw IOException(statusLine.getReasonPhrase()) // } // } catch (e: Exception) { // return null // } // // return responseString // } // // override fun onPostExecute(result: String) { // super.onPostExecute(result) // try { // count += 1 // val release = JSONObject(result) // // // Get current version // val pInfo = context.packageManager.getPackageInfo(context.packageName, 0) // val version = pInfo.versionName // // val latestVersion = release.getString("tag_name") // val isPreRelease = release.getBoolean("prerelease") // if (!isPreRelease && version.compareTo(latestVersion, ignoreCase = true) >= 0) { // // Your version is ahead of or same as the latest. // if (this.isUpdateOnRelease) // Toast.makeText(context, R.string.update_already_latest, Toast.LENGTH_SHORT).show() // } else { // if (!isUpdateOnRelease) { // Toast.makeText(context, context.getString(R.string.update_new_seg1) + latestVersion + context.getString(R.string.update_new_seg3), Toast.LENGTH_LONG).show() // return // } // // Need update. // val downloadUrl = release.getJSONArray("assets").getJSONObject(0).getString("browser_download_url") // // // Give up on the fucking DownloadManager. The downloaded apk got renamed and unable to install. Fuck. // val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl)) // browserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK // context.startActivity(browserIntent) // Toast.makeText(context, context.getString(R.string.update_new_seg1) + latestVersion + context.getString(R.string.update_new_seg2), Toast.LENGTH_LONG).show() // } // } catch (e: Exception) { // e.printStackTrace() // if (this.isUpdateOnRelease) Toast.makeText(context, R.string.update_error, Toast.LENGTH_LONG).show() // } // // } // // fun update() { // super.execute(updateUrl) // } // // companion object { // var count = 0 // val updateUrl = "https://api.github.com/repos/geeeeeeeeek/WeChatLuckyMoney/releases/latest" // } //}
apache-2.0
7d3b567c6d24a44a2a117df23b8ec8ac
40.534653
178
0.612542
4.013397
false
true
false
false
weibaohui/korm
src/main/kotlin/com/sdibt/korm/core/reflect/TypeParameterResolver.kt
1
9553
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.sdibt.korm.core.reflect import java.lang.reflect.* class TypeParameterResolver { companion object { /** * @return The field type as [Type]. If it has type parameters in the declaration,<br></br> * * they will be resolved to the actual runtime [Type]s. */ fun resolveFieldType(field: Field, srcType: Type): Type { val fieldType = field.genericType val declaringClass = field.declaringClass return resolveType(fieldType, srcType, declaringClass) } /** * @return The return type of the method as [Type]. If it has type parameters in the declaration,<br></br> * * they will be resolved to the actual runtime [Type]s. */ fun resolveReturnType(method: Method, srcType: Type): Type { val returnType = method.genericReturnType val declaringClass = method.declaringClass return resolveType(returnType, srcType, declaringClass) } /** * @return The parameter types of the method as an array of [Type]s. If they have type parameters in the declaration,<br></br> * * they will be resolved to the actual runtime [Type]s. */ fun resolveParamTypes(method: Method, srcType: Type): Array<Type?> { val paramTypes = method.genericParameterTypes val declaringClass = method.declaringClass val result = arrayOfNulls<Type>(paramTypes.size) for (i in paramTypes.indices) { result[i] = resolveType(paramTypes[i], srcType, declaringClass) } return result } private fun resolveType(type: Type, srcType: Type, declaringClass: Class<*>): Type { if (type is TypeVariable<*>) { return resolveTypeVar(type, srcType, declaringClass) } else if (type is ParameterizedType) { return resolveParameterizedType(type, srcType, declaringClass) } else if (type is GenericArrayType) { return resolveGenericArrayType(type, srcType, declaringClass) } else { return type } } private fun resolveGenericArrayType(genericArrayType: GenericArrayType, srcType: Type, declaringClass: Class<*>): Type { val componentType = genericArrayType.genericComponentType var resolvedComponentType: Type? = null if (componentType is TypeVariable<*>) { resolvedComponentType = resolveTypeVar(componentType, srcType, declaringClass) } else if (componentType is GenericArrayType) { resolvedComponentType = resolveGenericArrayType(componentType, srcType, declaringClass) } else if (componentType is ParameterizedType) { resolvedComponentType = resolveParameterizedType(componentType, srcType, declaringClass) } if (resolvedComponentType is Class<*>) { return arrayOf(resolvedComponentType as Class<*>?, 0).javaClass } else { return GenericArrayTypeImpl(resolvedComponentType) } } private fun resolveParameterizedType(parameterizedType: ParameterizedType, srcType: Type, declaringClass: Class<*>): ParameterizedType { val rawType = parameterizedType.rawType as Class<*> val typeArgs = parameterizedType.actualTypeArguments val args = arrayOfNulls<Type>(typeArgs.size) for (i in typeArgs.indices) { if (typeArgs[i] is TypeVariable<*>) { args[i] = resolveTypeVar(typeArgs[i] as TypeVariable<*>, srcType, declaringClass) } else if (typeArgs[i] is ParameterizedType) { args[i] = resolveParameterizedType(typeArgs[i] as ParameterizedType, srcType, declaringClass) } else if (typeArgs[i] is WildcardType) { args[i] = resolveWildcardType(typeArgs[i] as WildcardType, srcType, declaringClass) } else { args[i] = typeArgs[i] } } return ParameterizedTypeImpl(rawType, null, args) } private fun resolveWildcardType(wildcardType: WildcardType, srcType: Type, declaringClass: Class<*>): Type { val lowerBounds = resolveWildcardTypeBounds(wildcardType.lowerBounds, srcType, declaringClass) val upperBounds = resolveWildcardTypeBounds(wildcardType.upperBounds, srcType, declaringClass) return WildcardTypeImpl(lowerBounds, upperBounds) } private fun resolveWildcardTypeBounds(bounds: Array<Type>, srcType: Type, declaringClass: Class<*>): Array<Type?> { val result = arrayOfNulls<Type>(bounds.size) for (i in bounds.indices) { if (bounds[i] is TypeVariable<*>) { result[i] = resolveTypeVar(bounds[i] as TypeVariable<*>, srcType, declaringClass) } else if (bounds[i] is ParameterizedType) { result[i] = resolveParameterizedType(bounds[i] as ParameterizedType, srcType, declaringClass) } else if (bounds[i] is WildcardType) { result[i] = resolveWildcardType(bounds[i] as WildcardType, srcType, declaringClass) } else { result[i] = bounds[i] } } return result } private fun resolveTypeVar(typeVar: TypeVariable<*>, srcType: Type, declaringClass: Class<*>): Type { var result: Type? = null var clazz: Class<*>? = null if (srcType is Class<*>) { clazz = srcType } else if (srcType is ParameterizedType) { clazz = srcType.rawType as Class<*> } else { throw IllegalArgumentException("The 2nd arg must be Class or ParameterizedType, but was: " + srcType.javaClass) } if (clazz == declaringClass) { val bounds = typeVar.bounds if (bounds.isNotEmpty()) { return bounds[0] } return Any::class.java } val superclass = clazz.genericSuperclass result = scanSuperTypes(typeVar, srcType, declaringClass, clazz, superclass) if (result != null) { return result } val superInterfaces = clazz.genericInterfaces for (superInterface in superInterfaces) { result = scanSuperTypes(typeVar, srcType, declaringClass, clazz, superInterface) if (result != null) { return result } } return Any::class.java } private fun scanSuperTypes(typeVar: TypeVariable<*>, srcType: Type, declaringClass: Class<*>, clazz: Class<*>, superclass: Type?): Type? { var result: Type? = null if (superclass is ParameterizedType) { val parentAsType = superclass val parentAsClass = parentAsType.rawType as Class<*> if (declaringClass == parentAsClass) { val typeArgs = parentAsType.actualTypeArguments val declaredTypeVars = declaringClass.typeParameters for (i in declaredTypeVars.indices) { if (declaredTypeVars[i] === typeVar) { if (typeArgs[i] is TypeVariable<*>) { val typeParams = clazz.typeParameters for (j in typeParams.indices) { if (typeParams[j] === typeArgs[i]) { if (srcType is ParameterizedType) { result = srcType.actualTypeArguments[j] } break } } } else { result = typeArgs[i] } } } } else if (declaringClass.isAssignableFrom(parentAsClass)) { result = resolveTypeVar(typeVar, parentAsType, declaringClass) } } else if (superclass is Class<*>) { if (declaringClass.isAssignableFrom(superclass)) { result = resolveTypeVar(typeVar, superclass, declaringClass) } } return result } } }
apache-2.0
a3432d8d6f2eec78bb88e88dad9f3c95
46.527363
146
0.571339
5.461978
false
false
false
false
yawkat/javap
server/src/main/kotlin/at/yawk/javap/Decompiler.kt
1
2580
/* * 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/. */ package at.yawk.javap import com.strobel.assembler.metadata.Buffer import com.strobel.assembler.metadata.ClassFileReader import com.strobel.assembler.metadata.IMetadataResolver import com.strobel.assembler.metadata.MetadataSystem import com.strobel.decompiler.DecompilerContext import com.strobel.decompiler.DecompilerSettings import com.strobel.decompiler.PlainTextOutput import com.strobel.decompiler.languages.java.BraceStyle import com.strobel.decompiler.languages.java.JavaFormattingOptions import com.strobel.decompiler.languages.java.ast.AstBuilder import java.nio.file.Files import java.nio.file.Path /** * @author yawkat */ enum class Decompiler { PROCYON { private val settings = DecompilerSettings() init { // this ensures correct initialization order - removing this line will lead to an Exception in procyon code // (try it) MetadataSystem.instance() settings.forceExplicitImports = true settings.showSyntheticMembers = true settings.javaFormattingOptions = JavaFormattingOptions.createDefault() settings.javaFormattingOptions.ClassBraceStyle = BraceStyle.EndOfLine settings.javaFormattingOptions.EnumBraceStyle = BraceStyle.EndOfLine } override fun decompile(classDir: Path): String { val ctx = DecompilerContext(settings) val astBuilder = AstBuilder(ctx) Files.newDirectoryStream(classDir).use { for (classFile in it.sorted()) { if (!classFile.toString().endsWith(".class")) continue val def = ClassFileReader.readClass( ClassFileReader.OPTION_PROCESS_ANNOTATIONS or ClassFileReader.OPTION_PROCESS_CODE, IMetadataResolver.EMPTY, Buffer(Files.readAllBytes(classFile)) ) astBuilder.addType(def) // only need this to avoid errors. would be better to decompile separately, but... TODO ctx.currentType = def } } val output = PlainTextOutput() astBuilder.generateCode(output) return output.toString() } }; @Throws(Exception::class) abstract fun decompile(classDir: Path): String }
mpl-2.0
4c91c3929e9b14a3bbbeb22089c9dcb7
38.707692
119
0.660853
4.690909
false
false
false
false
valich/intellij-markdown
src/commonMain/kotlin/org/intellij/markdown/parser/MarkdownParser.kt
1
3067
package org.intellij.markdown.parser import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.ast.ASTNodeBuilder import org.intellij.markdown.flavours.MarkdownFlavourDescriptor import org.intellij.markdown.flavours.gfm.GFMTokenTypes import org.intellij.markdown.parser.sequentialparsers.LexerBasedTokensCache import org.intellij.markdown.parser.sequentialparsers.SequentialParser import org.intellij.markdown.parser.sequentialparsers.SequentialParserUtil class MarkdownParser(private val flavour: MarkdownFlavourDescriptor) { fun buildMarkdownTreeFromString(text: String): ASTNode { return parse(MarkdownElementTypes.MARKDOWN_FILE, text, true) } fun parse(root: IElementType, text: String, parseInlines: Boolean = true): ASTNode { val productionHolder = ProductionHolder() val markerProcessor = flavour.markerProcessorFactory.createMarkerProcessor(productionHolder) val rootMarker = productionHolder.mark() val textHolder = LookaheadText(text) var pos: LookaheadText.Position? = textHolder.startPosition while (pos != null) { productionHolder.updatePosition(pos.offset) pos = markerProcessor.processPosition(pos) } productionHolder.updatePosition(text.length) markerProcessor.flushMarkers() rootMarker.done(root) val nodeBuilder: ASTNodeBuilder nodeBuilder = if (parseInlines) { InlineExpandingASTNodeBuilder(text) } else { ASTNodeBuilder(text) } val builder = MyRawBuilder(nodeBuilder) return builder.buildTree(productionHolder.production) } fun parseInline(root: IElementType, text: CharSequence, textStart: Int, textEnd: Int): ASTNode { val lexer = flavour.createInlinesLexer() lexer.start(text, textStart, textEnd) val tokensCache = LexerBasedTokensCache(lexer) val wholeRange = 0..tokensCache.filteredTokens.size val nodes = flavour.sequentialParserManager.runParsingSequence(tokensCache, SequentialParserUtil.filterBlockquotes(tokensCache, wholeRange)) return MyBuilder(ASTNodeBuilder(text), tokensCache). buildTree(nodes + listOf(SequentialParser.Node(wholeRange, root))) } private inner class InlineExpandingASTNodeBuilder(text: CharSequence) : ASTNodeBuilder(text) { override fun createLeafNodes(type: IElementType, startOffset: Int, endOffset: Int): List<ASTNode> { return when (type) { MarkdownElementTypes.PARAGRAPH, MarkdownTokenTypes.ATX_CONTENT, MarkdownTokenTypes.SETEXT_CONTENT, GFMTokenTypes.CELL -> listOf(parseInline(type, text, startOffset, endOffset)) else -> super.createLeafNodes(type, startOffset, endOffset) } } } }
apache-2.0
a641b18b0d8da31948af8345b8d6424a
38.831169
107
0.70851
4.986992
false
false
false
false
b95505017/android-architecture-components
PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/repository/inDb/SubredditBoundaryCallback.kt
1
4021
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.paging.pagingwithnetwork.reddit.repository.inDb import android.arch.paging.PagedList import android.arch.paging.PagingRequestHelper import android.support.annotation.MainThread import com.android.example.paging.pagingwithnetwork.reddit.api.RedditApi import com.android.example.paging.pagingwithnetwork.reddit.util.createStatusLiveData import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.concurrent.Executor /** * This boundary callback gets notified when user reaches to the edges of the list such that the * database cannot provide any more data. * <p> * The boundary callback might be called multiple times for the same direction so it does its own * rate limiting using the PagingRequestHelper class. */ class SubredditBoundaryCallback( private val subredditName: String, private val webservice: RedditApi, private val handleResponse: (String, RedditApi.ListingResponse?) -> Unit, private val ioExecutor: Executor, private val networkPageSize: Int) : PagedList.BoundaryCallback<RedditPost>() { val helper = PagingRequestHelper(ioExecutor) val networkState = helper.createStatusLiveData() /** * Database returned 0 items. We should query the backend for more items. */ @MainThread override fun onZeroItemsLoaded() { helper.runIfNotRunning(PagingRequestHelper.RequestType.INITIAL) { webservice.getTop( subreddit = subredditName, limit = networkPageSize) .enqueue(createWebserviceCallback(it)) } } /** * User reached to the end of the list. */ @MainThread override fun onItemAtEndLoaded(itemAtEnd: RedditPost) { helper.runIfNotRunning(PagingRequestHelper.RequestType.AFTER) { webservice.getTopAfter( subreddit = subredditName, after = itemAtEnd.name, limit = networkPageSize) .enqueue(createWebserviceCallback(it)) } } /** * every time it gets new items, boundary callback simply inserts them into the database and * paging library takes care of refreshing the list if necessary. */ private fun insertItemsIntoDb( response: Response<RedditApi.ListingResponse>, it: PagingRequestHelper.Request.Callback) { ioExecutor.execute { handleResponse(subredditName, response.body()) it.recordSuccess() } } override fun onItemAtFrontLoaded(itemAtFront: RedditPost) { // ignored, since we only ever append to what's in the DB } private fun createWebserviceCallback(it: PagingRequestHelper.Request.Callback) : Callback<RedditApi.ListingResponse> { return object : Callback<RedditApi.ListingResponse> { override fun onFailure( call: Call<RedditApi.ListingResponse>, t: Throwable) { it.recordFailure(t) } override fun onResponse( call: Call<RedditApi.ListingResponse>, response: Response<RedditApi.ListingResponse>) { insertItemsIntoDb(response, it) } } } }
apache-2.0
2cfac91089c0cbd4064c662ce0f3909f
36.240741
97
0.677195
4.909646
false
false
false
false
facebook/react-native
packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt
1
6424
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.tasks import com.facebook.react.utils.detectOSAwareHermesCommand import com.facebook.react.utils.moveTo import com.facebook.react.utils.windowsAwareCommandLine import java.io.File import org.gradle.api.DefaultTask import org.gradle.api.file.ConfigurableFileTree import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.* abstract class BundleHermesCTask : DefaultTask() { init { group = "react" } @get:Internal abstract val root: DirectoryProperty @get:InputFiles val sources: ConfigurableFileTree = project.fileTree(root) { it.include("**/*.js") it.include("**/*.jsx") it.include("**/*.ts") it.include("**/*.tsx") it.exclude("**/android/**/*") it.exclude("**/ios/**/*") it.exclude("**/build/**/*") it.exclude("**/node_modules/**/*") } @get:Input abstract val nodeExecutableAndArgs: ListProperty<String> @get:InputFile abstract val cliFile: RegularFileProperty @get:Internal abstract val reactNativeDir: DirectoryProperty @get:Input abstract val bundleCommand: Property<String> @get:InputFile abstract val entryFile: RegularFileProperty @get:InputFile @get:Optional abstract val bundleConfig: RegularFileProperty @get:Input abstract val bundleAssetName: Property<String> @get:Input abstract val minifyEnabled: Property<Boolean> @get:Input abstract val hermesEnabled: Property<Boolean> @get:Input abstract val devEnabled: Property<Boolean> @get:Input abstract val extraPackagerArgs: ListProperty<String> @get:Input abstract val hermesCommand: Property<String> @get:Input abstract val hermesFlags: ListProperty<String> @get:OutputDirectory abstract val jsBundleDir: DirectoryProperty @get:OutputDirectory abstract val resourcesDir: DirectoryProperty @get:OutputDirectory abstract val jsIntermediateSourceMapsDir: RegularFileProperty @get:OutputDirectory abstract val jsSourceMapsDir: DirectoryProperty @TaskAction fun run() { jsBundleDir.get().asFile.mkdirs() resourcesDir.get().asFile.mkdirs() jsIntermediateSourceMapsDir.get().asFile.mkdirs() jsSourceMapsDir.get().asFile.mkdirs() val bundleAssetFilename = bundleAssetName.get() val bundleFile = File(jsBundleDir.get().asFile, bundleAssetFilename) val packagerSourceMap = resolvePackagerSourceMapFile(bundleAssetFilename) val bundleCommand = getBundleCommand(bundleFile, packagerSourceMap) runCommand(bundleCommand) if (hermesEnabled.get()) { val detectedHermesCommand = detectOSAwareHermesCommand(root.get().asFile, hermesCommand.get()) val bytecodeFile = File("${bundleFile}.hbc") val outputSourceMap = resolveOutputSourceMap(bundleAssetFilename) val compilerSourceMap = resolveCompilerSourceMap(bundleAssetFilename) val hermesCommand = getHermescCommand(detectedHermesCommand, bytecodeFile, bundleFile) runCommand(hermesCommand) bytecodeFile.moveTo(bundleFile) if (hermesFlags.get().contains("-output-source-map")) { val hermesTempSourceMapFile = File("$bytecodeFile.map") hermesTempSourceMapFile.moveTo(compilerSourceMap) val reactNativeDir = reactNativeDir.get().asFile val composeScriptFile = File(reactNativeDir, "scripts/compose-source-maps.js") val composeSourceMapsCommand = getComposeSourceMapsCommand( composeScriptFile, packagerSourceMap, compilerSourceMap, outputSourceMap) runCommand(composeSourceMapsCommand) } } } internal fun resolvePackagerSourceMapFile(bundleAssetName: String) = if (hermesEnabled.get()) { File(jsIntermediateSourceMapsDir.get().asFile, "$bundleAssetName.packager.map") } else { resolveOutputSourceMap(bundleAssetName) } internal fun resolveOutputSourceMap(bundleAssetName: String) = File(jsSourceMapsDir.get().asFile, "$bundleAssetName.map") internal fun resolveCompilerSourceMap(bundleAssetName: String) = File(jsIntermediateSourceMapsDir.get().asFile, "$bundleAssetName.compiler.map") private fun runCommand(command: List<Any>) { project.exec { it.workingDir(root.get().asFile) it.commandLine(command) } } internal fun getBundleCommand(bundleFile: File, sourceMapFile: File): List<Any> = windowsAwareCommandLine( buildList { addAll(nodeExecutableAndArgs.get()) add(cliFile.get().asFile.absolutePath) add(bundleCommand.get()) add("--platform") add("android") add("--dev") add(devEnabled.get().toString()) add("--reset-cache") add("--entry-file") add(entryFile.get().asFile.toString()) add("--bundle-output") add(bundleFile.toString()) add("--assets-dest") add(resourcesDir.get().asFile.toString()) add("--sourcemap-output") add(sourceMapFile.toString()) if (bundleConfig.isPresent) { add("--config") add(bundleConfig.get().asFile.absolutePath) } add("--minify") add(minifyEnabled.get().toString()) addAll(extraPackagerArgs.get()) add("--verbose") }) internal fun getHermescCommand( hermesCommand: String, bytecodeFile: File, bundleFile: File ): List<Any> = windowsAwareCommandLine( hermesCommand, "-emit-binary", "-out", bytecodeFile.absolutePath, bundleFile.absolutePath, *hermesFlags.get().toTypedArray()) internal fun getComposeSourceMapsCommand( composeScript: File, packagerSourceMap: File, compilerSourceMap: File, outputSourceMap: File ): List<Any> = windowsAwareCommandLine( *nodeExecutableAndArgs.get().toTypedArray(), composeScript.absolutePath, packagerSourceMap.toString(), compilerSourceMap.toString(), "-o", outputSourceMap.toString()) }
mit
40f5be319d5df96e5ba64fd25d27864a
32.810526
100
0.687578
4.695906
false
false
false
false
openhab/openhab.android
mobile/src/main/java/org/openhab/habdroid/core/connection/DefaultConnection.kt
1
2396
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.core.connection import android.net.Network import android.util.Log import java.io.IOException import java.net.InetSocketAddress import java.net.Socket import java.net.SocketTimeoutException import kotlinx.coroutines.delay import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.OkHttpClient import org.openhab.habdroid.model.ServerPath import org.openhab.habdroid.util.bindToNetworkIfPossible open class DefaultConnection : AbstractConnection { internal var network: Network? = null internal constructor( httpClient: OkHttpClient, connectionType: Int, path: ServerPath ) : super(httpClient, connectionType, path) internal constructor(baseConnection: AbstractConnection, connectionType: Int) : super(baseConnection, connectionType) suspend fun isReachableViaNetwork(network: Network?): Boolean { Log.d(TAG, "Checking reachability of $baseUrl (via $network)") val url = baseUrl.toHttpUrl() val s = createConnectedSocket(InetSocketAddress(url.host, url.port), network) s?.close() return s != null } private suspend fun createConnectedSocket(socketAddress: InetSocketAddress, network: Network?): Socket? { val s = Socket() s.bindToNetworkIfPossible(network) var retries = 0 while (retries < 10) { try { s.connect(socketAddress, 1000) Log.d(TAG, "Socket connected (attempt $retries)") return s } catch (e: SocketTimeoutException) { Log.d(TAG, "Socket timeout after $retries retries") retries += 5 } catch (e: IOException) { Log.d(TAG, "Socket creation failed (attempt $retries)") delay(200) } retries++ } return null } override fun prepareSocket(socket: Socket): Socket { socket.bindToNetworkIfPossible(network) return socket } }
epl-1.0
abf89b6b25b4d7d0c3926be81b7273d3
30.946667
109
0.66778
4.56381
false
false
false
false
FarbodSalamat-Zadeh/TimetableApp
app/src/main/java/co/timetableapp/ui/start/WelcomeActivity.kt
1
2896
/* * Copyright 2017 Farbod Salamat-Zadeh * * 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 co.timetableapp.ui.start import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import co.timetableapp.R import co.timetableapp.TimetableApplication import co.timetableapp.data.PortingFragment import co.timetableapp.ui.home.MainActivity /** * This activity is the launcher activity. It redirects to [MainActivity] if the user already has * timetable data, otherwise displays a welcome screen. * * In the welcome screen, the user has options to import their data, or to go through a setup guide. * * @see InitialSetupActivity */ class WelcomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (hasExistingData()) { startActivity(Intent(baseContext, MainActivity::class.java)) finish() return } setContentView(R.layout.activity_welcome) setupLayout() } private fun hasExistingData() = (application as TimetableApplication).currentTimetable != null private fun setupLayout() { findViewById(R.id.button_import).setOnClickListener { startImportFragment() } findViewById(R.id.button_next).setOnClickListener { startActivity(Intent(this, InitialSetupActivity::class.java)) finish() } } private fun startImportFragment() { val fragmentArgs = Bundle() fragmentArgs.putInt(PortingFragment.ARGUMENT_PORT_TYPE, PortingFragment.TYPE_IMPORT) fragmentArgs.putBoolean(PortingFragment.ARGUMENT_IMPORT_FIRST_DB, true) val fragment = PortingFragment() fragment.arguments = fragmentArgs fragment.onPortingCompleteListener = object : PortingFragment.OnPortingCompleteListener { override fun onPortingComplete(portingType: Int, successful: Boolean) { if (successful && portingType == PortingFragment.TYPE_IMPORT) { startActivity(Intent(this@WelcomeActivity, MainActivity::class.java)) finish() } } } val transaction = supportFragmentManager.beginTransaction() transaction.add(fragment, null) transaction.commit() } }
apache-2.0
6f0c7ee17e495be44a0e1e36082f85e3
33.47619
100
0.694406
4.763158
false
false
false
false
ankidroid/Anki-Android
lint-rules/src/main/java/com/ichi2/anki/lint/rules/DirectSystemCurrentTimeMillisUsage.kt
1
3485
/**************************************************************************************** * Copyright (c) 2020 lukstbit <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ @file:Suppress("UnstableApiUsage") package com.ichi2.anki.lint.rules import com.android.tools.lint.detector.api.* import com.google.common.annotations.VisibleForTesting import com.ichi2.anki.lint.utils.Constants import com.ichi2.anki.lint.utils.LintUtils import com.intellij.psi.PsiMethod import org.jetbrains.uast.UCallExpression /** * This custom Lint rules will raise an error if a developer uses the [System.currentTimeMillis] method instead * of using the time provided by the new Time class. */ class DirectSystemCurrentTimeMillisUsage : Detector(), SourceCodeScanner { companion object { @VisibleForTesting const val ID = "DirectSystemCurrentTimeMillisUsage" @VisibleForTesting const val DESCRIPTION = "Use the collection's getTime() method instead of System.currentTimeMillis()" private const val EXPLANATION = "Using time directly means time values cannot be controlled during testing. " + "Time values like System.currentTimeMillis() must be obtained through the Time obtained from a Collection" private val implementation = Implementation(DirectSystemCurrentTimeMillisUsage::class.java, Scope.JAVA_FILE_SCOPE) val ISSUE: Issue = Issue.create( ID, DESCRIPTION, EXPLANATION, Constants.ANKI_TIME_CATEGORY, Constants.ANKI_TIME_PRIORITY, Constants.ANKI_TIME_SEVERITY, implementation ) } override fun getApplicableMethodNames() = mutableListOf("currentTimeMillis") override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) { super.visitMethodCall(context, node, method) val evaluator = context.evaluator val foundClasses = context.uastFile!!.classes if (!LintUtils.isAnAllowedClass(foundClasses, "SystemTime") && evaluator.isMemberInClass(method, "java.lang.System")) { context.report( ISSUE, context.getCallLocation(node, includeReceiver = true, includeArguments = true), DESCRIPTION ) } } }
gpl-3.0
bdec3eb680ae3f6901d446561c4bad31
51.80303
127
0.584218
5.411491
false
true
false
false
CarrotCodes/Pellet
logging/src/main/kotlin/dev.pellet/logging/PelletLogElement.kt
1
1164
package dev.pellet.logging // Boxes primitive types to make sure that structured log elements can be serialised properly at the point of printing public sealed class PelletLogElement { object NullValue : PelletLogElement() data class StringValue(val value: String) : PelletLogElement() data class NumberValue(val value: Number) : PelletLogElement() data class BooleanValue(val value: Boolean) : PelletLogElement() } public interface PelletLoggable { fun toLogElement(): PelletLogElement } public fun logElement(value: String?): PelletLogElement { if (value == null) { return PelletLogElement.NullValue } return PelletLogElement.StringValue(value) } public fun logElement(value: Number?): PelletLogElement { if (value == null) { return PelletLogElement.NullValue } return PelletLogElement.NumberValue(value) } public fun logElement(value: Boolean?): PelletLogElement { if (value == null) { return PelletLogElement.NullValue } return PelletLogElement.BooleanValue(value) } public fun logElement(loggable: PelletLoggable): PelletLogElement { return loggable.toLogElement() }
apache-2.0
23502af0eca3bf43f902001ede23d08f
28.1
118
0.737973
4.263736
false
false
false
false
kunny/RxFirebase
firebase-database-kotlin/src/main/kotlin/com/androidhuman/rxfirebase2/database/RxFirebaseDatabase.kt
1
5244
@file:Suppress("NOTHING_TO_INLINE", "UNUSED") package com.androidhuman.rxfirebase2.database import com.androidhuman.rxfirebase2.database.model.DataValue import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseReference import com.google.firebase.database.GenericTypeIndicator import com.google.firebase.database.MutableData import com.google.firebase.database.Query import com.google.firebase.database.Transaction import io.reactivex.BackpressureStrategy import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.Single inline fun DatabaseReference.childEvents() : Observable<ChildEvent> = RxFirebaseDatabase.childEvents(this) inline fun DatabaseReference.childEvents(strategy: BackpressureStrategy) : Flowable<ChildEvent> = RxFirebaseDatabase.childEvents(this, strategy) inline fun DatabaseReference.data() : Single<DataSnapshot> = RxFirebaseDatabase.data(this) inline fun DatabaseReference.dataChanges() : Observable<DataSnapshot> = RxFirebaseDatabase.dataChanges(this) inline fun DatabaseReference.dataChanges(strategy: BackpressureStrategy) : Flowable<DataSnapshot> = RxFirebaseDatabase.dataChanges(this, strategy) inline fun <reified T : Any> DatabaseReference.dataChangesOf() : Observable<DataValue<T>> = RxFirebaseDatabase.dataChangesOf(this, T::class.java) inline fun <reified T : Any> DatabaseReference.dataChangesOf(strategy: BackpressureStrategy) : Flowable<DataValue<T>> = RxFirebaseDatabase.dataChangesOf(this, T::class.java, strategy) inline fun <reified T : Any> DatabaseReference.dataChangesOf(typeIndicator: GenericTypeIndicator<T>) : Observable<DataValue<T>> = RxFirebaseDatabase.dataChangesOf(this, typeIndicator) inline fun <reified T : Any> DatabaseReference.dataChangesOf( typeIndicator: GenericTypeIndicator<T>, strategy: BackpressureStrategy) : Flowable<DataValue<T>> = RxFirebaseDatabase.dataChangesOf(this, typeIndicator, strategy) inline fun <reified T : Any> DatabaseReference.dataOf() : Single<T> = RxFirebaseDatabase.dataOf(this, T::class.java) inline fun <reified T : Any> DatabaseReference.dataOf(typeIndicator: GenericTypeIndicator<T>) : Single<T> = RxFirebaseDatabase.dataOf(this, typeIndicator) inline fun DatabaseReference.rxRemoveValue() : Completable = RxFirebaseDatabase.removeValue(this) inline fun DatabaseReference.rxRunTransaction(noinline task: (MutableData) -> Transaction.Result) : Completable = RxFirebaseDatabase.runTransaction(this, task) inline fun DatabaseReference.rxRunTransaction( fireLocalEvents: Boolean, noinline task: (MutableData) -> Transaction.Result) : Completable = RxFirebaseDatabase.runTransaction(this, fireLocalEvents, task) inline fun <reified T : Any> DatabaseReference.rxSetPriority(priority: T) : Completable = RxFirebaseDatabase.setPriority(this, priority) inline fun <reified T : Any> DatabaseReference.rxSetValue(value: T) : Completable = RxFirebaseDatabase.setValue(this, value) inline fun <reified T : Any, reified U : Any> DatabaseReference.rxSetValue(value: T, priority: U) : Completable = RxFirebaseDatabase.setValue(this, value, priority) inline fun DatabaseReference.rxUpdateChildren(update: Map<String, Any?>) : Completable = RxFirebaseDatabase.updateChildren(this, update) inline fun Query.childEvents() : Observable<ChildEvent> = RxFirebaseDatabase.childEvents(this) inline fun Query.childEvents(strategy: BackpressureStrategy) : Flowable<ChildEvent> = RxFirebaseDatabase.childEvents(this, strategy) inline fun Query.data() : Single<DataSnapshot> = RxFirebaseDatabase.data(this) inline fun Query.dataChanges() : Observable<DataSnapshot> = RxFirebaseDatabase.dataChanges(this) inline fun Query.dataChanges(strategy: BackpressureStrategy) : Flowable<DataSnapshot> = RxFirebaseDatabase.dataChanges(this, strategy) inline fun <reified T : Any> Query.dataChangesOf() : Observable<DataValue<T>> = RxFirebaseDatabase.dataChangesOf(this, T::class.java) inline fun <reified T : Any> Query.dataChangesOf(strategy: BackpressureStrategy) : Flowable<DataValue<T>> = RxFirebaseDatabase.dataChangesOf(this, T::class.java, strategy) inline fun <reified T : Any> Query.dataChangesOf(typeIndicator: GenericTypeIndicator<T>) : Observable<DataValue<T>> = RxFirebaseDatabase.dataChangesOf(this, typeIndicator) inline fun <reified T : Any> Query.dataChangesOf( typeIndicator: GenericTypeIndicator<T>, strategy: BackpressureStrategy) : Flowable<DataValue<T>> = RxFirebaseDatabase.dataChangesOf(this, typeIndicator, strategy) inline fun <reified T : Any> Query.dataOf() : Single<T> = RxFirebaseDatabase.dataOf(this, T::class.java) inline fun <reified T : Any> Query.dataOf(typeIndicator: GenericTypeIndicator<T>) : Single<T> = RxFirebaseDatabase.dataOf(this, typeIndicator)
apache-2.0
b91364bda9abce9f8c5fc6d392ff1f0f
37.844444
100
0.73913
4.485885
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/service/system/v1alpha/RequisitionsService.kt
1
2671
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.service.system.v1alpha import org.wfanet.measurement.common.grpc.grpcRequire import org.wfanet.measurement.common.grpc.grpcRequireNotNull import org.wfanet.measurement.common.identity.DuchyIdentity import org.wfanet.measurement.common.identity.apiIdToExternalId import org.wfanet.measurement.common.identity.duchyIdentityFromContext import org.wfanet.measurement.internal.kingdom.FulfillRequisitionRequestKt.computedRequisitionParams import org.wfanet.measurement.internal.kingdom.RequisitionsGrpcKt.RequisitionsCoroutineStub as InternalRequisitionsCoroutineStub import org.wfanet.measurement.internal.kingdom.fulfillRequisitionRequest as internalFulfillRequisitionRequest import org.wfanet.measurement.system.v1alpha.FulfillRequisitionRequest import org.wfanet.measurement.system.v1alpha.Requisition import org.wfanet.measurement.system.v1alpha.RequisitionKey import org.wfanet.measurement.system.v1alpha.RequisitionsGrpcKt.RequisitionsCoroutineImplBase class RequisitionsService( private val internalRequisitionsClient: InternalRequisitionsCoroutineStub, private val duchyIdentityProvider: () -> DuchyIdentity = ::duchyIdentityFromContext ) : RequisitionsCoroutineImplBase() { override suspend fun fulfillRequisition(request: FulfillRequisitionRequest): Requisition { val requisitionKey = grpcRequireNotNull(RequisitionKey.fromName(request.name)) { "Resource name unspecified or invalid." } grpcRequire(request.nonce != 0L) { "nonce unspecified" } val internalResponse = internalRequisitionsClient.fulfillRequisition( internalFulfillRequisitionRequest { externalRequisitionId = apiIdToExternalId(requisitionKey.requisitionId) nonce = request.nonce computedParams = computedRequisitionParams { externalComputationId = apiIdToExternalId(requisitionKey.computationId) externalFulfillingDuchyId = duchyIdentityProvider().id } } ) return internalResponse.toSystemRequisition() } }
apache-2.0
57864bf30ed6fddb1b043662f5913815
47.563636
128
0.7997
4.937153
false
false
false
false
mercadopago/px-android
px-checkout/src/main/java/com/mercadopago/android/px/internal/features/pay_button/PayButtonFragment.kt
1
11180
package com.mercadopago.android.px.internal.features.pay_button import android.annotation.SuppressLint import android.app.Activity import android.arch.lifecycle.Observer import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.view.LayoutInflater import android.view.View import android.view.View.INVISIBLE import android.view.View.VISIBLE import android.view.ViewGroup import com.mercadolibre.android.ui.widgets.MeliButton import com.mercadolibre.android.ui.widgets.MeliSnackbar import com.mercadopago.android.px.R import com.mercadopago.android.px.addons.BehaviourProvider import com.mercadopago.android.px.addons.internal.SecurityValidationHandler import com.mercadopago.android.px.addons.model.SecurityValidationData import com.mercadopago.android.px.internal.di.Session import com.mercadopago.android.px.internal.features.Constants import com.mercadopago.android.px.internal.features.SecurityCodeActivity import com.mercadopago.android.px.internal.features.business_result.BusinessPaymentResultActivity import com.mercadopago.android.px.internal.features.explode.ExplodeDecorator import com.mercadopago.android.px.internal.features.explode.ExplodingFragment import com.mercadopago.android.px.internal.features.payment_result.PaymentResultActivity import com.mercadopago.android.px.internal.features.plugins.PaymentProcessorActivity import com.mercadopago.android.px.internal.util.FragmentUtil import com.mercadopago.android.px.internal.util.ViewUtils import com.mercadopago.android.px.internal.view.OnSingleClickListener import com.mercadopago.android.px.internal.viewmodel.PostPaymentAction import com.mercadopago.android.px.model.Card import com.mercadopago.android.px.model.PaymentRecovery import com.mercadopago.android.px.model.exceptions.MercadoPagoError import com.mercadopago.android.px.tracking.internal.events.FrictionEventTracker import com.mercadopago.android.px.tracking.internal.model.Reason import com.mercadopago.android.px.internal.viewmodel.PayButtonViewModel as ButtonConfig class PayButtonFragment : Fragment(), PayButton.View, SecurityValidationHandler { private var buttonStatus = MeliButton.State.NORMAL private lateinit var button: MeliButton private lateinit var viewModel: PayButtonViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_pay_button, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = Session.getInstance().viewModelModule.get(this, PayButtonViewModel::class.java) when { targetFragment is PayButton.Handler -> viewModel.attach(targetFragment as PayButton.Handler) parentFragment is PayButton.Handler -> viewModel.attach(parentFragment as PayButton.Handler) context is PayButton.Handler -> viewModel.attach(context as PayButton.Handler) else -> throw IllegalStateException("Parent should implement ${PayButton.Handler::class.java.simpleName}") } button = view.findViewById(R.id.confirm_button) button.setOnClickListener(object : OnSingleClickListener() { override fun onSingleClick(v: View?) { viewModel.preparePayment() } }) savedInstanceState?.let { buttonStatus = it.getInt(EXTRA_STATE, MeliButton.State.NORMAL) button.visibility = it.getInt(EXTRA_VISIBILITY, VISIBLE) viewModel.recoverFromBundle(it) } updateButtonState() with(viewModel) { buttonTextLiveData.observe(viewLifecycleOwner, Observer { buttonConfig -> button.text = buttonConfig!!.getButtonText([email protected]!!) }) cvvRequiredLiveData.observe(viewLifecycleOwner, Observer { pair -> pair?.let { showSecurityCodeScreen(it.first, it.second) } }) recoverRequiredLiveData.observe(viewLifecycleOwner, Observer { recovery -> recovery?.let { showSecurityCodeForRecovery(it) } }) stateUILiveData.observe(viewLifecycleOwner, Observer { state -> state?.let { onStateUIChanged(it) } }) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt(EXTRA_STATE, buttonStatus) outState.putInt(EXTRA_VISIBILITY, button.visibility) viewModel.storeInBundle(outState) } private fun onStateUIChanged(stateUI: PayButtonState) { when (stateUI) { is UIProgress.FingerprintRequired -> startBiometricsValidation(stateUI.validationData) is UIProgress.ButtonLoadingStarted -> startLoadingButton(stateUI.timeOut, stateUI.buttonConfig) is UIProgress.ButtonLoadingFinished -> finishLoading(stateUI.explodeDecorator) is UIProgress.ButtonLoadingCanceled -> cancelLoading() is UIResult.VisualProcessorResult -> PaymentProcessorActivity.start(this, REQ_CODE_PAYMENT_PROCESSOR) is UIError.ConnectionError -> showSnackBar(stateUI.error) is UIResult.PaymentResult -> PaymentResultActivity.start(this, REQ_CODE_CONGRATS, stateUI.model) is UIResult.BusinessPaymentResult -> BusinessPaymentResultActivity.start(this, REQ_CODE_CONGRATS, stateUI.model) } } override fun stimulate() { viewModel.preparePayment() } override fun enable() { buttonStatus = MeliButton.State.NORMAL updateButtonState() } override fun disable() { buttonStatus = MeliButton.State.DISABLED updateButtonState() } private fun updateButtonState() { if (::button.isInitialized) { button.state = buttonStatus } } @SuppressLint("Range") private fun showSnackBar(error: MercadoPagoError) { view?.let { MeliSnackbar.make(it, error.message, Snackbar.LENGTH_LONG, MeliSnackbar.SnackbarType.ERROR).show() } } private fun startBiometricsValidation(validationData: SecurityValidationData) { disable() BehaviourProvider.getSecurityBehaviour().startValidation(this, validationData, REQ_CODE_BIOMETRICS) } override fun onAnimationFinished() { viewModel.hasFinishPaymentAnimation() } override fun onSecurityValidated(isSuccess: Boolean, securityValidated: Boolean) { viewModel.handleBiometricsResult(isSuccess, securityValidated) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQ_CODE_BIOMETRICS) { val securityRequested = data?.getBooleanExtra( BehaviourProvider.getSecurityBehaviour().extraResultKey, false) ?: false enable() onSecurityValidated(resultCode == Activity.RESULT_OK, securityRequested) } else if (requestCode == REQ_CODE_SECURITY_CODE) { cancelLoading() if (resultCode == Activity.RESULT_OK) { viewModel.startPayment() } } else if (requestCode == REQ_CODE_CONGRATS && resultCode == Constants.RESULT_ACTION) { handleAction(data) } else if (resultCode == Constants.RESULT_PAYMENT) { viewModel.onPostPayment(PaymentProcessorActivity.getPaymentModel(data)) } else if (resultCode == Constants.RESULT_FAIL_ESC) { viewModel.onRecoverPaymentEscInvalid(PaymentProcessorActivity.getPaymentRecovery(data)!!) } else { super.onActivityResult(requestCode, resultCode, data) } } private fun handleAction(data: Intent?) { data?.extras?.let { viewModel.onPostPaymentAction(PostPaymentAction.fromBundle(it)) } } override fun onDestroyView() { super.onDestroyView() viewModel.detach() } override fun onDestroy() { FragmentUtil.tryRemoveNow(childFragmentManager, ExplodingFragment.TAG) super.onDestroy() } private fun finishLoading(params: ExplodeDecorator) { childFragmentManager.findFragmentByTag(ExplodingFragment.TAG) ?.let { (it as ExplodingFragment).finishLoading(params) } ?: viewModel.hasFinishPaymentAnimation() } private fun startLoadingButton(paymentTimeout: Int, buttonConfig: ButtonConfig) { context?.let { button.post { if (!isAdded) { FrictionEventTracker.with("/px_checkout/pay_button_loading", FrictionEventTracker.Id.GENERIC, FrictionEventTracker.Style.SCREEN, emptyMap<String, String>()) } else { val explodeParams = ExplodingFragment.getParams(button, buttonConfig.getButtonProgressText(it), paymentTimeout) val explodingFragment = ExplodingFragment.newInstance(explodeParams) childFragmentManager.beginTransaction() .add(R.id.exploding_frame, explodingFragment, ExplodingFragment.TAG) .commitNowAllowingStateLoss() hideConfirmButton() } } } } private fun cancelLoading() { showConfirmButton() val fragment = childFragmentManager.findFragmentByTag(ExplodingFragment.TAG) as ExplodingFragment? if (fragment != null && fragment.isAdded && fragment.hasFinished()) { childFragmentManager .beginTransaction() .remove(fragment) .commitNowAllowingStateLoss() restoreStatusBar() } } private fun restoreStatusBar() { activity?.let { ViewUtils.setStatusBarColor(ContextCompat.getColor(it, R.color.px_colorPrimaryDark), it.window) } } private fun hideConfirmButton() { button.clearAnimation() button.visibility = INVISIBLE } private fun showConfirmButton() { button.clearAnimation() button.visibility = VISIBLE } private fun showSecurityCodeForRecovery(recovery: PaymentRecovery) { cancelLoading() SecurityCodeActivity.startForRecovery(this, recovery, REQ_CODE_SECURITY_CODE) } private fun showSecurityCodeScreen(card: Card, reason: Reason?) { SecurityCodeActivity.startForSavedCard(this, card, reason, REQ_CODE_SECURITY_CODE) } override fun isExploding(): Boolean { return FragmentUtil.isFragmentVisible(childFragmentManager, ExplodingFragment.TAG) } companion object { const val TAG = "TAG_BUTTON_FRAGMENT" const val REQ_CODE_CONGRATS = 300 private const val REQ_CODE_SECURITY_CODE = 301 private const val REQ_CODE_PAYMENT_PROCESSOR = 302 private const val REQ_CODE_BIOMETRICS = 303 private const val EXTRA_STATE = "extra_state" private const val EXTRA_VISIBILITY = "extra_visibility" } }
mit
37c79084a1daade52e5f744f86b3a15c
42.337209
122
0.70161
4.785959
false
false
false
false
mercadopago/px-android
px-services/src/main/java/com/mercadopago/android/px/internal/core/extensions/BaseExtensions.kt
1
1171
package com.mercadopago.android.px.internal.core.extensions import android.app.Activity import android.graphics.Rect import android.view.View internal fun CharSequence?.isNotNullNorEmpty() = !isNullOrEmpty() internal fun CharSequence?.orIfEmpty(fallback: String) = if (isNotNullNorEmpty()) this!! else fallback internal fun View.gone() = apply { visibility = View.GONE } internal fun View.visible() = apply { visibility = View.VISIBLE } internal fun View.invisible() = apply { visibility = View.INVISIBLE } internal fun Any?.runIfNull(action: ()->Unit) { if(this == null) { action.invoke() } } internal fun Activity.addKeyBoardListener( onKeyBoardOpen: (() -> Unit)? = null, onKeyBoardClose: (() -> Unit)? = null ) { window.decorView.rootView?.apply { viewTreeObserver?.addOnGlobalLayoutListener { val r = Rect() getWindowVisibleDisplayFrame(r) val heightDiff = rootView.height - (r.bottom - r.top) if (heightDiff > rootView.height * 0.15) { onKeyBoardOpen?.invoke() } else { onKeyBoardClose?.invoke() } } } }
mit
d79d2f76805d8d5c71cee20e82a9611f
27.585366
102
0.643894
4.258182
false
false
false
false
jeffersonvenancio/BarzingaNow
android/app/src/main/java/com/barzinga/view/IdentifyRfidActivity.kt
1
2437
package com.barzinga.view import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.content.ContextCompat.startActivity import android.support.v7.app.AppCompatActivity import android.widget.Toast import com.barzinga.R import com.barzinga.manager.RfidManager import com.barzinga.manager.UserManager import com.barzinga.model.User import com.barzinga.viewmodel.Constants.USER_EXTRA import com.barzinga.viewmodel.MainViewModel import com.barzinga.viewmodel.RfidViewModel import okhttp3.ResponseBody import retrofit2.Response import java.util.* import kotlin.concurrent.timerTask class IdentifyRfidActivity : AppCompatActivity(), RfidManager.DataListener, UserManager.DataListener { lateinit var viewModelRfid: RfidViewModel lateinit var viewModelMain: MainViewModel var user: User? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_identify_rfid) viewModelRfid = ViewModelProviders.of(this).get(RfidViewModel::class.java) viewModelMain = ViewModelProviders.of(this).get(MainViewModel::class.java) viewModelRfid.setListener(this) viewModelMain.setListener(this) val str = intent?.extras?.getString("rfid") if (str != null) { logUser(str) return } viewModelRfid.getRfid() //logUser("0006915991") } companion object { fun start(context: Context) { val starter = Intent(context, IdentifyRfidActivity::class.java) context.startActivity(starter) } } override fun onRfidSuccess(response: Response<ResponseBody>) { logUser(response.body()!!.string()) } override fun onRfidFailure(error: String) { finish() } private fun logUser(rfid : String) { viewModelMain.logUserWithRfid(rfid) } override fun onLogInSuccess(user: User) { var intent = Intent(this, ProductsActivity::class.java) intent.putExtra(USER_EXTRA, user) startActivity(intent) finish() } override fun onLogInFailure() { Toast.makeText(this, getString(R.string.login_failure), Toast.LENGTH_SHORT).show() val timer = Timer() timer.schedule(timerTask { finish() }, 2000) } }
apache-2.0
3dd043d2cf1effb0064d684c47351823
29.475
102
0.702503
4.29806
false
false
false
false
lightem90/Sismic
app/src/main/java/com/polito/sismic/Presenters/ReportActivity/Fragments/BaseReportFragment.kt
1
8000
package com.polito.sismic.Presenters.ReportActivity.Fragments import android.content.Context import android.graphics.Color import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.mikephil.charting.components.YAxis import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineDataSet import com.polito.sismic.Domain.PillarDomain import com.polito.sismic.Domain.Report import com.polito.sismic.Extensions.getReport import com.polito.sismic.Extensions.toast import com.polito.sismic.Interactors.Helpers.UiMapper import com.polito.sismic.Presenters.CustomLayout.FragmentScrollableCanvas import com.polito.sismic.R import com.stepstone.stepper.BlockingStep import com.stepstone.stepper.StepperLayout import com.stepstone.stepper.VerificationError /** * Created by Matteo on 29/07/2017. */ //base class for all report fragment to hide communication with activity and make every fragment scrollable abstract class BaseReportFragment : Fragment(), BlockingStep { private var mPdfWriterCallback: BaseReportFragment.PdfWriterManager? = null private var mParametersCallback: BaseReportFragment.ParametersManager? = null private var mReport: Report? = null fun getReport(): Report { return mReport!! //ALWAYS TRUE! } //Is the activity the handler of the dto, each fragment only passes its own // parameters througth the callback when the button "next" is pressed //Each fragment must implement the method to get their own paramter name-value interface ParametersManager { fun onParametersConfirmed(report: Report, needReload : Boolean) fun onParametersSaveRequest() } interface PdfWriterManager { fun onSavePageRequest(fragmentView: View?, fragName: String) } //domain report from bundle override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mReport = arguments.getReport() } //injects parameters to view from domain (needs some fixing, for example the user should not update or re / import data when editing, //the problem is that the activity doesn't know when a value is changed and needs to update the view (could this be done just always?) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mReport = arguments?.getReport() onParametersInjectedForEdit() } //binds domain values to ui (done by each fragment by mapper) protected open fun onParametersInjectedForEdit() { UiMapper.bindToDomain(this, getReport().reportState) } //In this way I can make every fragment scrollable and use protected properties avoiding replicated zone protected fun inflateFragment(resId: Int, inflater: LayoutInflater?, container: ViewGroup?, needScrollable: Boolean = true): View? { //Custom view any layout with "scrollable" style val view = inflater!!.inflate(resId, container, false) //For hiding the created bottom action bar (on fab pressure) view.setOnClickListener({ hideBottomActions() }) if (!needScrollable) return view val baseLayout = inflater.inflate(R.layout.base_report_fragment, container, false) val scrollableCanvas = baseLayout.findViewById<FragmentScrollableCanvas>(R.id.base_fragment_scroll_view) scrollableCanvas.addView(view) //Must be called or it crashes on scroll!!! scrollableCanvas.setObjectsToHideOnScroll(activity.findViewById(R.id.fabtoolbar), activity.findViewById(R.id.fabtoolbar_fab), activity.findViewById<StepperLayout>(R.id.stepperLayout)) //Requires api 23 //scrollableCanvas.setOnScrollChangeListener(View.OnScrollChangeListener({ // view, scrollX, scrollY, oldScrollX, oldScroolY -> //})) return baseLayout } //callback to activity updates domain instance of each fragment. //in this way activity and fragments work on the same data override fun onNextClicked(callback: StepperLayout.OnNextClickedCallback?) { mParametersCallback?.onParametersConfirmed(getReport(), onNeedReload()) mPdfWriterCallback?.onSavePageRequest(view?.findViewById(R.id.base_fragment_scroll_view), javaClass.canonicalName) callback!!.goToNextStep() } //utility protected open fun onNeedReload(): Boolean { return false } //actions to update user interface when domain parameters change protected open fun onReload() { } fun reloadFragmentFromCallback(newReportState: Report) { mReport = newReportState onReload() } override fun onBackClicked(callback: StepperLayout.OnBackClickedCallback?) { callback?.goToPrevStep() } override fun onError(error: VerificationError) { activity.toast(error.errorMessage) } override fun onAttach(context: Context?) { super.onAttach(context) try { mParametersCallback = context as ParametersManager? } catch (e: ClassCastException) { throw ClassCastException(context!!.toString() + " must implement OnParametersConfirmed") } try { mPdfWriterCallback = context as PdfWriterManager? } catch (e: ClassCastException) { throw ClassCastException(context!!.toString() + " must implement OnParametersConfirmed") } } //utility protected fun hideBottomActions() { activity.findViewById<FloatingActionButton>(R.id.fabtoolbar_fab)?.hide() } //utility protected fun showBottomActions() { activity.findViewById<FloatingActionButton>(R.id.fabtoolbar_fab)?.show() } //Eventually in derived classes override fun onSelected() {} //every child fragment has its own override fun verifyStep(): VerificationError? { return null } //save report override fun onCompleteClicked(callback: StepperLayout.OnCompleteClickedCallback?) { mParametersCallback?.onParametersSaveRequest() callback!!.complete() } protected fun buildPillarDomainForUi(pillarDomain: PillarDomain, addSismicStatePoints: Boolean = false): MutableList<LineDataSet> { val upPointList = mutableListOf<Entry>() pillarDomain.domainPoints.forEach { point -> upPointList.add(Entry(point.n.toFloat(), point.m.toFloat())) } val domainGraph = mutableListOf<LineDataSet>() if (addSismicStatePoints) { domainGraph.addAll(pillarDomain.limitStatePoints.map { LineDataSet(listOf(Entry(it.n.toFloat(), it.m.toFloat())), it.label).apply { setDrawCircles(true) circleRadius = 10f circleColors = listOf(ContextCompat.getColor(context, it.color)) axisDependency = YAxis.AxisDependency.LEFT } } ) } val UiDomainUp = LineDataSet(upPointList, "").apply { color = Color.BLUE setDrawCircles(false) lineWidth = 3f axisDependency = YAxis.AxisDependency.LEFT } //Just ui stuff to show the simmetric val downList = mutableListOf<Entry>() pillarDomain.domainPoints.forEach { point -> downList.add(Entry(point.n.toFloat(), -point.m.toFloat())) } val UiDomainDown = LineDataSet(downList, "").apply { color = Color.BLUE setDrawCircles(false) lineWidth = 3f axisDependency = YAxis.AxisDependency.LEFT } domainGraph.add(UiDomainUp) domainGraph.add(UiDomainDown) return domainGraph } }
mit
95c31ad5178d7392d362236741ba7d8e
36.383178
138
0.694
4.79904
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/fluidsolidifier/FluidSolidifierCategory.kt
1
3894
package net.ndrei.teslapoweredthingies.machines.fluidsolidifier import com.google.common.collect.Lists import mezz.jei.api.IModRegistry import mezz.jei.api.gui.IDrawable import mezz.jei.api.gui.IRecipeLayout import mezz.jei.api.ingredients.IIngredients import mezz.jei.api.recipe.IRecipeCategoryRegistration import mezz.jei.api.recipe.IRecipeWrapper import net.minecraft.client.Minecraft import net.minecraft.item.ItemStack import net.minecraftforge.fluids.FluidRegistry import net.minecraftforge.fluids.FluidStack import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly import net.ndrei.teslapoweredthingies.client.ThingiesTexture import net.ndrei.teslapoweredthingies.integrations.jei.BaseCategory import net.ndrei.teslapoweredthingies.integrations.jei.TeslaThingyJeiCategory /** * Created by CF on 2017-06-30. */ @TeslaThingyJeiCategory object FluidSolidifierCategory : BaseCategory<FluidSolidifierCategory.FluidSolidifierRecipeWrapper>(FluidSolidifierBlock) { private lateinit var lavaOverlay: IDrawable private lateinit var waterOverlay: IDrawable override fun setRecipe(recipeLayout: IRecipeLayout, recipeWrapper: FluidSolidifierRecipeWrapper, ingredients: IIngredients) { val fluids = recipeLayout.fluidStacks fluids.init(0, true, 8, 15, 8, 27, 1000, true, lavaOverlay) fluids.set(0, ingredients.getInputs(FluidStack::class.java)[0]) fluids.init(1, true, 20, 15, 8, 27, 1000, true, waterOverlay) fluids.set(1, ingredients.getInputs(FluidStack::class.java)[1]) fluids.init(2, true, 43, 15, 8, 27, 1000, true, lavaOverlay) fluids.set(2, FluidStack(FluidRegistry.LAVA, recipeWrapper.recipe.lavaMbConsumed)) fluids.init(3, true, 55, 15, 8, 27, 1000, true, waterOverlay) fluids.set(3, FluidStack(FluidRegistry.WATER, recipeWrapper.recipe.waterMbConsumed)) val stacks = recipeLayout.itemStacks stacks.init(0, false, 77, 20) stacks.set(0, recipeWrapper.recipe.resultStack) } class FluidSolidifierRecipeWrapper(val recipe: FluidSolidifierResult) : IRecipeWrapper { override fun getIngredients(ingredients: IIngredients) { ingredients.setInputs(FluidStack::class.java, Lists.newArrayList( FluidStack(FluidRegistry.LAVA, this.recipe.lavaMbMin), FluidStack(FluidRegistry.WATER, this.recipe.waterMbMin) )) ingredients.setOutput(ItemStack::class.java, this.recipe.resultStack) } @SideOnly(Side.CLIENT) override fun drawInfo(minecraft: Minecraft, recipeWidth: Int, recipeHeight: Int, mouseX: Int, mouseY: Int) { super.drawInfo(minecraft, recipeWidth, recipeHeight, mouseX, mouseY) val required = "required" val consumed = "consumed" minecraft.fontRenderer.drawString(required, 18 - minecraft.fontRenderer.getStringWidth(required) / 2, 8 - minecraft.fontRenderer.FONT_HEIGHT, 0x424242) minecraft.fontRenderer.drawString(consumed, 54 - minecraft.fontRenderer.getStringWidth(consumed) / 2, 47, 0x424242) } } override fun register(registry: IRecipeCategoryRegistration) { super.register(registry) this.recipeBackground = this.guiHelper.createDrawable(ThingiesTexture.JEI_TEXTURES.resource, 0, 132, 124, 66) lavaOverlay = this.guiHelper.createDrawable(ThingiesTexture.JEI_TEXTURES.resource, 8, 147, 8, 27) waterOverlay = this.guiHelper.createDrawable(ThingiesTexture.JEI_TEXTURES.resource, 20, 147, 8, 27) } override fun register(registry: IModRegistry) { super.register(registry) registry.handleRecipes(FluidSolidifierResult::class.java, { FluidSolidifierRecipeWrapper(it) }, this.uid) registry.addRecipes(FluidSolidifierResult.values().toMutableList(), this.uid) } }
mit
ef50ff7f87fc4b71e46ab62a4372d223
45.357143
163
0.739343
4.182599
false
false
false
false
dbacinski/Design-Patterns-In-Kotlin
patterns/src/test/kotlin/ChainOfResponsibility.kt
1
2352
import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test interface HeadersChain { fun addHeader(inputHeader: String): String } class AuthenticationHeader(val token: String?, var next: HeadersChain? = null) : HeadersChain { override fun addHeader(inputHeader: String): String { token ?: throw IllegalStateException("Token should be not null") return inputHeader + "Authorization: Bearer $token\n" .let { next?.addHeader(it) ?: it } } } class ContentTypeHeader(val contentType: String, var next: HeadersChain? = null) : HeadersChain { override fun addHeader(inputHeader: String): String = inputHeader + "ContentType: $contentType\n" .let { next?.addHeader(it) ?: it } } class BodyPayload(val body: String, var next: HeadersChain? = null) : HeadersChain { override fun addHeader(inputHeader: String): String = inputHeader + "$body" .let { next?.addHeader(it) ?: it } } class ChainOfResponsibilityTest { @Test fun `Chain Of Responsibility`() { //create chain elements val authenticationHeader = AuthenticationHeader("123456") val contentTypeHeader = ContentTypeHeader("json") val messageBody = BodyPayload("Body:\n{\n\"username\"=\"dbacinski\"\n}") //construct chain authenticationHeader.next = contentTypeHeader contentTypeHeader.next = messageBody //execute chain val messageWithAuthentication = authenticationHeader.addHeader("Headers with Authentication:\n") println(messageWithAuthentication) val messageWithoutAuth = contentTypeHeader.addHeader("Headers:\n") println(messageWithoutAuth) assertThat(messageWithAuthentication).isEqualTo( """ Headers with Authentication: Authorization: Bearer 123456 ContentType: json Body: { "username"="dbacinski" } """.trimIndent() ) assertThat(messageWithoutAuth).isEqualTo( """ Headers: ContentType: json Body: { "username"="dbacinski" } """.trimIndent() ) } }
gpl-3.0
9306538086862ca7b9c46e0bc3cd26f6
28.4
97
0.600765
4.983051
false
false
false
false
tasks/tasks
app/src/googleplay/java/org/tasks/location/GoogleGeofenceTransitionIntentService.kt
1
2691
package org.tasks.location import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.google.android.gms.location.Geofence import com.google.android.gms.location.GeofencingEvent import com.todoroo.andlib.utility.DateUtilities import dagger.hilt.android.AndroidEntryPoint import org.tasks.Notifier import org.tasks.data.LocationDao import org.tasks.injection.InjectingJobIntentService import timber.log.Timber import javax.inject.Inject @AndroidEntryPoint class GoogleGeofenceTransitionIntentService : InjectingJobIntentService() { @Inject lateinit var locationDao: LocationDao @Inject lateinit var notifier: Notifier override suspend fun doWork(intent: Intent) { val geofencingEvent = GeofencingEvent.fromIntent(intent) if (geofencingEvent.hasError()) { Timber.e("geofence error code %s", geofencingEvent.errorCode) return } val transitionType = geofencingEvent.geofenceTransition val triggeringGeofences = geofencingEvent.triggeringGeofences Timber.i("Received geofence transition: %s, %s", transitionType, triggeringGeofences) if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER || transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) { triggeringGeofences.forEach { triggerNotification(it, transitionType == Geofence.GEOFENCE_TRANSITION_ENTER) } } else { Timber.w("invalid geofence transition type: %s", transitionType) } } private suspend fun triggerNotification(triggeringGeofence: Geofence, arrival: Boolean) { val requestId = triggeringGeofence.requestId try { val place = locationDao.getPlace(requestId) if (place == null) { Timber.e("Can't find place for requestId %s", requestId) return } val geofences = if (arrival) { locationDao.getArrivalGeofences(place.uid!!, DateUtilities.now()) } else { locationDao.getDepartureGeofences(place.uid!!, DateUtilities.now()) } notifier.triggerNotifications(place.id, geofences, arrival) } catch (e: Exception) { Timber.e(e, "Error triggering geofence %s: %s", requestId, e.message) } } class Broadcast : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { enqueueWork( context, GoogleGeofenceTransitionIntentService::class.java, JOB_ID_GEOFENCE_TRANSITION, intent) } } }
gpl-3.0
4f2cda18e2316290d0c4e68e375c186b
39.179104
122
0.666667
4.955801
false
false
false
false
sandjelkovic/dispatchd
content-service/src/main/kotlin/com/sandjelkovic/dispatchd/content/data/entity/UpdateJob.kt
1
706
package com.sandjelkovic.dispatchd.content.data.entity import java.time.LocalDateTime import java.time.ZoneId import java.time.ZonedDateTime import javax.persistence.* import javax.validation.constraints.NotNull /** * @author sandjelkovic * @date 3.3.18. */ @Entity data class UpdateJob( @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long? = null, @Column(nullable = false) @NotNull var finishTime: ZonedDateTime = ZonedDateTime.of(LocalDateTime.MIN, ZoneId.systemDefault()), @Column(nullable = false) @NotNull var startTime: ZonedDateTime = ZonedDateTime.of(LocalDateTime.MIN, ZoneId.systemDefault()), @NotNull var success: Boolean = false )
apache-2.0
8f1ad80e21f3af7ed6ef48263753ac05
26.153846
96
0.736544
4.104651
false
false
false
false
dafi/photoshelf
core/src/main/java/com/ternaryop/photoshelf/activity/ImageViewerActivityStarter.kt
1
1181
package com.ternaryop.photoshelf.activity import android.content.Context import android.content.Intent import java.io.Serializable class TagPhotoBrowserData( val blogName: String?, val tag: String, val allowSearch: Boolean ) : Serializable { companion object { const val serialVersionUID = 1L } } class ImageViewerData( val imageUrl: String, val title: String? = null, val tag: String? = null ) : Serializable { companion object { const val serialVersionUID = 1L } } interface ImageViewerActivityStarter { fun startImagePicker(context: Context, url: String) fun startImagePickerPrefetch(urls: List<String>) /** * Prepare the intent need to launch the tag photo browser activity * @param context the context * @param tagPhotoBrowserData the data used by activity * @param returnSelectedPost true if selected item must be returned, false otherwise */ fun tagPhotoBrowserIntent( context: Context, tagPhotoBrowserData: TagPhotoBrowserData, returnSelectedPost: Boolean = false ): Intent fun startImageViewer(context: Context, data: ImageViewerData) }
mit
22e8eae6d684f73a5f54e04cebbc5d39
25.840909
88
0.708721
4.631373
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/data/Attachment.kt
1
964
package org.tasks.data import androidx.room.* import com.todoroo.astrid.data.Task @Entity( tableName = "attachment", foreignKeys = [ ForeignKey( entity = Task::class, parentColumns = ["_id"], childColumns = ["task"], onDelete = ForeignKey.CASCADE, ), ForeignKey( entity = TaskAttachment::class, parentColumns = ["file_id"], childColumns = ["file"], onDelete = ForeignKey.CASCADE, ) ], indices = [Index(value = ["task", "file"], unique = true)], ) data class Attachment( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "attachment_id") @Transient val id: Long? = null, @ColumnInfo(name = "task", index = true) @Transient val task: Long, @ColumnInfo(name = "file", index = true) @Transient val fileId: Long, @ColumnInfo(name = "file_uuid") val attachmentUid: String, )
gpl-3.0
9dc43349a3d28ee893b0aa75c8c9dbdf
25.081081
63
0.567427
4.246696
false
false
false
false
nemerosa/ontrack
ontrack-extension-stale/src/main/java/net/nemerosa/ontrack/extension/stale/StaleProperty.kt
1
2772
package net.nemerosa.ontrack.extension.stale import net.nemerosa.ontrack.model.annotations.APIDescription /** * Defines a stale policy for branches. A branch last activity is the date its last build was created. * * @property disablingDuration Number of days of inactivity after which the branch is _disabled_ * @property deletingDuration Number of days of inactivity _after_ a branch has been disabled after which the branch * is _deleted_. If 0, the branches are never deleted. * @property promotionsToKeep List of promotions to always keep. If a branch has at least one build having one of these * promotions, the branch will never be disabled not deleted. * @property includes Regular expression to identify branches which will never be disabled not deleted * @property excludes Can define a regular expression for exceptions to the [includes] rule */ data class StaleProperty( @APIDescription("Number of days of inactivity after which the branch is disabled") val disablingDuration: Int, @APIDescription("Number of days of inactivity after a branch has been disabled after which the branch is deleted. If 0, the branches are never deleted.") val deletingDuration: Int?, @APIDescription("List of promotions to always keep. If a branch has at least one build having one of these promotions, the branch will never be disabled not deleted.") val promotionsToKeep: List<String>?, @APIDescription("Regular expression to identify branches which will never be disabled not deleted") val includes: String?, @APIDescription("Can define a regular expression for exceptions to the includes rule") val excludes: String?, ) { fun withDisablingDuration(disablingDuration: Int): StaleProperty { return if (this.disablingDuration == disablingDuration) this else StaleProperty( disablingDuration, deletingDuration, promotionsToKeep, includes, excludes, ) } fun withDeletingDuration(deletingDuration: Int): StaleProperty { return if (this.deletingDuration == deletingDuration) this else StaleProperty( disablingDuration, deletingDuration, promotionsToKeep, includes, excludes, ) } fun withPromotionsToKeep(promotionsToKeep: List<String>?): StaleProperty { return if (this.promotionsToKeep === promotionsToKeep) this else StaleProperty( disablingDuration, deletingDuration, promotionsToKeep, includes, excludes, ) } companion object { fun create(): StaleProperty { return StaleProperty(0, 0, emptyList(), null, null) } } }
mit
23c360f205fa558c8e587c20cde5b097
41.661538
171
0.696609
5.210526
false
false
false
false
groupdocs-comparison/GroupDocs.Comparison-for-Java
Demos/Ktor/src/main/kotlin/com/groupdocs/ui/modules/download/DownloadModule.kt
1
1343
package com.groupdocs.ui.modules.download import com.groupdocs.ui.status.InternalServerException import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.util.* import org.koin.ktor.ext.inject import java.nio.file.Paths fun Route.downloadModule() { val downloadController by inject<DownloadController>() get("/downloadDocument/") { call.parameters["guid"]?.let { guid -> val guidAsPath = Paths.get(guid) call.response.headers.apply { append("Content-disposition", "attachment; filename=${guidAsPath.fileName}") append("Content-Description", "File Transfer") append("Content-Transfer-Encoding", "binary") append("Cache-Control", "must-revalidate") append("Pragma", "public") } call.respondOutputStream( status = HttpStatusCode.OK, contentType = ContentType.Application.OctetStream, producer = { downloadController.download( fileName = guid, outputStream = this ) } ) } ?: throw InternalServerException("Document guid is not provided!") } }
mit
098992da234ac02f1d6be5a7e64b4956
34.368421
92
0.589724
4.919414
false
false
false
false
kiruto/kotlin-android-mahjong
mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/ctrl/impl/Player.kt
1
3867
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[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 dev.yuriel.kotmahjan.ctrl.impl import dev.yuriel.kotmahjan.models.* import rx.Observable /** * Created by yuriel on 7/25/16. */ open class Player(private val model: PlayerModel, private val jikaze: Kaze, private val commander: PlayerCommander, private val rounder: RoundContextV2): PlayerContext { init{ } override fun onStart() { } override fun onReceiveHai(hai: Hai) { model.tehai.put(hai) } override fun onHaiPai(haiList: List<Hai>) { model.tehai.put(haiList) } override fun afterHaiPai() { model.tehai.sort() } override fun onEnd() { } override fun onRichi() { } override fun onChi() { } override fun onPon() { } override fun onKan() { } override fun onRon() { } override fun onReceive(event: RoundEvent): RoundEventResponse { val response: RoundEventResponse = RoundEventResponse() if (event.to == model) { when(event.action) { EVENT_LOOP_TSUMO -> { commander.receive(event.hai!!) val basis = commander.getBasisByVisibleHai(rounder.getAllVisibleHai()) response.from = model response.action = ACTION_SUTE response.hai = commander.da(basis) if (model.tsumo.hai == response.hai) { model.tsumo.hai = null Thread.sleep(250L) } else { model.tehai.remove(response.hai!!) Thread.sleep(250L) model.tehai.put(model.tsumo.hai!!) model.tsumo.hai = null model.tehai.sort() } return response } } } else { } return response } override fun getObservable(event: RoundEvent, duration: Long): Observable<RoundEvent> { return commander.getObservable(event, duration) } override fun isChankan(): Boolean = false override fun isRich(): Boolean = false override fun isDoubleRich(): Boolean = false override fun isTsumo(): Boolean = false override fun getJikaze(): Hai { return when(jikaze) { Kaze.EAST -> Hai(HaiType.E) Kaze.SOUTH -> Hai(HaiType.S) Kaze.WEST -> Hai(HaiType.W) Kaze.NORTH -> Hai(HaiType.N) } } override fun isRinshankaihoh(): Boolean = false override fun isIppatsu(): Boolean = false override fun isParent(): Boolean = false }
mit
31c54dbc2c2e90e2ec666e3772621da4
26.425532
91
0.599948
4.414384
false
false
false
false
Setekh/Gleipnir-Graphics
src/main/kotlin/eu/corvus/corax/app/timers/NanoTimer.kt
1
2354
/** * Copyright (c) 2013-2019 Corvus Corax Entertainment * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of Corvus Corax Entertainment 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 eu.corvus.corax.app.timers import eu.corvus.corax.app.Timer class NanoTimer: Timer() { companion object { const val Resolution = 1000000000L const val InverseResolution = (1f / Resolution).toLong() } private var startTime: Long = 0 private var previousTime: Long = 0 override fun getTime(): Long = System.nanoTime() - startTime override val resolution: Long get() = Resolution override val inverseResolution: Long get() = InverseResolution init { startTime = System.nanoTime() } override fun tick() { timePerFrame = (getTime() - previousTime) * (1.0f / Resolution) framePerSecond = (1.0f / timePerFrame).toInt() previousTime = getTime() } }
bsd-3-clause
9859d4a29f8916c50addde18be9b6e5f
38.25
81
0.730246
4.726908
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/component/OutOverDecorator.kt
1
1193
package com.soywiz.korge.component import com.soywiz.korge.input.* import com.soywiz.korge.view.* @Deprecated("Use decorateOutOverSimple") fun <T : View> T.decorateOutOver(onOver: (T) -> Unit = { }, onOut: (T) -> Unit = { }): T { onOut(this) mouse { this.over { onOver(this@decorateOutOver) } this.out { if (it.input.numActiveTouches == 0) onOut(this@decorateOutOver) } this.upOutside { onOut(this@decorateOutOver) } } return this } fun <T : View> T.decorateOutOverAlpha(overAlpha: () -> Double = { 1.0 }, outAlpha: () -> Double = { 0.75 }): T { return decorateOutOverSimple() } fun <T : View> T.decorateOutOverSimple(onEvent: (view: T, over: Boolean) -> Unit = { view, over -> }): T { val view = this onEvent(view, false) mouse { this.over { onEvent(view, true) } this.out { if (it.input.numActiveTouches == 0) onEvent(view, false) } this.upOutside { onEvent(view, false) } } return this } fun <T : View> T.decorateOutOverAlphaSimple(alpha: (over: Boolean) -> Double = { if (it) 1.0 else 0.75 }): T { return decorateOutOverSimple { view, over -> view.alpha = alpha(over) } }
apache-2.0
93b211c11b4e77642317e7e09891ec9d
32.138889
112
0.615256
3.181333
false
false
false
false
ArdentDiscord/ArdentKotlin
src/main/kotlin/commands/games/GameHelperCommands.kt
1
10908
package commands.games /* import events.Category import events.Command import main.waiter import net.dv8tion.jda.api.events.message.MessageReceivedEvent import translation.tr import utils.* import utils.discord.embed import utils.discord.send import utils.discord.toFancyString import utils.discord.toUser import utils.discord.toUsers import utils.functionality.Emoji import utils.functionality.Settings import java.util.concurrent.TimeUnit class Cancel : Command(Category.GAMES, "cancel", "cancel a currently running game") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { var found = false gamesInLobby.forEach { game -> if (game.creator == event.author.id) { found = true event.channel.send("${Emoji.HEAVY_EXCLAMATION_MARK_SYMBOL}" + "Are you sure you want to cancel your __{0}__ game? Type **".tr(event, game.type.readable) + "yes".tr(event) + "** if so or **" + "no".tr(event) + "** if you're not sure.".tr(event, game.type.readable) + "\n" + "Current players in lobby: *{0}*".tr(event, game.players.toUsers())) waiter.waitForMessage(Settings(event.author.id, event.channel.id, event.guild.id), { message -> if (message.contentRaw.startsWith("ye") || message.contentRaw.startsWith("yes".tr(event))) { game.cancel(event.member!!) } else event.channel.send("${Emoji.BALLOT_BOX_WITH_CHECK} " + "I'll keep the game in lobby".tr(event)) }, { event.channel.send("You're not the creator of a game in lobby!".tr(event) + " ${Emoji.NO_ENTRY_SIGN}") }) } } if (!found) event.channel.send("You're not the creator of a game in lobby!".tr(event) + " ${Emoji.NO_ENTRY_SIGN}") } } class Forcestart : Command(Category.GAMES, "start", "manually start a game", "forcestart") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { gamesInLobby.forEach { game -> if (game.creator == event.author.id && game.channel.guild == event.guild) { if (game.players.size == 1 && game.type != GameType.TRIVIA) event.channel.send("You can't force start a game with only **1** person!".tr(event)) else game.startEvent() return } } event.channel.send("You're not the creator of a game in lobby!".tr(event) + " ${Emoji.NO_ENTRY_SIGN}") } fun registerSubcommands() { } } class AcceptInvitation : Command(Category.GAMES, "accept", "accept an invitation to a game") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { if (event.member!!.isInGameOrLobby()) event.channel.send("You can't join another game! You must leave the game you're currently in first".tr(event)) else { gamesInLobby.forEach { game -> if (checkInvite(event, game)) return } event.channel.send("You must be invited by the creator of a game to join!".tr(event)) } } fun registerSubcommands() { } } class JoinGame : Command(Category.GAMES, "join", "join a game in lobby") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { if (arguments.size == 1) { val id = arguments[0].replace("#", "").toIntOrNull() if (id == null) { event.channel.send("You need to include a Game ID! Example: **{0}join #123456**".tr(event, event.guild.getPrefix())) return } gamesInLobby.forEach { game -> if (game.channel.guild == event.guild) { if (event.member!!.isInGameOrLobby()) event.channel.send("You can't join another game! You must leave the game you're currently in first".tr(event)) else { if (game.isPublic || checkInvite(event, game)) { game.players.add(event.author.id) event.channel.send("**{0}** has joined **{1}**'s game of {2}".tr(event, event.author.toFancyString(), game.creator.toUser()?.toFancyString() ?: "unknown", game.type.readable) + "\n" + "Current players in lobby: *{0}*".tr(event, game.players.toUsers())) } } return } } event.channel.send("There's not a game in lobby with the ID of **#{0}**".tr(event, id)) } else event.channel.send("You need to include a Game ID! Example: **{0}join #123456**".tr(event, event.guild.getPrefix())) } } class LeaveGame : Command(Category.GAMES, "leavegame", "leave a game you're currently queued for", "lg") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { gamesInLobby.forEach { game -> if (game.creator == event.author.id && game.channel.guild == event.guild) { event.channel.send("You can't leave the game that you've started! If you want to cancel the game, type **{0}cancel**".tr(event, event.guild.getPrefix())) return } else if (game.players.contains(event.author.id)) { game.players.remove(event.author.id) event.channel.send("{0}, you successfully left **{1}**'s game".tr(event, event.author.asMention, game.creator.toUser()?.toFancyString() ?: "unknown")) return } } event.channel.send("You're not in a game lobby!".tr(event)) } } class Gamelist : Command(Category.GAMES, "gamelist", "show a list of all currently running games") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { val embed = event.member!!.embed("Games in Lobby", event.channel) val builder = StringBuilder() .append("**" + "Red means that the game is in lobby, Green that it's currently ingame".tr(event) + "**") if (gamesInLobby.isEmpty() && activeGames.isEmpty()) event.channel.send("\n\n" + "There are no games in lobby or ingame right now. You can start one though :) Type {0}help to see a list of game commands".tr(event, event.guild.getPrefix())) else { gamesInLobby.forEach { builder.append("\n\n ${Emoji.LARGE_RED_CIRCLE}") .append(" **${it.type.readable}** [**${it.players.size}** / **${it.playerCount}**] " + "created by".tr(event) + " __${it.creator.toUser()?.toFancyString()}__ | ${it.players.toUsers()}") } activeGames.forEach { builder.append("\n\n ${Emoji.LARGE_GREEN_CIRCLE}") .append(" **${it.type.readable}** [**${it.players.size}** / **${it.playerCount}**] " + "created by".tr(event) + " __${it.creator.toUser()?.toFancyString()}__ | ${it.players.toUsers()}") } builder.append("\n\n" + "__Take Note__: You can run only one game of each type at a time in this server unless you become an Ardent patron".tr(event)) event.channel.send(embed.setDescription(builder.toString())) } } } class Decline : Command(Category.GAMES, "decline", "decline a pending game invite") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { if (invites.containsKey(event.author.id)) { val game = invites[event.author.id]!! event.channel.send("{0} declined an invite to **{1}**'s game of **{2}**".tr(event, event.author.asMention, game.creator.toUser()?.toFancyString() ?: "unknown", game.type.readable)) invites.remove(event.author.id) } else event.channel.send("You don't have a pending invite to decline!".tr(event)) } } class InviteToGame : Command(Category.GAMES, "gameinvite", "invite people to your game!", "ginvite", "gi") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { gamesInLobby.forEach { game -> if (game.creator == event.author.id && game.channel.guild == event.guild) { if (game.isPublic) { event.channel.send("You don't need to invite people to a public game! Everyone can join".tr(event)) return } val mentionedUsers = event.message.mentionedUsers if (mentionedUsers.size == 0 || mentionedUsers[0].isBot) event.channel.send("You need to mention at least one member to invite them".tr(event)) else { mentionedUsers.forEach { toInvite -> when { invites.containsKey(toInvite.id) -> event.channel.send("You can't invite a member who already has a pending invite!".tr(event)) toInvite.isInGameOrLobby() -> event.channel.send("This person is already in a lobby or ingame!".tr(event)) else -> { invites.put(toInvite.id, game) event.channel.send("{0}, you're being invited by {1} to join a game of **{2}**! Type *{3}accept* to accept this invite and join the game or decline by typing *{3}decline*".tr(event, toInvite.asMention, event.member!!.asMention, game.type.readable, event.guild.getPrefix())) val delay = 45 waiter.executor.schedule({ if (invites.containsKey(toInvite.id)) { event.channel.send("{0}, your invite to **{1}**'s game has expired after {2} seconds.".tr(event, toInvite.asMention, game.creator.toUser()?.toFancyString() ?: "unknown", delay)) invites.remove(toInvite.id) } }, delay.toLong(), TimeUnit.SECONDS) } } } } return } } event.channel.send("You're not the creator of a game in lobby!".tr(event) + " ${Emoji.NO_ENTRY_SIGN}") } } fun checkInvite(event: MessageReceivedEvent, game: Game): Boolean { return if (invites.containsKey(event.author.id) && invites[event.author.id]!!.gameId == game.gameId) { invites.remove(event.author.id) game.players.add(event.author.id) event.channel.send("**{0}** has joined **{1}**'s game of {2}".tr(event, event.author.toFancyString(), game.creator.toUser()?.toFancyString() ?: "unknown", game.type.readable) + "\n" + "Current players in lobby: *{0}*".tr(event, game.players.toUsers())) true } else false } */
apache-2.0
1d94df293debbb7ea7a904e2929b471e
56.415789
305
0.581683
4.12869
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/LoginWebviewFragment.kt
1
13412
package com.pennapps.labs.pennmobile import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.View.INVISIBLE import android.view.ViewGroup import android.webkit.* import android.widget.Button import android.widget.LinearLayout import android.widget.Toast import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import com.pennapps.labs.pennmobile.api.StudentLife import com.pennapps.labs.pennmobile.api.Platform import com.pennapps.labs.pennmobile.api.Platform.platformBaseUrl import com.pennapps.labs.pennmobile.classes.AccessTokenResponse import com.pennapps.labs.pennmobile.classes.Account import com.pennapps.labs.pennmobile.classes.GetUserResponse import com.pennapps.labs.pennmobile.classes.SaveAccountResponse import kotlinx.android.synthetic.main.fragment_login_webview.view.* import org.apache.commons.lang3.RandomStringUtils import retrofit.Callback import retrofit.RetrofitError import retrofit.client.Response import java.nio.charset.Charset import java.security.KeyStore import java.security.MessageDigest import java.util.* import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.SecretKey import javax.crypto.spec.IvParameterSpec class LoginWebviewFragment : Fragment() { lateinit var webView: WebView lateinit var headerLayout: LinearLayout lateinit var cancelButton: Button lateinit var user: Account private lateinit var mStudentLife: StudentLife private var mPlatform: Platform? = null private lateinit var mActivity: MainActivity lateinit var sp: SharedPreferences lateinit var codeChallenge: String lateinit var codeVerifier: String lateinit var platformAuthUrl: String lateinit var clientID: String lateinit var redirectUri: String override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_login_webview, container, false) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mStudentLife = MainActivity.studentLifeInstance mPlatform = MainActivity.platformInstance arguments?.let { user = arguments?.getSerializable("user") as Account } mActivity = activity as MainActivity sp = PreferenceManager.getDefaultSharedPreferences(mActivity) // These values are added to the BuildConfig at runtime, to allow GitHub Actions // to build the app without pushing the secrets to GitHub clientID = BuildConfig.PLATFORM_CLIENT_ID redirectUri = BuildConfig.PLATFORM_REDIRECT_URI codeVerifier = RandomStringUtils.randomAlphanumeric(64) codeChallenge = getCodeChallenge(codeVerifier) platformAuthUrl = platformBaseUrl + "/accounts/authorize/?response_type=code&client_id=" + clientID + "&redirect_uri=" + redirectUri + "&code_challenge_method=S256" + "&code_challenge=" + codeChallenge + "&scope=read+introspection&state=" } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) webView = view.findViewById(R.id.webView) headerLayout = view.linear_layout cancelButton = view.findViewById(R.id.cancel_button) webView.loadUrl(platformAuthUrl) val webSettings = webView.settings webSettings.javaScriptEnabled = true webSettings.javaScriptCanOpenWindowsAutomatically = true webView.webViewClient = MyWebViewClient() cancelButton.setOnClickListener { mActivity.startLoginFragment() } } private fun encryptPassword(password: String) { if (Build.VERSION.SDK_INT >= 26) { var secretKey = createSecretKey() as SecretKey var cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7) cipher.init(Cipher.ENCRYPT_MODE, secretKey) var encryptionIv = cipher.iv var passwordBytes = password.toByteArray(Charset.forName("UTF-8")) var encryptedPasswordBytes = cipher.doFinal(passwordBytes) var encryptedPassword = Base64.getEncoder().encodeToString(encryptedPasswordBytes) //save the encrypted password val spEditor = sp.edit() spEditor.putString("penn_password", encryptedPassword) spEditor.apply() spEditor.commit() spEditor.putString("encryptionIv", Base64.getEncoder().encodeToString(encryptionIv)) spEditor.apply() spEditor.commit() } } private fun getDecodedPassword(): String? { if (Build.VERSION.SDK_INT >= 26) { var base64EncryptedPassword = sp.getString("penn_password", "null") var base64EncryptionIv = sp.getString("encryptionIv", "null") var encryptionIv = Base64.getDecoder().decode(base64EncryptionIv) var encryptedPassword = Base64.getDecoder().decode(base64EncryptedPassword) var keyStore = KeyStore.getInstance("AndroidKeyStore") keyStore.load(null) var secretkey = keyStore.getKey("Key", null) as SecretKey var cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7) cipher.init(Cipher.DECRYPT_MODE, secretkey, IvParameterSpec(encryptionIv)) var passwordBytes = cipher.doFinal(encryptedPassword) var password = String(passwordBytes, Charset.forName("UTF-8")) return password } else { return null } } private fun saveUsername(username: String) { val editor = sp.edit() editor.putString(getString(R.string.penn_user), username) editor.apply() } private fun createSecretKey(): SecretKey? { if (Build.VERSION.SDK_INT >= 23) { val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") keyGenerator.init(KeyGenParameterSpec.Builder("Key", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setUserAuthenticationRequired(false) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) .build()) return keyGenerator.generateKey() } return null } inner class MyWebViewClient : WebViewClient() { override fun onReceivedHttpError(view: WebView?, request: WebResourceRequest?, errorResponse: WebResourceResponse?) { super.onReceivedHttpError(view, request, errorResponse) view?.visibility = INVISIBLE headerLayout.visibility = INVISIBLE } override fun shouldOverrideUrlLoading(view: WebView?, url: String): Boolean { if (url.contains("callback") && url.contains("?code=")) { val urlArr = url.split("?code=").toTypedArray() val authCode = urlArr[urlArr.size - 1] initiateAuthentication(authCode) } if (url.contains("weblogin") && url.contains("pennkey")) { if (Build.VERSION.SDK_INT >= 19) { webView.evaluateJavascript("document.getElementById('pennname').value;", ValueCallback<String> { s -> if (s != null || s != "null") { saveUsername(s) } }) webView.evaluateJavascript("document.getElementById('password').value;", ValueCallback<String> { s -> if (s != null || s != "null") { encryptPassword(s) } }) } } return super.shouldOverrideUrlLoading(view, url) } } private fun initiateAuthentication(authCode: String) { mPlatform?.getAccessToken(authCode, "authorization_code", clientID, redirectUri, codeVerifier, object : Callback<AccessTokenResponse> { override fun success(t: AccessTokenResponse?, response: Response?) { if (response?.status == 200) { val accessToken = t?.accessToken val editor = sp.edit() editor.putString(getString(R.string.access_token), accessToken) editor.putString(getString(R.string.refresh_token), t?.refreshToken) editor.putString(getString(R.string.expires_in), t?.expiresIn) val calendar = Calendar.getInstance() calendar.time = Date() val expiresInInt = t?.expiresIn!!.toInt() val date = Date(System.currentTimeMillis().plus(expiresInInt)) //or simply new Date(); editor.putLong(getString(R.string.token_generated), date.time) editor.apply() getUser(accessToken) } } override fun failure(error: RetrofitError) { Log.e("Accounts", "Error fetching access token $error", error) Toast.makeText(mActivity, "Error logging in", Toast.LENGTH_SHORT).show() mActivity.startLoginFragment() } }) } private fun getUser(accessToken: String?) { mPlatform?.getUser("Bearer $accessToken", accessToken, object : Callback<GetUserResponse> { override fun success(t: GetUserResponse?, response: Response?) { val user = t?.user val editor = sp.edit() editor.putString(getString(R.string.first_name), user?.firstName) editor.putString(getString(R.string.last_name), user?.lastName) var initials = "" try { initials = initials + user?.firstName?.first() + user?.lastName?.first() initials.capitalize() } catch (ignored: Exception) { } editor.putString(getString(R.string.initials), initials) editor.putString(getString(R.string.email_address), user?.email) editor.putString(getString(R.string.pennkey), user?.username) editor.apply() mActivity.startHomeFragment() // saveAccount(Account(user?.firstName, user?.lastName, // user?.username, user?.pennid, user?.email, user?.affiliation), user?.username.toString(), accessToken) } override fun failure(error: RetrofitError) { Log.e("Accounts", "Error getting user $error") Toast.makeText(mActivity, "Error logging in", Toast.LENGTH_SHORT).show() mActivity.startLoginFragment() } }) } private fun saveAccount(account: Account, pennkey: String, accessToken: String?) { mStudentLife.saveAccount("Bearer $accessToken", pennkey, account, object : Callback<SaveAccountResponse> { override fun success(t: SaveAccountResponse?, response: Response?) { val editor = sp.edit() editor.putString(getString(R.string.accountID), t?.accountID) editor.apply() // After saving the account, go to homepage mActivity.startHomeFragment() } override fun failure(error: RetrofitError) { Log.e("Accounts", "Error saving account $error", error) Toast.makeText(mActivity, "Error logging in", Toast.LENGTH_SHORT).show() mActivity.startLoginFragment() } }) } private fun getCodeChallenge(codeVerifier: String): String { // Hash the code verifier val md = MessageDigest.getInstance("SHA-256") val byteArr = md.digest(codeVerifier.toByteArray()) // Base-64 encode var codeChallenge = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Base64.getEncoder().encodeToString(byteArr) } else { String( android.util.Base64.encode(byteArr, android.util.Base64.DEFAULT), Charsets.UTF_8) } // Replace characters to make it web safe codeChallenge = codeChallenge.replace("=", "") codeChallenge = codeChallenge.replace("+", "-") codeChallenge = codeChallenge.replace("/", "_") return codeChallenge } }
mit
29c3c002f112449e5b344a85dbd917f8
43.71
160
0.61527
5.200465
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/CreateUserBlockTask.kt
1
4735
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.task import android.content.ContentValues import android.content.Context import android.widget.Toast import de.vanita5.microblog.library.MicroBlog import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.mastodon.Mastodon import org.mariotaku.sqliteqb.library.Expression import de.vanita5.twittnuker.Constants import de.vanita5.twittnuker.R import de.vanita5.twittnuker.annotation.AccountType import de.vanita5.twittnuker.constant.nameFirstKey import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable import de.vanita5.twittnuker.extension.model.api.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.event.FriendshipTaskEvent import de.vanita5.twittnuker.provider.TwidereDataStore.CachedRelationships import de.vanita5.twittnuker.provider.TwidereDataStore.Statuses import de.vanita5.twittnuker.util.DataStoreUtils import de.vanita5.twittnuker.util.Utils open class CreateUserBlockTask( context: Context, val filterEverywhere: Boolean = false ) : AbsFriendshipOperationTask(context, FriendshipTaskEvent.Action.BLOCK), Constants { @Throws(MicroBlogException::class) override fun perform(details: AccountDetails, args: Arguments): ParcelableUser { when (details.type) { AccountType.MASTODON -> { val mastodon = details.newMicroBlogInstance(context, Mastodon::class.java) mastodon.blockUser(args.userKey.id) return mastodon.getAccount(args.userKey.id).toParcelable(details) } AccountType.FANFOU -> { val fanfou = details.newMicroBlogInstance(context, MicroBlog::class.java) return fanfou.createFanfouBlock(args.userKey.id).toParcelable(details, profileImageSize = profileImageSize) } else -> { val twitter = details.newMicroBlogInstance(context, MicroBlog::class.java) return twitter.createBlock(args.userKey.id).toParcelable(details, profileImageSize = profileImageSize) } } } override fun succeededWorker(details: AccountDetails, args: Arguments, user: ParcelableUser) { val resolver = context.contentResolver Utils.setLastSeen(context, args.userKey, -1) for (uri in DataStoreUtils.STATUSES_ACTIVITIES_URIS) { val where = Expression.and( Expression.equalsArgs(Statuses.ACCOUNT_KEY), Expression.equalsArgs(Statuses.USER_KEY) ) val whereArgs = arrayOf(args.accountKey.toString(), args.userKey.toString()) resolver.delete(uri, where.sql, whereArgs) } // I bet you don't want to see this user in your auto complete list. val values = ContentValues() values.put(CachedRelationships.ACCOUNT_KEY, args.accountKey.toString()) values.put(CachedRelationships.USER_KEY, args.userKey.toString()) values.put(CachedRelationships.BLOCKING, true) values.put(CachedRelationships.FOLLOWING, false) values.put(CachedRelationships.FOLLOWED_BY, false) resolver.insert(CachedRelationships.CONTENT_URI, values) if (filterEverywhere) { DataStoreUtils.addToFilter(context, listOf(user), true) } } override fun showSucceededMessage(params: Arguments, user: ParcelableUser) { val nameFirst = kPreferences[nameFirstKey] val message = context.getString(R.string.message_blocked_user, manager.getDisplayName(user, nameFirst)) Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } }
gpl-3.0
376a54f314f5ab0d0e271d921cd69bac
43.679245
99
0.717423
4.610516
false
false
false
false
AndroidX/androidx
wear/compose/compose-material/src/androidAndroidTest/kotlin/androidx/wear/compose/material/ToggleChipScreenshotTest.kt
3
6783
/* * 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.wear.compose.material import android.os.Build import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.testutils.assertAgainstGolden import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.LayoutDirection import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import androidx.test.screenshot.AndroidXScreenshotTestRule import org.junit.Rule import org.junit.Test import org.junit.rules.TestName import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) class ToggleChipScreenshotTest { @get:Rule val rule = createComposeRule() @get:Rule val screenshotRule = AndroidXScreenshotTestRule(SCREENSHOT_GOLDEN_PATH) @get:Rule val testName = TestName() @Test fun toggle_chip_checkbox() = verifyScreenshot { sampleToggleChip(checked = true) } @Test fun toggle_chip_checkbox_unchecked() = verifyScreenshot { sampleToggleChip(checked = false) } @Test fun toggle_chip_checkbox_rtl() = verifyScreenshot(layoutDirection = LayoutDirection.Rtl) { sampleToggleChip() } @Test fun toggle_chip_radio() = verifyScreenshot { val checked = true sampleToggleChip( toggleControl = { Icon( imageVector = ToggleChipDefaults.radioIcon(checked), contentDescription = "" ) }, checked = checked ) } @Test fun toggle_chip_radio_unchecked() = verifyScreenshot { val checked = false sampleToggleChip( toggleControl = { Icon( imageVector = ToggleChipDefaults.radioIcon(checked), contentDescription = "" ) }, checked = checked, ) } @Test fun toggle_chip_switch_checked() = verifyScreenshot { val checked = true sampleToggleChip( toggleControl = { Icon( imageVector = ToggleChipDefaults.switchIcon(checked), contentDescription = "" ) }, checked = checked, ) } @Test fun toggle_chip_switch_unchecked() = verifyScreenshot { val checked = false sampleToggleChip( colors = ToggleChipDefaults.toggleChipColors( uncheckedToggleControlColor = ToggleChipDefaults.SwitchUncheckedIconColor ), toggleControl = { // For Switch toggle controls the Wear Material UX guidance is to set the // unselected toggle control color to ToggleChipDefaults.switchUncheckedIconColor() // rather than the default. Icon( imageVector = ToggleChipDefaults.switchIcon(checked), contentDescription = "" ) }, checked = checked, ) } @Test fun toggle_chip_disabled() = verifyScreenshot { sampleToggleChip( enabled = false, ) } @Test fun split_toggle_chip() = verifyScreenshot { sampleSplitToggleChip() } @Test fun split_toggle_chip_rtl() = verifyScreenshot(layoutDirection = LayoutDirection.Rtl) { sampleSplitToggleChip() } @Test fun split_toggle_chip_disabled() = verifyScreenshot { sampleSplitToggleChip(enabled = false) } @Composable private fun sampleToggleChip( colors: ToggleChipColors = ToggleChipDefaults.toggleChipColors(), enabled: Boolean = true, checked: Boolean = true, toggleControl: @Composable () -> Unit = { Icon( imageVector = ToggleChipDefaults.checkboxIcon(checked = checked), contentDescription = "" ) }, ) { ToggleChip( appIcon = { TestIcon() }, label = { Text("Standard toggle chip", maxLines = 1, overflow = TextOverflow.Ellipsis) }, secondaryLabel = { Text("Secondary label", maxLines = 1, overflow = TextOverflow.Ellipsis) }, checked = checked, enabled = enabled, colors = colors, toggleControl = toggleControl, onCheckedChange = {}, modifier = Modifier.testTag(TEST_TAG), ) } @Composable private fun sampleSplitToggleChip( enabled: Boolean = true, ) { SplitToggleChip( label = { Text("Split chip", maxLines = 1, overflow = TextOverflow.Ellipsis) }, secondaryLabel = { Text("Secondary", maxLines = 1, overflow = TextOverflow.Ellipsis) }, checked = true, enabled = enabled, toggleControl = { Icon( imageVector = ToggleChipDefaults.checkboxIcon(checked = true), contentDescription = "" ) }, onCheckedChange = {}, onClick = {}, modifier = Modifier.testTag(TEST_TAG), ) } private fun verifyScreenshot( layoutDirection: LayoutDirection = LayoutDirection.Ltr, content: @Composable () -> Unit ) { rule.setContentWithTheme { CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) { content() } } rule.onNodeWithTag(TEST_TAG) .captureToImage() .assertAgainstGolden(screenshotRule, testName.methodName) } }
apache-2.0
2fccb8be613aa8ab8275cc2e6c0be07b
29.831818
99
0.604157
5.340945
false
true
false
false
TeamWizardry/LibrarianLib
modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/screens/TextEmbedsTestScreen.kt
1
1729
package com.teamwizardry.librarianlib.facade.test.screens import com.teamwizardry.librarianlib.facade.FacadeScreen import com.teamwizardry.librarianlib.facade.layers.RectLayer import com.teamwizardry.librarianlib.facade.layers.TextLayer import com.teamwizardry.librarianlib.facade.text.SpriteEmbed import com.teamwizardry.librarianlib.mosaic.Mosaic import dev.thecodewarrior.bitfont.typesetting.MutableAttributedString import dev.thecodewarrior.bitfont.typesetting.TextAttribute import net.minecraft.text.Text import net.minecraft.util.Identifier import java.awt.Color class TextEmbedsTestScreen(title: Text): FacadeScreen(title) { init { val dirt = Mosaic(Identifier("minecraft:textures/block/dirt.png"), 8, 8) val dirtEmbed = SpriteEmbed(9, 7, 1, 0, -7, dirt.getSprite(""), false) val stone = Mosaic(Identifier("minecraft:textures/block/stone.png"), 8, 8) val stoneEmbed = SpriteEmbed(9, 7, 1, 0, -7, stone.getSprite(""), false) val diamond = Mosaic(Identifier("minecraft:textures/item/diamond.png"), 8, 8) val diamondEmbed = SpriteEmbed(9, 7, 1, 0, -7, diamond.getSprite(""), false) val bg = RectLayer(Color.WHITE, 0, 0, 300, 200) val text = TextLayer(25, 25, 250, 150, "") val str = MutableAttributedString("1x") .append("\uE000", TextAttribute.textEmbed to dirtEmbed) .append("Dirt + 1x") .append("\uE000", TextAttribute.textEmbed to stoneEmbed) .append("Stone = 1x") .append("\uE000", TextAttribute.textEmbed to diamondEmbed) .append("Diamond") text.attributedText = str main.size = bg.size main.add(bg, text) } companion object { } }
lgpl-3.0
a8a10529ee61abf8a4f15c65f3be130a
42.25
85
0.693464
3.911765
false
true
false
false
charleskorn/batect
app/src/main/kotlin/batect/config/io/deserializers/DependencySetSerializer.kt
1
3280
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.config.io.deserializers import batect.config.io.ConfigurationException import com.charleskorn.kaml.YamlInput import kotlinx.serialization.CompositeDecoder import kotlinx.serialization.Decoder import kotlinx.serialization.Encoder import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialDescriptor import kotlinx.serialization.Serializer import kotlinx.serialization.internal.HashSetClassDesc import kotlinx.serialization.internal.StringSerializer import kotlinx.serialization.set @Serializer(forClass = Set::class) internal object DependencySetSerializer : KSerializer<Set<String>> { val elementSerializer = StringSerializer override val descriptor: SerialDescriptor = HashSetClassDesc(elementSerializer.descriptor) override fun deserialize(decoder: Decoder): Set<String> { val input = decoder.beginStructure(descriptor, elementSerializer) val result = read(input) input.endStructure(descriptor) return result } private fun read(input: CompositeDecoder): Set<String> { val size = input.decodeCollectionSize(descriptor) while (true) { when (val index = input.decodeElementIndex(descriptor)) { CompositeDecoder.READ_ALL -> return readAll(input, size) else -> return readUntilDone(input, index) } } } private fun readAll(input: CompositeDecoder, size: Int): Set<String> { val soFar = mutableSetOf<String>() for (currentIndex in 0..size) { soFar.add(readSingle(input, currentIndex, soFar)) } return soFar } private fun readUntilDone(input: CompositeDecoder, firstIndex: Int): Set<String> { var currentIndex = firstIndex val soFar = mutableSetOf<String>() while (currentIndex != CompositeDecoder.READ_DONE) { soFar.add(readSingle(input, currentIndex, soFar)) currentIndex = input.decodeElementIndex(descriptor) } return soFar } private fun readSingle(input: CompositeDecoder, index: Int, soFar: Set<String>): String { val value = input.decodeSerializableElement(descriptor, index, elementSerializer) if (value in soFar) { val location = (input as YamlInput).getCurrentLocation() throw ConfigurationException(getDuplicateValueMessage(value), location.line, location.column) } return value } private fun getDuplicateValueMessage(value: String) = "The dependency '$value' is given more than once" override fun serialize(encoder: Encoder, obj: Set<String>) = StringSerializer.set.serialize(encoder, obj) }
apache-2.0
816d288b623efe61b43f1bc824e98d0e
33.526316
109
0.714634
4.816446
false
false
false
false
androidx/androidx
compose/integration-tests/docs-snippets/src/main/java/androidx/compose/integration/docs/layout/CustomLayouts.kt
3
5105
// ktlint-disable indent https://github.com/pinterest/ktlint/issues/967 /* * 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. */ // Ignore lint warnings in documentation snippets @file:Suppress("unused", "UNUSED_PARAMETER", "UNUSED_VARIABLE") package androidx.compose.integration.docs.layout import androidx.compose.foundation.layout.padding import androidx.compose.integration.docs.layout.CustomLayoutsSnippet2.firstBaselineToTop import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.AlignmentLine import androidx.compose.ui.layout.FirstBaseline import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.layout import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /** * This file lets DevRel track changes to snippets present in * https://developer.android.com/jetpack/compose/layouts/custom * * No action required if it's modified. */ private object CustomLayoutsSnippet1 { /* Can't be compiled without returning layout() from Modifier.layout. See next snippet for possible changes. fun Modifier.customLayoutModifier(/*...*/) = layout { measurable, constraints -> // ... } */ } private object CustomLayoutsSnippet2 { fun Modifier.firstBaselineToTop( firstBaselineToTop: Dp ) = layout { measurable, constraints -> // Measure the composable val placeable = measurable.measure(constraints) // Check the composable has a first baseline check(placeable[FirstBaseline] != AlignmentLine.Unspecified) val firstBaseline = placeable[FirstBaseline] // Height of the composable with padding - first baseline val placeableY = firstBaselineToTop.roundToPx() - firstBaseline val height = placeable.height + placeableY layout(placeable.width, height) { // Where the composable gets placed placeable.placeRelative(0, placeableY) } } } private object CustomLayoutsSnippet3 { @Composable fun TextWithPaddingToBaselinePreview() { MyApplicationTheme { Text("Hi there!", Modifier.firstBaselineToTop(32.dp)) } } // @Preview @Composable fun TextWithNormalPaddingPreview() { MyApplicationTheme { Text("Hi there!", Modifier.padding(top = 32.dp)) } } } private object CustomLayoutsSnippet4 { /* Can't be compiled without returning layout() from Layout. See previous snippet for possible changes. @Composable fun MyBasicColumn( modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Layout( modifier = modifier, children = content ) { measurables, constraints -> // measure and position children given constraints logic here } } */ } private object CustomLayoutsSnippet5and6 { @Composable fun MyBasicColumn( modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Layout( modifier = modifier, content = content ) { measurables, constraints -> // Don't constrain child views further, measure them with given constraints // List of measured children val placeables = measurables.map { measurable -> // Measure each children measurable.measure(constraints) } // Set the size of the layout as big as it can layout(constraints.maxWidth, constraints.maxHeight) { // Track the y co-ord we have placed children up to var yPosition = 0 // Place children in the parent layout placeables.forEach { placeable -> // Position item on the screen placeable.placeRelative(x = 0, y = yPosition) // Record the y co-ord placed up to yPosition += placeable.height } } } } // Snippet 6 @Composable fun CallingComposable(modifier: Modifier = Modifier) { MyBasicColumn(modifier.padding(8.dp)) { Text("MyBasicColumn") Text("places items") Text("vertically.") Text("We've done it by hand!") } } } /* Fakes needed for snippets to build: */ @Composable private fun MyApplicationTheme(content: @Composable () -> Unit) { }
apache-2.0
f074294f2d0dbfbff6119be5864e9ce5
29.939394
98
0.648188
4.793427
false
false
false
false
androidx/androidx
camera/integration-tests/coretestapp/src/androidTest/java/androidx/camera/integration/core/camera2/SurfaceOrientedMeteringPointFactoryTest.kt
3
5912
/* * 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.camera.integration.core.camera2 import android.content.Context import android.util.Rational import androidx.camera.camera2.Camera2Config import androidx.camera.camera2.pipe.integration.CameraPipeConfig import androidx.camera.core.AspectRatio import androidx.camera.core.CameraSelector import androidx.camera.core.CameraXConfig import androidx.camera.core.ImageAnalysis import androidx.camera.core.MeteringPointFactory import androidx.camera.core.SurfaceOrientedMeteringPointFactory import androidx.camera.testing.CameraUtil import androidx.camera.testing.CameraXUtil import androidx.test.core.app.ApplicationProvider import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth import java.util.concurrent.TimeUnit import org.junit.After import org.junit.Assume import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @LargeTest @RunWith(Parameterized::class) @SdkSuppress(minSdkVersion = 21) class SurfaceOrientedMeteringPointFactoryTest( private val implName: String, private val cameraConfig: CameraXConfig ) { var pointFactory: SurfaceOrientedMeteringPointFactory? = null private var context: Context? = null @Before fun setUp() { context = ApplicationProvider.getApplicationContext() CameraXUtil.initialize(context!!, cameraConfig) pointFactory = SurfaceOrientedMeteringPointFactory(WIDTH, HEIGHT) } @After fun tearDown() { CameraXUtil.shutdown()[10000, TimeUnit.MILLISECONDS] } @Test fun defaultAreaSize() { val point = pointFactory!!.createPoint(0f, 0f) Truth.assertThat(point.size).isEqualTo(MeteringPointFactory.getDefaultPointSize()) Truth.assertThat(point.surfaceAspectRatio).isNull() } @Test fun createPointWithValidAreaSize() { val areaSize = 0.2f val point = pointFactory!!.createPoint(0f, 0f, areaSize) Truth.assertThat(point.size).isEqualTo(areaSize) Truth.assertThat(point.surfaceAspectRatio).isNull() } @Test fun createPointLeftTop_correctValueSet() { val meteringPoint = pointFactory!!.createPoint(0f, 0f) Truth.assertThat(meteringPoint.x).isEqualTo(0f) Truth.assertThat(meteringPoint.y).isEqualTo(0f) } @Test fun createPointLeftBottom_correctValueSet() { val meteringPoint2 = pointFactory!!.createPoint(0f, HEIGHT) Truth.assertThat(meteringPoint2.x).isEqualTo(0f) Truth.assertThat(meteringPoint2.y).isEqualTo(1f) } @Test fun createPointRightTop_correctValueSet() { val meteringPoint3 = pointFactory!!.createPoint(WIDTH, 0f) Truth.assertThat(meteringPoint3.x).isEqualTo(1f) Truth.assertThat(meteringPoint3.y).isEqualTo(0f) } @Test fun createPointRightBottom_correctValueSet() { val meteringPoint4 = pointFactory!!.createPoint(WIDTH, HEIGHT) Truth.assertThat(meteringPoint4.x).isEqualTo(1f) Truth.assertThat(meteringPoint4.y).isEqualTo(1f) } @Test fun createPointWithFoVUseCase_success() { Assume.assumeTrue(CameraUtil.hasCameraWithLensFacing(CameraSelector.LENS_FACING_BACK)) val imageAnalysis = ImageAnalysis.Builder() .setTargetName("ImageAnalysis") .build() val cameraSelector = CameraSelector.Builder().requireLensFacing( CameraSelector.LENS_FACING_BACK ).build() val camera = CameraUtil.createCameraAndAttachUseCase( context!!, cameraSelector, imageAnalysis ) val surfaceResolution = imageAnalysis.attachedSurfaceResolution val factory = SurfaceOrientedMeteringPointFactory( WIDTH, HEIGHT, imageAnalysis ) val point = factory.createPoint(0f, 0f) Truth.assertThat(point.surfaceAspectRatio).isEqualTo( Rational(surfaceResolution!!.width, surfaceResolution.height) ) InstrumentationRegistry.getInstrumentation() .runOnMainSync { // TODO: The removeUseCases() call might be removed after clarifying the // abortCaptures() issue in b/162314023. camera.removeUseCases(camera.useCases) } } @Test(expected = IllegalStateException::class) fun createPointWithFoVUseCase_FailedNotBound() { Assume.assumeTrue(CameraUtil.hasCameraWithLensFacing(CameraSelector.LENS_FACING_BACK)) val imageAnalysis = ImageAnalysis.Builder() .setTargetAspectRatio(AspectRatio.RATIO_4_3) .setTargetName("ImageAnalysis") .build() // This will throw IllegalStateException. SurfaceOrientedMeteringPointFactory( WIDTH, HEIGHT, imageAnalysis ) } companion object { private const val WIDTH = 480f private const val HEIGHT = 640f @JvmStatic @Parameterized.Parameters(name = "{0}") fun data() = listOf( arrayOf(Camera2Config::class.simpleName, Camera2Config.defaultConfig()), arrayOf(CameraPipeConfig::class.simpleName, CameraPipeConfig.defaultConfig()) ) } }
apache-2.0
5f7ef5aacb3cbd053306edd754854bcb
35.95625
94
0.713633
4.572312
false
true
false
false
androidx/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/TopAppBarSmallCenteredTokens.kt
3
1510
/* * 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. */ // VERSION: v0_103 // GENERATED CODE - DO NOT MODIFY BY HAND package androidx.compose.material3.tokens import androidx.compose.ui.unit.dp internal object TopAppBarSmallCenteredTokens { val AvatarShape = ShapeKeyTokens.CornerFull val AvatarSize = 30.0.dp val ContainerColor = ColorSchemeKeyTokens.Surface val ContainerElevation = ElevationTokens.Level0 val ContainerHeight = 64.0.dp val ContainerShape = ShapeKeyTokens.CornerNone val ContainerSurfaceTintLayerColor = ColorSchemeKeyTokens.SurfaceTint val HeadlineColor = ColorSchemeKeyTokens.OnSurface val HeadlineFont = TypographyKeyTokens.TitleLarge val LeadingIconColor = ColorSchemeKeyTokens.OnSurface val LeadingIconSize = 24.0.dp val OnScrollContainerElevation = ElevationTokens.Level2 val TrailingIconColor = ColorSchemeKeyTokens.OnSurfaceVariant val TrailingIconSize = 24.0.dp }
apache-2.0
5237ea1362c792e216912ed039f2e5c9
38.736842
75
0.772185
4.534535
false
false
false
false
MoonlightOwl/Yui
src/main/kotlin/totoro/yui/util/api/YandexSpeller.kt
1
1016
package totoro.yui.util.api import com.beust.klaxon.JsonArray import com.beust.klaxon.JsonObject import com.beust.klaxon.Parser import java.net.URL import java.net.URLEncoder object YandexSpeller { private const val charset = "UTF-8" fun correct(phrase: String): String { var result = phrase val raw = URL("http://speller.yandex.net/services/spellservice.json/" + "checkText?text=${URLEncoder.encode(phrase, charset)}").readText() @Suppress("UNCHECKED_CAST") val array = Parser().parse(StringBuilder(raw)) as JsonArray<JsonObject> array.forEach { json -> val word = json.string("word") val variants = json.array<String>("s") if (word != null) { result = if (variants != null && variants.isNotEmpty()) result.replace(word, variants.first(), true) else result.replace(word, "<rip>", true) } } return result } }
mit
0bd8fff6f328f6b8be2433bced013f64
32.866667
82
0.591535
4.323404
false
false
false
false
philo-dragon/CoolWeather-kotlin
app/src/main/java/com/pfl/coolweather/ui/activity/WeatherActivity.kt
1
7285
package com.pfl.coolweather.ui.activity import android.content.Intent import android.graphics.Color import android.os.Build import android.os.Bundle import android.preference.PreferenceManager import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.app.AppCompatActivity import android.view.Gravity import android.view.View import android.widget.TextView import android.widget.Toast import com.bumptech.glide.Glide import com.pfl.coolweather.R import com.pfl.coolweather.db.Weather import com.pfl.coolweather.service.AutoUpdateService import com.pfl.coolweather.util.HttpUtil import com.pfl.coolweather.util.Utility import kotlinx.android.synthetic.main.activity_weather.* import kotlinx.android.synthetic.main.aqi.* import kotlinx.android.synthetic.main.forecast.* import kotlinx.android.synthetic.main.now.* import kotlinx.android.synthetic.main.suggesting.* import kotlinx.android.synthetic.main.title.* import okhttp3.Call import okhttp3.Callback import okhttp3.Response import java.io.IOException class WeatherActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Build.VERSION.SDK_INT >= 21) { var decordView = window.decorView decordView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; View.SYSTEM_UI_FLAG_LAYOUT_STABLE window.statusBarColor = Color.TRANSPARENT } setContentView(R.layout.activity_weather) var prefs = PreferenceManager.getDefaultSharedPreferences(this) var weatherString: String? = prefs.getString("weather", null) var bingPic: String? = prefs.getString("bing_pic", null) var weatherId: String? if (null != weatherString) { var weatehr: Weather = Utility.handleWeatherResponse(weatherString)!! weatherId = weatehr.basic!!.id showWeatherInfo(weatehr) } else { weatherId = intent.getStringExtra("weather_id") sv_weather.visibility = View.INVISIBLE requestWeather(weatherId) } if (null != bingPic) { Glide.with(this@WeatherActivity).load(bingPic).into(img_backgroud) } else { loadBingPic() } //为SwipeRefreshLayout设置刷新时的颜色变化,最多可以设置4种 swipefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light) swipefreshLayout.setOnRefreshListener { requestWeather(weatherId) } tv_nev.setOnClickListener { drawerLayout.openDrawer(GravityCompat.START) } } fun getDrawerLayout(): DrawerLayout { return drawerLayout } fun getSwipefreshLayout(): SwipeRefreshLayout { return swipefreshLayout } /** * 根据天气id 请求城市天气信息 */ fun requestWeather(weatherId: String?) { var weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=0dff9c2f64ca467088a0853001b26d4d" HttpUtil.sendOkHttpRequest(weatherUrl, object : Callback { override fun onResponse(call: Call?, response: Response?) { var responstText = response?.body()?.string() var weather: Weather = Utility.handleWeatherResponse(responstText!!)!! runOnUiThread(object : Runnable { override fun run() { if (null != weather && "ok".equals(weather.status)) { var editor = PreferenceManager.getDefaultSharedPreferences(this@WeatherActivity).edit() editor.putString("weather", responstText) editor.apply() showWeatherInfo(weather) } else { Toast.makeText(this@WeatherActivity, "获取天气信息失败", Toast.LENGTH_SHORT).show() } swipefreshLayout.isRefreshing = false } }) } override fun onFailure(call: Call?, e: IOException?) { runOnUiThread(object : Runnable { override fun run() { Toast.makeText(this@WeatherActivity, "获取天气信息失败", Toast.LENGTH_SHORT).show() swipefreshLayout.isRefreshing = false } }) } }) loadBingPic() } /** * 加载每日一图 */ private fun loadBingPic() { val weatherUrl = "http://guolin.tech/api/bing_pic" HttpUtil.sendOkHttpRequest(weatherUrl, object : Callback { override fun onResponse(call: Call?, response: Response?) { val bingPic = response!!.body().string() var editor = PreferenceManager.getDefaultSharedPreferences(this@WeatherActivity).edit() editor.putString("bing_pic", bingPic) editor.apply() runOnUiThread(object : Runnable { override fun run() { Glide.with(this@WeatherActivity).load(bingPic).into(img_backgroud) } }) } override fun onFailure(call: Call?, e: IOException?) { e!!.printStackTrace() } }) } /** * 处理并展示 Weather实体类中的数据 */ private fun showWeatherInfo(weatehr: Weather) { if (weatehr != null && "ok".equals(weatehr.status)) { tv_city.text = weatehr.basic!!.city tv_update_time.text = weatehr.basic!!.update!!.loc!!.split(" ")[1] tv_degree.text = weatehr.now!!.tmp + "℃" tv_wetherinfo.text = weatehr.now!!.cond!!.txt ll_forecast.removeAllViews() weatehr.daily_forecast!!.forEach { var view = getLayoutInflater().inflate(R.layout.item_forecast, ll_forecast, false) view.findViewById<TextView>(R.id.tv_date).text = it.date view.findViewById<TextView>(R.id.tv_info).text = it.cond!!.txt_n view.findViewById<TextView>(R.id.tv_max).text = it.tmp!!.max view.findViewById<TextView>(R.id.tv_min).text = it.tmp!!.min ll_forecast.addView(view) } tv_aqi.text = weatehr.aqi!!.city!!.aqi tv_pm25.text = weatehr.aqi!!.city!!.pm25 tv_comfort.text = "舒适度: " + weatehr.suggestion!!.comf!!.txt tv_car_wash.text = "洗车指数: " + weatehr.suggestion!!.cw!!.txt tv_sport.text = "运动建议: " + weatehr.suggestion!!.sport!!.txt sv_weather.visibility = View.VISIBLE // 开启定时任务 var intent = Intent(this@WeatherActivity, AutoUpdateService::class.java) startService(intent) } else { Toast.makeText(this@WeatherActivity, "获取天气信息失败", Toast.LENGTH_SHORT).show() } } }
apache-2.0
31d60a7cd34fade9a51d076469649314
34.873737
119
0.606645
4.304848
false
false
false
false
yuncheolkim/gitmt
src/main/kotlin/com/joyouskim/Server.kt
1
682
package com.joyouskim import com.joyouskim.http.GitAction import com.joyouskim.log.COMMON import com.joyouskim.vertx.HttpServerVertx import io.vertx.core.Vertx import io.vertx.kotlin.lang.VertxOptions import java.util.logging.Logger /** * Created by jinyunzhe on 16/4/5. */ fun main(args: Array<String>) { val option = VertxOptions { } val vertx = Vertx.vertx() val http = HttpServerVertx() http.gitAction = GitAction() val bus = vertx.eventBus() vertx.deployVerticle(http,{ if (it.succeeded()) { COMMON.info("Http server start") } if (it.failed()) { COMMON.error("",it.cause()) } }) }
mit
d525583b21b83f76cbc492440dad1c1a
19.69697
44
0.639296
3.427136
false
false
false
false
world-federation-of-advertisers/virtual-people-common
src/main/kotlin/org/wfanet/virtualpeople/common/fieldfilter/utils/FieldUtil.kt
1
12702
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.virtualpeople.common.fieldfilter.utils import com.google.protobuf.Descriptors.Descriptor import com.google.protobuf.Descriptors.FieldDescriptor import com.google.protobuf.Message.Builder import com.google.protobuf.MessageOrBuilder /** * A container for value of protobuf field. * @param isSet whether the field is set. * @param value the return of the getter of protobuf reflection. Will be the default value of the * field when the field is not set. */ data class ProtoFieldValue<V>(val isSet: Boolean, val value: V) /** * In the protobuf message represented by [descriptor], get the field descriptors of the field, the * path of which is represented by [fullFieldName]. * * @param descriptor descriptor of the proto. * @param fullFieldName field name separated by ".". * @param allowRepeated If true, the last field in the path represented by [fullFieldName] is * allowed to be a repeated field. If false, no repeated field is allowed in the path. * * @return a list of FieldDescriptors in the order of the field name to access the nested field. */ fun getFieldFromProto( descriptor: Descriptor, fullFieldName: String, allowRepeated: Boolean = false ): List<FieldDescriptor> { val result: MutableList<FieldDescriptor> = mutableListOf() var currentDescriptor = descriptor val fieldNames = fullFieldName.split('.') for (i in fieldNames.indices) { val fieldDescriptor: FieldDescriptor = currentDescriptor.findFieldByName((fieldNames[i])) ?: error("The field name is invalid: $fullFieldName") result.add(fieldDescriptor) if (i != fieldNames.size - 1) { /** Can't call .messageType on the last field, since it could be a non-Message. */ currentDescriptor = fieldDescriptor.messageType } } if (result.isEmpty()) { /** This should never happen. */ error("Get empty field descriptor from $fullFieldName") } for (fieldDescriptor in result.take(result.size - 1)) { if (fieldDescriptor.isRepeated) { error("Repeated field is not allowed in the path: $fullFieldName") } } if (!allowRepeated && result.last().isRepeated) { error("Repeated field is not allowed in the path: $fullFieldName") } return result } /** * Gets the parent message of the field represented by [fieldDescriptors] from the [message]. * * Unset parent message is equivalent to an empty message. * * All elements except the last one in [fieldDescriptors] must refer to a protobuf Message. The * first element in [fieldDescriptors] must refer to a field in [message], Each of the rest elements * must refer to a field in the message referred by the previous element. * * The typical usage is to first call GetFieldFromProto(see above), to get fieldDescriptors for the * target field in [message], then call this function to get the parent message of the target field. * * Example: If we have a protobuf * ``` * message MsgA { * message MsgB { * optional int32 c = 1; * } * optional MsgB b = 1; * } * ``` * To get the field descriptors of MsgA.b.c: * ``` * fieldDescriptors = getFieldFromProto(MsgA().GetDescriptor(), "b.c")); * ``` * And if there is an MsgA object obj_a, to get the message obj_a.b: * ``` * output = getParentMessageFromProto(obj_a, fieldDescriptors); * ``` */ fun getParentMessageFromProto( message: MessageOrBuilder, fieldDescriptors: List<FieldDescriptor> ): MessageOrBuilder { /** * [fieldDescriptors] refers to a field in [message]. To get the parent message of the field, the * last entry in [fieldDescriptors] is unused. */ var result = message for (fieldDescriptor in fieldDescriptors.take(fieldDescriptors.size - 1)) { val temp = if (result is Builder) { result.getFieldBuilder(fieldDescriptor) } else { result.getField(fieldDescriptor) } ?: error("Message doesn't contain field ${fieldDescriptor.name}") if (temp is MessageOrBuilder) { result = temp } else { error("${fieldDescriptor.name} is not a proto MessageOrBuilder") } } return result } /** * Gets the value from the [message], with field name represented by [fieldDescriptor]. * * When called with unset field, returns default value. * * The field must be an immediate field of [message]. The corresponding C++ type of the field must * be [V]. */ inline fun <reified V> getImmediateValueFromProtoOrDefault( message: MessageOrBuilder, fieldDescriptor: FieldDescriptor ): V { val result = message.getField(fieldDescriptor) return if (result is V) { result } else if (result is Int && V::class == UInt::class) { result.toUInt() as V } else if (result is Long && V::class == ULong::class) { result.toULong() as V } else { error("The type of the field is not compatible to the target") } } /** * Same as GetImmediateValueFromProtoOrDefault, except that returns a [ProtoFieldValue], which also * indicates whether the field is set. */ inline fun <reified V> getImmediateValueFromProto( message: MessageOrBuilder, fieldDescriptor: FieldDescriptor ): ProtoFieldValue<V> { return ProtoFieldValue( message.hasField(fieldDescriptor), getImmediateValueFromProtoOrDefault(message, fieldDescriptor) ) } /** * Gets the value from the [message], with field path represented by [fieldDescriptors]. * * isSet of the return indicates whether the field is set. value of the return is the value of the * field, and will be the default value when isSet is false. * * All elements except the last one in [fieldDescriptors] must refer to a protobuf Message. The last * one in [fieldDescriptors] must refer to a field with [V]. The first element in [fieldDescriptors] * must refer to a field in [message], Each of the rest elements must refer to a field in the * message referred by the previous element. */ inline fun <reified V> getValueFromProto( message: MessageOrBuilder, fieldDescriptors: List<FieldDescriptor> ): ProtoFieldValue<V> { return getImmediateValueFromProto( getParentMessageFromProto(message, fieldDescriptors), fieldDescriptors.last() ) } /** * Sets the value to the [builder], with field name represented by [fieldDescriptor]. * * The field must be an immediate field of [builder]. The corresponding Kotlin type of the field * must be [V]. */ inline fun <reified V> setImmediateValueToProtoBuilder( builder: Builder, fieldDescriptor: FieldDescriptor, value: V ) { val fieldObject = builder.getField(fieldDescriptor) if (fieldObject is V) { builder.setField(fieldDescriptor, value) } else if (fieldObject is Int && V::class == UInt::class) { builder.setField(fieldDescriptor, (value as UInt).toInt()) } else if (fieldObject is Long && V::class == ULong::class) { builder.setField(fieldDescriptor, (value as ULong).toLong()) } else { error( "The type of the field is not compatible to the target. ${fieldObject.javaClass} vs ${V::class}" ) } } /** * Sets the value to the [builder], with field path represented by [fieldDescriptors]. * * All elements except the last one in [fieldDescriptors] must refer to a protobuf Message. The last * one in [fieldDescriptors] must refer to a field with [V]. The first element in [fieldDescriptors] * must refer to a field in [builder], Each of the rest elements must refer to a field in the * message referred by the previous element. * * The typical usage is to first call getFieldFromProto(see above), to get [fieldDescriptors] for * the target field in [builder], then call this function to set the value of the target field. * Example: If we have a protobuf * ``` * message MsgA { * message MsgB { * optional int32 c = 1; * } * optional MsgB b = 1; * } * ``` * To get the field descriptors of MsgA.b.c: * ``` * val fieldDescriptors = getFieldFromProto(MsgA().GetDescriptor(), "b.c")); * ``` * And if there is a MsgA object obj_a, to set the value of obj_a.b.c to 10: * ``` * setValueToProto(obj_a, fieldDescriptors, 10); * ``` */ inline fun <reified V> setValueToProtoBuilder( builder: Builder, fieldDescriptors: List<FieldDescriptor>, value: V ) { val parentBuilder = getParentMessageFromProto(builder, fieldDescriptors) if (parentBuilder !is Builder) { /** this should never happen */ error("expecting a Builder but get a Message") } setImmediateValueToProtoBuilder(parentBuilder, fieldDescriptors.last(), value) } /** Gets the size of the repeated field represented by [fieldDescriptors] in [message]. */ fun getSizeOfRepeatedProto( message: MessageOrBuilder, fieldDescriptors: List<FieldDescriptor> ): Int { return getParentMessageFromProto(message, fieldDescriptors) .getRepeatedFieldCount(fieldDescriptors.last()) } /** * Gets the value from the [message], with repeated field name represented by [fieldDescriptor], and * the index represented by [index]. * * [index] must be in the boundary of the repeated field. * * The field must be an immediate field of [message]. The corresponding type of the field must be * [V]. */ inline fun <reified V> getImmediateValueFromRepeatedProto( message: MessageOrBuilder, fieldDescriptor: FieldDescriptor, index: Int ): V { val result = message.getRepeatedField(fieldDescriptor, index) return if (result is V) { result } else if (result is Int && V::class == UInt::class) { result.toUInt() as V } else if (result is Long && V::class == ULong::class) { result.toULong() as V } else { error("The type of the field is not compatible to the target: $result") } } /** * Gets the value from the [message], with repeated field path represented by [fieldDescriptors], * and the index represented by [index]. * * [index] must be in the boundary of the repeated field. * * All entries except the last one in [fieldDescriptors] must refer to a singular protobuf Message * field. The last entry in [fieldDescriptors] must refer to a repeated field with [V]. The first * element in [fieldDescriptors] must refer to a field in [message], Each of the rest elements must * refer to a field in the message referred by the previous element. */ inline fun <reified V> getValueFromRepeatedProto( message: MessageOrBuilder, fieldDescriptors: List<FieldDescriptor>, index: Int ): V { return getImmediateValueFromRepeatedProto( getParentMessageFromProto(message, fieldDescriptors), fieldDescriptors.last(), index ) } /** * Gets all values from the [message], with repeated field name represented by [fieldDescriptor] * * The field must be an immediate field of [message]. The corresponding type of the field must be * [V]. */ inline fun <reified V> getAllImmediateValuesFromRepeatedProto( message: MessageOrBuilder, fieldDescriptor: FieldDescriptor, ): List<V> { return (0 until message.getRepeatedFieldCount(fieldDescriptor)) .map { val value = message.getRepeatedField(fieldDescriptor, it) if (value is V) { value } else if (value is Int && V::class == UInt::class) { value.toUInt() as V } else if (value is Long && V::class == ULong::class) { value.toULong() as V } else { error("The type of the field is not compatible to the target: $value") } } .toList() } /** * Gets all values from the [message], with repeated field path represented by [fieldDescriptors] * * All entries except the last one in [fieldDescriptors] must refer to a singular protobuf Message * field. The last entry in [fieldDescriptors] must refer to a repeated field with [V]. The first * element in [fieldDescriptors] must refer to a field in [message], Each of the rest elements must * refer to a field in the message referred by the previous element. */ inline fun <reified V> getAllValuesFromRepeatedProto( message: MessageOrBuilder, fieldDescriptors: List<FieldDescriptor>, ): List<V> { return getAllImmediateValuesFromRepeatedProto( getParentMessageFromProto(message, fieldDescriptors), fieldDescriptors.last() ) }
apache-2.0
786c4e2e5c4c57700c45f6100da30f6d
34.579832
103
0.713352
4.084244
false
false
false
false
inorichi/tachiyomi-extensions
src/en/nhentaicom/src/eu/kanade/tachiyomi/extension/en/nhentai/com/NHentaiCom.kt
1
7460
package eu.kanade.tachiyomi.extension.en.nhentai.com import android.app.Application import android.content.SharedPreferences import com.github.salomonbrys.kotson.fromJson import com.github.salomonbrys.kotson.get import com.github.salomonbrys.kotson.int import com.github.salomonbrys.kotson.nullString import com.github.salomonbrys.kotson.string import com.google.gson.Gson import com.google.gson.JsonObject import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get @Nsfw class NHentaiCom : HttpSource() { override val name = "nHentai.com (unoriginal)" override val baseUrl = "https://nhentai.com" override val lang = "en" override val supportsLatest = true override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64)") private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } override val client: OkHttpClient = network.cloudflareClient private val gson = Gson() private fun parseMangaFromJson(response: Response): MangasPage { val jsonObject = gson.fromJson<JsonObject>(response.body!!.string()) val mangas = jsonObject["data"].asJsonArray.map { json -> SManga.create().apply { title = json["title"].string thumbnail_url = json["image_url"].string url = json["slug"].string } } return MangasPage(mangas, jsonObject["current_page"].int < jsonObject["last_page"].int) } private fun getMangaUrl(url: String): String { return url.toHttpUrlOrNull()!!.newBuilder() .setQueryParameter("nsfw", "false").toString() } // Popular override fun popularMangaRequest(page: Int): Request { return GET(getMangaUrl("$baseUrl/api/comics?page=$page&q=&sort=popularity&order=desc&duration=week"), headers) } override fun popularMangaParse(response: Response): MangasPage = parseMangaFromJson(response) // Latest override fun latestUpdatesRequest(page: Int): Request { return GET(getMangaUrl("$baseUrl/api/comics?page=$page&q=&sort=uploaded_at&order=desc&duration=day"), headers) } override fun latestUpdatesParse(response: Response): MangasPage = parseMangaFromJson(response) // Search override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = "$baseUrl/api/comics".toHttpUrlOrNull()!!.newBuilder() .addQueryParameter("per_page", "18") .addQueryParameter("page", page.toString()) .addQueryParameter("order", "desc") .addQueryParameter("q", query) .addQueryParameter("nsfw", "false") filters.forEach { filter -> when (filter) { is SortFilter -> url.addQueryParameter("sort", filter.toUriPart()) is DurationFilter -> url.addQueryParameter("duration", filter.toUriPart()) } } return GET(url.toString(), headers) } override fun searchMangaParse(response: Response): MangasPage = parseMangaFromJson(response) // Details // Workaround to allow "Open in browser" to use the real URL override fun fetchMangaDetails(manga: SManga): Observable<SManga> = client.newCall(apiMangaDetailsRequest(manga)).asObservableSuccess() .map { mangaDetailsParse(it).apply { initialized = true } } // Return the real URL for "Open in browser" override fun mangaDetailsRequest(manga: SManga) = GET(getMangaUrl("$baseUrl/en/webtoon/${manga.url}"), headers) private fun apiMangaDetailsRequest(manga: SManga): Request { return GET(getMangaUrl("$baseUrl/api/comics/${manga.url}"), headers) } override fun mangaDetailsParse(response: Response): SManga { val jsonObject = gson.fromJson<JsonObject>(response.body!!.string()) return SManga.create().apply { description = jsonObject["description"].nullString status = jsonObject["status"].nullString.toStatus() thumbnail_url = jsonObject["image_url"].nullString genre = try { jsonObject["tags"].asJsonArray.joinToString { it["name"].string } } catch (_: Exception) { null } artist = try { jsonObject["artists"].asJsonArray.joinToString { it["name"].string } } catch (_: Exception) { null } author = try { jsonObject["authors"].asJsonArray.joinToString { it["name"].string } } catch (_: Exception) { null } } } private fun String?.toStatus() = when { this == null -> SManga.UNKNOWN this.contains("ongoing", ignoreCase = true) -> SManga.ONGOING this.contains("complete", ignoreCase = true) -> SManga.COMPLETED else -> SManga.UNKNOWN } // Chapters override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> { return Observable.just( listOf( SChapter.create().apply { name = "chapter" url = manga.url } ) ) } override fun chapterListRequest(manga: SManga): Request = throw Exception("not used") override fun chapterListParse(response: Response): List<SChapter> = throw UnsupportedOperationException("Not used") // Pages override fun pageListRequest(chapter: SChapter): Request { return GET(getMangaUrl("$baseUrl/api/comics/${chapter.url}/images"), headers) } override fun pageListParse(response: Response): List<Page> { return gson.fromJson<JsonObject>(response.body!!.string())["images"].asJsonArray.mapIndexed { i, json -> Page(i, "", json["source_url"].string) } } override fun imageUrlParse(response: Response): String = throw UnsupportedOperationException("Not used") // Filters override fun getFilterList() = FilterList( DurationFilter(getDurationList()), SortFilter(getSortList()) ) private class DurationFilter(pairs: Array<Pair<String, String>>) : UriPartFilter("Duration", pairs) private class SortFilter(pairs: Array<Pair<String, String>>) : UriPartFilter("Sorted by", pairs) open class UriPartFilter(displayName: String, private val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } private fun getDurationList() = arrayOf( Pair("All time", "all"), Pair("Year", "year"), Pair("Month", "month"), Pair("Week", "week"), Pair("Day", "day") ) private fun getSortList() = arrayOf( Pair("Popularity", "popularity"), Pair("Date", "uploaded_at") ) }
apache-2.0
09e7f751729555bfc829809eb6924948
36.114428
127
0.669169
4.613482
false
false
false
false
tasomaniac/OpenLinkWith
base-prefs/src/main/kotlin/com/tasomaniac/openwith/browser/BrowserPreferences.kt
1
1924
package com.tasomaniac.openwith.browser import android.content.ComponentName import android.content.SharedPreferences import androidx.core.content.edit import javax.inject.Inject class BrowserPreferences @Inject constructor(private val sharedPreferences: SharedPreferences) { var mode: Mode set(value) { sharedPreferences.edit { putString(KEY, value.value) if (value is Mode.Browser) { putString(KEY_BROWSER_NAME, value.displayLabel) putString(KEY_BROWSER_COMPONENT, value.componentName.flattenToString()) } else { remove(KEY_BROWSER_NAME) remove(KEY_BROWSER_COMPONENT) } } } get() { return when (val value = sharedPreferences.getString(KEY, null)) { null, "always_ask" -> Mode.AlwaysAsk "none" -> Mode.None "browser" -> Mode.Browser(browserName!!, componentName) else -> error("Unknown when checking browser mode: $value") } } private val browserName: String? get() = sharedPreferences.getString(KEY_BROWSER_NAME, null) private val componentName: ComponentName get() { val browserComponent = sharedPreferences.getString(KEY_BROWSER_COMPONENT, null)!! return ComponentName.unflattenFromString(browserComponent)!! } sealed class Mode(val value: String) { object None : Mode("none") object AlwaysAsk : Mode("always_ask") data class Browser(val displayLabel: String, val componentName: ComponentName) : Mode("browser") } companion object { private const val KEY = "pref_browser" private const val KEY_BROWSER_NAME = "pref_browser_name" private const val KEY_BROWSER_COMPONENT = "pref_browser_component" } }
apache-2.0
d5c66b69697ea7a12e073d1dcff15114
35.301887
104
0.613306
4.920716
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/place_name/AddPlaceName.kt
1
6272
package de.westnordost.streetcomplete.quests.place_name import de.westnordost.osmapi.map.MapDataWithGeometry import de.westnordost.osmapi.map.data.Element import de.westnordost.osmfeatures.FeatureDictionary import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementQuestType import de.westnordost.streetcomplete.ktx.arrayOfNotNull import java.util.concurrent.FutureTask class AddPlaceName( private val featureDictionaryFuture: FutureTask<FeatureDictionary> ) : OsmElementQuestType<PlaceNameAnswer> { private val filter by lazy { (""" nodes, ways, relations with ( shop and shop !~ no|vacant or craft or office or tourism = information and information = office or """.trimIndent() + // The common list is shared by the name quest, the opening hours quest and the wheelchair quest. // So when adding other tags to the common list keep in mind that they need to be appropriate for all those quests. // Independent tags can by added in the "name only" tab. mapOf( "amenity" to arrayOf( // common "restaurant", "cafe", "ice_cream", "fast_food", "bar", "pub", "biergarten", "food_court", "nightclub", // eat & drink "cinema", "planetarium", "casino", // amenities "townhall", "courthouse", "embassy", "community_centre", "youth_centre", "library", // civic "bank", "bureau_de_change", "money_transfer", "post_office", "marketplace", "internet_cafe", // commercial "car_wash", "car_rental", "fuel", // car stuff "dentist", "doctors", "clinic", "pharmacy", "veterinary", // health "animal_boarding", "animal_shelter", "animal_breeding", // animals // name & opening hours "boat_rental", // name & wheelchair "theatre", // culture "conference_centre", "arts_centre", // events "police", "ranger_station", // civic "ferry_terminal", // transport "place_of_worship", // religious "hospital", // health care // name only "studio", // culture "events_venue", "exhibition_centre", "music_venue", // events "prison", "fire_station", // civic "social_facility", "nursing_home", "childcare", "retirement_home", "social_centre", // social "monastery", // religious "kindergarten", "school", "college", "university", "research_institute", // education "driving_school", "dive_centre", "language_school", "music_school", // learning "brothel", "gambling", "love_hotel", "stripclub" // bad stuff ), "tourism" to arrayOf( // common "zoo", "aquarium", "theme_park", "gallery", "museum", // name & wheelchair "attraction", "hotel", "guest_house", "motel", "hostel", "alpine_hut", "apartment", "resort", "camp_site", "caravan_site", "chalet" // accommodations // and tourism = information, see above ), "leisure" to arrayOf( // common "fitness_centre", "golf_course", "water_park", "miniature_golf", "bowling_alley", "amusement_arcade", "adult_gaming_centre", "tanning_salon", // name & wheelchair "sports_centre", "stadium", "marina", // name & opening hours "horse_riding", // name only "dance", "nature_reserve" ), "landuse" to arrayOf( "cemetery", "allotments" ), "military" to arrayOf( "airfield", "barracks", "training_area" ) ).map { it.key + " ~ " + it.value.joinToString("|") }.joinToString("\n or ") + "\n" + """ ) and !name and !brand and noname != yes and name:signed != no """.trimIndent()).toElementFilterExpression() } override val commitMessage = "Determine place names" override val wikiLink = "Key:name" override val icon = R.drawable.ic_quest_label override val isReplaceShopEnabled = true override fun getTitle(tags: Map<String, String>) = R.string.quest_placeName_title_name override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>) = arrayOfNotNull(featureName.value) override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> = mapData.filter { isApplicableTo(it) } override fun isApplicableTo(element: Element) = filter.matches(element) && hasAnyName(element.tags) override fun createForm() = AddPlaceNameForm() override fun applyAnswerTo(answer: PlaceNameAnswer, changes: StringMapChangesBuilder) { when(answer) { is NoPlaceNameSign -> changes.add("name:signed", "no") is PlaceName -> changes.add("name", answer.name) is BrandFeature -> { for ((key, value) in answer.tags.entries) { changes.addOrModify(key, value) } } } } private fun hasAnyName(tags: Map<String, String>?): Boolean = tags?.let { featureDictionaryFuture.get().byTags(it).find().isNotEmpty() } ?: false }
gpl-3.0
c29761a4cea49168790529a091b81a83
47.620155
151
0.52854
4.694611
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/fragment/JobsFragment.kt
2
4412
package com.commit451.gitlab.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import com.commit451.gitlab.App import com.commit451.gitlab.R import com.commit451.gitlab.activity.ProjectActivity import com.commit451.gitlab.adapter.BaseAdapter import com.commit451.gitlab.event.BuildChangedEvent import com.commit451.gitlab.event.ProjectReloadEvent import com.commit451.gitlab.model.api.Build import com.commit451.gitlab.model.api.Project import com.commit451.gitlab.navigation.Navigator import com.commit451.gitlab.util.LoadHelper import com.commit451.gitlab.viewHolder.BuildViewHolder import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.fragment_jobs.* import org.greenrobot.eventbus.Subscribe /** * Shows the jobs of a project */ class JobsFragment : BaseFragment() { companion object { fun newInstance(): JobsFragment { return JobsFragment() } } private lateinit var adapter: BaseAdapter<Build, BuildViewHolder> private lateinit var loadHelper: LoadHelper<Build> private lateinit var scopes: Array<String> private var scope: String? = null private var project: Project? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) scopes = resources.getStringArray(R.array.build_scope_values) scope = scopes.first() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_jobs, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) App.bus().register(this) adapter = BaseAdapter( onCreateViewHolder = { parent, _ -> val viewHolder = BuildViewHolder.inflate(parent) viewHolder.itemView.setOnClickListener { val build = adapter.items[viewHolder.adapterPosition] if (project != null) { Navigator.navigateToBuild(baseActivty, project!!, build) } else { Snackbar.make(root, getString(R.string.wait_for_project_to_load), Snackbar.LENGTH_SHORT) .show() } } viewHolder }, onBindViewHolder = { viewHolder, _, item -> viewHolder.bind(item) } ) loadHelper = LoadHelper( lifecycleOwner = this, recyclerView = listBuilds, baseAdapter = adapter, swipeRefreshLayout = swipeRefreshLayout, errorOrEmptyTextView = textMessage, loadInitial = { gitLab.getBuilds(project!!.id, scope) }, loadMore = { gitLab.loadAnyList(it) } ) spinnerIssue.adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, resources.getStringArray(R.array.build_scope_names)) spinnerIssue.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { scope = scopes[position] loadData() } override fun onNothingSelected(parent: AdapterView<*>?) {} } swipeRefreshLayout.setOnRefreshListener { loadData() } if (activity is ProjectActivity) { project = (activity as ProjectActivity).project loadData() } else { throw IllegalStateException("Incorrect parent activity") } } override fun onDestroyView() { App.bus().unregister(this) super.onDestroyView() } override fun loadData() { loadHelper.load() } @Subscribe fun onEvent(event: ProjectReloadEvent) { project = event.project loadData() } @Subscribe fun onEvent(event: BuildChangedEvent) { adapter.update(event.build) } }
apache-2.0
9e86431bf567cdc532ccf40c134c60bd
33.46875
116
0.62942
5.082949
false
false
false
false
sn3d/nomic
nomic-db/src/main/kotlin/nomic/db/NotCompiledBox.kt
1
1001
package nomic.db import nomic.core.exception.NotCompiledBoxException import nomic.compiler.Compiler import nomic.core.* /** * @author [email protected] */ class NotCompiledBox( override val name: String, override val group: String, override val version: String, override val script: Script, override val dependencies: List<BoxRef>) : InstalledBox { override val facts: List<Fact> get() = throw NotCompiledBoxException() fun compileWith(compiler: Compiler): InstalledBox { val f = compiler.compile(script) return CompiledBox(f) } private inner class CompiledBox(override val facts: List<Fact>) : InstalledBox { override val name: String get() = [email protected] override val group: String get() = [email protected] override val version: String get() = [email protected] override val script: Script get() = [email protected] override val dependencies: List<BoxRef> get() = [email protected] } }
apache-2.0
377e70c7c85666f9dba81bf0b9a880f1
22.857143
81
0.748252
3.626812
false
false
false
false
sjnyag/stamp
app/src/main/java/com/sjn/stamp/model/migration/Migration.kt
1
9734
package com.sjn.stamp.model.migration import com.sjn.stamp.utils.LogHelper import io.realm.* class Migration : RealmMigration { companion object { private val TAG = LogHelper.makeLogTag(Migration::class.java) const val VERSION = 6 } override fun migrate(realm: DynamicRealm, version: Long, newVersion: Long) { var oldVersion = version val schema = realm.schema if (oldVersion == 0L) { migrateTo1(realm, schema) oldVersion++ } if (oldVersion == 1L) { migrateTo2(schema) oldVersion++ } if (oldVersion == 2L) { migrateTo3(schema) oldVersion++ } if (oldVersion == 3L) { migrateTo4(schema) oldVersion++ } if (oldVersion == 4L) { migrateTo5(realm, schema) oldVersion++ } if (oldVersion == 5L) { migrateTo6(realm, schema) oldVersion++ } if (oldVersion != newVersion) { LogHelper.w(TAG, "Realm migration might be failed.") } } private fun migrateTo1(realm: DynamicRealm, schema: RealmSchema) { val artistSchema = schema.create("Artist") .addField("mId", Long::class.javaPrimitiveType, FieldAttribute.PRIMARY_KEY) .addField("mName", String::class.java, FieldAttribute.INDEXED) .addField("mAlbumArtUri", String::class.java) val songSchema = schema.get("Song") songSchema.addRealmObjectField("mArtist_new", artistSchema) .transform(object : RealmObjectSchema.Function { override fun apply(obj: DynamicRealmObject) { obj.set("mArtist_new", findOrCreateArtist(obj.getString("mArtist"), obj.getString("mAlbumArtUri"))) } internal fun findOrCreateArtist(name: String, artUrl: String): DynamicRealmObject { var artist: DynamicRealmObject? = realm.where("Artist").equalTo("mName", name).findFirst() if (artist == null) { artist = realm.createObject("Artist", getAutoIncrementId(realm, "Artist")) artist!!.setString("mName", name) artist.setString("mAlbumArtUri", artUrl) } return artist } internal fun getAutoIncrementId(realm: DynamicRealm, clazz: String): Int { val maxId = realm.where(clazz).max("mId") if (maxId != null) { return maxId.toInt() + 1 } return 1 } }) .removeField("mArtist") .renameField("mArtist_new", "mArtist") } private fun migrateTo2(schema: RealmSchema) { schema.get("Artist") .renameField("mId", "id") .renameField("mName", "name") .renameField("mAlbumArtUri", "albumArtUri") schema.get("CategoryStamp") .renameField("mId", "id") .renameField("mName", "name") .renameField("mValue", "value") .renameField("mType", "type") schema.get("Device") .renameField("mId", "id") .renameField("mModel", "model") .renameField("mOs", "os") schema.get("Playlist") .renameField("mId", "id") .renameField("mName", "name") .renameField("mActive", "active") .renameField("mCreatedAt", "createdAt") .renameField("mUpdatedAt", "updatedAt") .renameField("mSongs", "songs") schema.get("PlaylistSong") .renameField("mId", "id") .renameField("mArtist", "artist") .renameField("mTitle", "title") .renameField("mSongId", "songId") .renameField("mActive", "active") .renameField("mCreatedAt", "createdAt") .renameField("mUpdatedAt", "updatedAt") .renameField("mPlaylist", "playlist") schema.get("Song") .renameField("mId", "id") .renameField("mMediaId", "mediaId") .renameField("mTrackSource", "trackSource") .renameField("mAlbum", "album") .renameField("mDuration", "duration") .renameField("mGenre", "genre") .renameField("mAlbumArtUri", "albumArtUri") .renameField("mTitle", "title") .renameField("mTrackNumber", "trackNumber") .renameField("mNumTracks", "numTracks") .renameField("mDateAdded", "dateAdded") .renameField("mSongStampList", "songStampList") .renameField("mArtist", "artist") schema.get("SongHistory") .renameField("mId", "id") .renameField("mSong", "song") .renameField("mRecordedAt", "recordedAt") .renameField("mRecordType", "recordType") .renameField("mDevice", "device") .renameField("mCount", "count") .renameField("mLatitude", "latitude") .renameField("mLongitude", "longitude") .renameField("mAccuracy", "accuracy") .renameField("mAltitude", "altitude") schema.get("SongStamp") .renameField("mId", "id") .renameField("mName", "name") .renameField("mIsSystem", "isSystem") .renameField("mSongList", "songList") schema.get("TotalSongHistory") .renameField("mId", "id") .renameField("mSong", "song") .renameField("mPlayCount", "playCount") .renameField("mSkipCount", "skipCount") .renameField("mCompleteCount", "completeCount") schema.get("UserSetting") .renameField("mIsAutoLogin", "isAutoLogin") .renameField("mRepeatState", "repeatState") .renameField("mShuffleState", "shuffleState") .renameField("mQueueIdentifyMediaId", "queueIdentifyMediaId") .renameField("mLastMusicId", "lastMusicId") } private fun migrateTo3(schema: RealmSchema) { schema.get("UserSetting") .addField("stopOnAudioLostFocus", Boolean::class.java, FieldAttribute.REQUIRED) .transform({ obj -> obj.setBoolean("stopOnAudioLostFocus", false) }) .addField("showAlbumArtOnLockScreen", Boolean::class.java, FieldAttribute.REQUIRED) .transform({ obj -> obj.setBoolean("showAlbumArtOnLockScreen", false) }) .addField("autoPlayOnHeadsetConnected", Boolean::class.java, FieldAttribute.REQUIRED) .transform({ obj -> obj.setBoolean("autoPlayOnHeadsetConnected", false) }) .addField("alertSpeaker", Boolean::class.java, FieldAttribute.REQUIRED) .transform({ obj -> obj.setBoolean("alertSpeaker", false) }) .addField("newSongDays", Int::class.java, FieldAttribute.REQUIRED) .transform({ obj -> obj.setInt("newSongDays", 30) }) .addField("mostPlayedSongSize", Int::class.java, FieldAttribute.REQUIRED) .transform({ obj -> obj.setInt("mostPlayedSongSize", 30) }) } private fun migrateTo4(schema: RealmSchema) { schema.get("CategoryStamp") .addField("isSystem", Boolean::class.java, FieldAttribute.REQUIRED) .transform({ obj -> obj.setBoolean("isSystem", false) }) } private fun migrateTo5(realm: DynamicRealm, schema: RealmSchema) { schema.get("Song") .addRealmObjectField("totalSongHistory", schema.get("TotalSongHistory")) .transform(object : RealmObjectSchema.Function { override fun apply(obj: DynamicRealmObject) { obj.set("totalSongHistory", findOrCreateArtist(obj)) } internal fun findOrCreateArtist(obj: DynamicRealmObject): DynamicRealmObject { var totalSongHistory: DynamicRealmObject? = realm.where("TotalSongHistory").equalTo("song.id", obj.getLong("id")).findFirst() if (totalSongHistory == null) { totalSongHistory = realm.createObject("TotalSongHistory", getAutoIncrementId(realm, "TotalSongHistory")) totalSongHistory!!.set("song", obj) totalSongHistory.setInt("playCount", 0) totalSongHistory.setInt("playCount", 0) totalSongHistory.setInt("playCount", 0) } return totalSongHistory } internal fun getAutoIncrementId(realm: DynamicRealm, clazz: String): Int { val maxId = realm.where(clazz).max("id") if (maxId != null) { return maxId.toInt() + 1 } return 1 } }) schema.get("TotalSongHistory") .removeField("song") } private fun migrateTo6(realm: DynamicRealm, schema: RealmSchema) { schema.get("UserSetting") .removeField("repeatState") .removeField("shuffleState") } }
apache-2.0
fbc364d563ef6cc614a5b22fc1d7a9a8
43.861751
149
0.526402
4.876754
false
false
false
false
maxoumime/emoji-data-java
src/main/java/com/maximebertheau/emoji/EmojiLoader.kt
1
3524
package com.maximebertheau.emoji import org.json.JSONArray import org.json.JSONObject import java.io.IOException import java.io.UnsupportedEncodingException internal object EmojiLoader { private const val PATH = "/emojis.json" /** * Loads a JSONArray of emojis from an InputStream, parses it and returns the * associated list of [Emoji]s * * @param stream the stream of the JSONArray * @return the list of [Emoji]s * @throws IOException if an error occurs while reading the stream or parsing * the JSONArray */ @Throws(IOException::class) internal fun loadEmojis(): Sequence<Emoji> { val stream = EmojiLoader::class.java.getResourceAsStream(PATH) val json = try { stream.use { it.bufferedReader(Charsets.UTF_8).readText() } } catch (e: IOException) { throw RuntimeException(e) } return JSONArray(json).objects().asSequence() .filter { it.has("unified") } .flatMap { emojiObject -> val variations = sequence<String> { yield(emojiObject.getString("unified")) yieldAll(emojiObject.optJSONArray("variations")?.strings().orEmpty()) }.reversed() variations.map { variation -> emojiObject to variation } } .flatMap { (emojiObject, variation) -> emojiObject.put("unified", variation) emojiObject.toEmojis() } } @JvmStatic @Throws(UnsupportedEncodingException::class) internal fun JSONObject.toEmojis(): Sequence<Emoji> { val unified = optString("unified") ?: return emptySequence() val aliases = optJSONArray("short_names")?.strings() ?: return emptySequence() val category = optString("category")?.let(Category.Companion::parse) ?: return emptySequence() val name = optString("name") val isObsolete = has("obsoleted_by") val sortOrder = optInt("sort_order") val skinVariations = optJSONArray("skin_variations")?.arrays() ?.map { val types = it.getString(0).split('-').map(SkinVariationType.Companion::fromUnified) val variation = it.getString(1) SkinVariation(types, variation) } .orEmpty() val emojiBase = Emoji(name, unified, aliases, isObsolete, category, sortOrder, skinVariations, isPristine = true) return sequence { yield(emojiBase) skinVariations.forEach { variation -> val newAliases = emojiBase.aliases.map { alias -> if (variation.types.isEmpty()) { alias } else { alias + ":" + variation.types.joinToString(separator = "") { ":${it.alias}:" }.trimEnd(':') } } yield(emojiBase.copy(aliases = newAliases, unified = variation.unified, isPristine = false, skinVariations = emptyList<SkinVariation>())) } } } private fun JSONArray.objects() = (0 until length()).map(::getJSONObject) private fun JSONArray.arrays() = (0 until length()).map(::getJSONArray) private fun JSONArray.strings() = (0 until length()).map(::getString) private fun <T> Sequence<T>.reversed() = toList().asReversed().asSequence() }
mit
edebc16007e0995bdc899b477b565c84
38.166667
153
0.574064
5.005682
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/pages/PageItem.kt
1
7939
package org.wordpress.android.ui.pages import androidx.annotation.ColorRes import androidx.annotation.IdRes import androidx.annotation.StringRes import org.wordpress.android.R import org.wordpress.android.ui.pages.PageItem.Type.DIVIDER import org.wordpress.android.ui.pages.PageItem.Type.EMPTY import org.wordpress.android.ui.pages.PageItem.Type.PAGE import org.wordpress.android.ui.utils.UiString import org.wordpress.android.viewmodel.uistate.ProgressBarUiState import java.util.Date sealed class PageItem(open val type: Type) { @Suppress("LongParameterList") abstract class Page( open val remoteId: Long, open val localId: Int, open val title: String, open val subtitle: Int? = null, open val icon: Int? = null, open val date: Date, open val labels: List<UiString>, @ColorRes open val labelsColor: Int?, open var indent: Int, open var imageUrl: String?, open val actions: Set<Action>, open var actionsEnabled: Boolean, open val tapActionEnabled: Boolean, open val progressBarUiState: ProgressBarUiState, open val showOverlay: Boolean, open val author: String?, open var showQuickStartFocusPoint: Boolean ) : PageItem(PAGE) @Suppress("DataClassShouldBeImmutable") data class PublishedPage( override val remoteId: Long, override val localId: Int, override val title: String, override val subtitle: Int? = null, override val icon: Int? = null, override val date: Date, override val labels: List<UiString> = emptyList(), override val labelsColor: Int? = null, override var indent: Int = 0, override var imageUrl: String? = null, override val actions: Set<Action>, override var actionsEnabled: Boolean = true, override val progressBarUiState: ProgressBarUiState, override val showOverlay: Boolean, override val author: String? = null, override var showQuickStartFocusPoint: Boolean = false ) : Page( remoteId = remoteId, localId = localId, title = title, date = date, labels = labels, labelsColor = labelsColor, indent = indent, imageUrl = imageUrl, actions = actions, actionsEnabled = actionsEnabled, tapActionEnabled = true, progressBarUiState = progressBarUiState, showOverlay = showOverlay, author = author, showQuickStartFocusPoint = showQuickStartFocusPoint ) @Suppress("DataClassShouldBeImmutable") data class DraftPage( override val remoteId: Long, override val localId: Int, override val title: String, override val subtitle: Int? = null, override val date: Date, override val labels: List<UiString> = emptyList(), override val labelsColor: Int? = null, override var imageUrl: String? = null, override val actions: Set<Action>, override var actionsEnabled: Boolean = true, override val progressBarUiState: ProgressBarUiState, override val showOverlay: Boolean, override val author: String? = null, override var showQuickStartFocusPoint: Boolean = false ) : Page( remoteId = remoteId, localId = localId, title = title, date = date, labels = labels, labelsColor = labelsColor, indent = 0, imageUrl = imageUrl, actions = actions, actionsEnabled = actionsEnabled, tapActionEnabled = true, progressBarUiState = progressBarUiState, showOverlay = showOverlay, author = author, showQuickStartFocusPoint = showQuickStartFocusPoint ) @Suppress("DataClassShouldBeImmutable") data class ScheduledPage( override val remoteId: Long, override val localId: Int, override val title: String, override val subtitle: Int? = null, override val date: Date, override val labels: List<UiString> = emptyList(), override val labelsColor: Int? = null, override var imageUrl: String? = null, override val actions: Set<Action>, override var actionsEnabled: Boolean = true, override val progressBarUiState: ProgressBarUiState, override val showOverlay: Boolean, override val author: String? = null, override var showQuickStartFocusPoint: Boolean = false ) : Page( remoteId = remoteId, localId = localId, title = title, date = date, labels = labels, labelsColor = labelsColor, indent = 0, imageUrl = imageUrl, actions = actions, actionsEnabled = actionsEnabled, tapActionEnabled = true, progressBarUiState = progressBarUiState, showOverlay = showOverlay, author = author, showQuickStartFocusPoint = showQuickStartFocusPoint ) @Suppress("DataClassShouldBeImmutable") data class TrashedPage( override val remoteId: Long, override val localId: Int, override val title: String, override val subtitle: Int? = null, override val date: Date, override val labels: List<UiString> = emptyList(), override val labelsColor: Int? = null, override var imageUrl: String? = null, override val actions: Set<Action>, override var actionsEnabled: Boolean = true, override val progressBarUiState: ProgressBarUiState, override val showOverlay: Boolean, override val author: String? = null, override var showQuickStartFocusPoint: Boolean = false ) : Page( remoteId = remoteId, localId = localId, title = title, date = date, labels = labels, labelsColor = labelsColor, indent = 0, imageUrl = imageUrl, actions = actions, actionsEnabled = actionsEnabled, tapActionEnabled = false, progressBarUiState = progressBarUiState, showOverlay = showOverlay, author = author, showQuickStartFocusPoint = showQuickStartFocusPoint ) @Suppress("DataClassShouldBeImmutable") data class ParentPage( val id: Long, val title: String, var isSelected: Boolean, override val type: Type ) : PageItem(type) data class Divider(val title: String = "") : PageItem(DIVIDER) data class Empty( @StringRes val textResource: Int = R.string.empty_list_default, val isSearching: Boolean = false, val isButtonVisible: Boolean = true, val isImageVisible: Boolean = true ) : PageItem(EMPTY) enum class Type(val viewType: Int) { PAGE(1), DIVIDER(2), EMPTY(3), PARENT(4), TOP_LEVEL_PARENT(5) } enum class Action(@IdRes val itemId: Int) { VIEW_PAGE(R.id.view_page), CANCEL_AUTO_UPLOAD(R.id.cancel_auto_upload), SET_PARENT(R.id.set_parent), SET_AS_HOMEPAGE(R.id.set_as_homepage), SET_AS_POSTS_PAGE(R.id.set_as_posts_page), COPY(R.id.copy), COPY_LINK(R.id.copy_page_link), PUBLISH_NOW(R.id.publish_now), MOVE_TO_DRAFT(R.id.move_to_draft), DELETE_PERMANENTLY(R.id.delete_permanently), MOVE_TO_TRASH(R.id.move_to_trash); companion object { fun fromItemId(itemId: Int): Action { return values().firstOrNull { it.itemId == itemId } ?: throw IllegalArgumentException("Unexpected item ID in context menu") } } } }
gpl-2.0
1e2fa76a5259bf8397413e868dfecb20
35.251142
95
0.612672
4.846764
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/deltarnn/DeltaRNNRelevanceSupport.kt
1
1434
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.recurrent.deltarnn import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.simplemath.ndarray.Shape import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory /** * A support structure for the DeltaRNN, used to save temporary results during a forward and using them to calculate the * relevance later. * * @property outputSize the size of the output array of the layer */ internal data class DeltaRNNRelevanceSupport(val outputSize: Int) { /** * The contribution from the input to the d1 array, including half biases of the candidate. */ val d1Input = AugmentedArray(values = DenseNDArrayFactory.emptyArray(Shape(this.outputSize))) /** * The contribution from the previous state to the d1 array, including half biases of the candidate. */ val d1Rec = AugmentedArray(values = DenseNDArrayFactory.emptyArray(Shape(this.outputSize))) /** * The d2 array. */ val d2 = AugmentedArray(values = DenseNDArrayFactory.emptyArray(Shape(this.outputSize))) }
mpl-2.0
429b39bfe210f7da5494b36e252fd112
38.833333
120
0.723849
4.453416
false
false
false
false
TomsUsername/Phoenix
src/main/kotlin/phoenix/bot/pogo/nRnMK9r/util/pokemon/CatchablePokemon.kt
1
7032
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package phoenix.bot.pogo.nRnMK9r.util.pokemon import POGOProtos.Data.Capture.CaptureProbabilityOuterClass.CaptureProbability import POGOProtos.Inventory.Item.ItemIdOuterClass.ItemId import POGOProtos.Networking.Responses.CatchPokemonResponseOuterClass.CatchPokemonResponse.CatchStatus import phoenix.bot.pogo.api.cache.Inventory import phoenix.bot.pogo.api.cache.MapPokemon import phoenix.bot.pogo.api.request.CatchPokemon import phoenix.bot.pogo.api.request.UseItemCapture import phoenix.bot.pogo.nRnMK9r.util.Log import java.util.concurrent.atomic.AtomicInteger /** * Extension function to make the code more readable in the CatchOneNearbyPokemon task */ fun MapPokemon.catch(normalizedHitPosition: Double = 1.0, normalizedReticleSize: Double = 1.95 + Math.random() * 0.05, spinModifier: Double = 0.85 + Math.random() * 0.15, ballType: ItemId = ItemId.ITEM_POKE_BALL): rx.Observable<CatchPokemon> { return poGoApi.queueRequest(CatchPokemon() .withEncounterId(encounterId) .withHitPokemon(true) .withNormalizedHitPosition(normalizedHitPosition) .withNormalizedReticleSize(normalizedReticleSize) .withPokeball(ballType) .withSpinModifier(spinModifier) .withSpawnPointId(spawnPointId)) } fun MapPokemon.catch(captureProbability: CaptureProbability, inventory: Inventory, desiredCatchProbability: Double, alwaysCurve: Boolean = false, allowBerries: Boolean = false, randomBallThrows: Boolean = false, waitBetweenThrows: Boolean = false, amount: Int): rx.Observable<CatchPokemon> { var catch: rx.Observable<CatchPokemon> var numThrows = 0 do { catch = catch(captureProbability, inventory, desiredCatchProbability, alwaysCurve, allowBerries, randomBallThrows) val first = catch.toBlocking().first() if (first != null) { val result = first.response if (result.status != CatchStatus.CATCH_ESCAPE && result.status != CatchStatus.CATCH_MISSED) { break } if (waitBetweenThrows) { val waitTime = (Math.random() * 2900 + 100) Log.blue("Pokemon got out of the ball. Waiting for ca. ${Math.round(waitTime / 1000)} second(s) until next throw") Thread.sleep(waitTime.toLong()) } numThrows++ } } while (amount < 0 || numThrows < amount) return catch } fun MapPokemon.catch(captureProbability: CaptureProbability, inventory: Inventory, desiredCatchProbability: Double, alwaysCurve: Boolean = false, allowBerries: Boolean = false, randomBallThrows: Boolean = false): rx.Observable<CatchPokemon> { val ballTypes = captureProbability.pokeballTypeList val probabilities = captureProbability.captureProbabilityList //Log.yellow(probabilities.toString()) var ball: ItemId? = null var needCurve = alwaysCurve var needRazzBerry = false var highestAvailable: ItemId? = null var catchProbability = 0f for ((index, ballType) in ballTypes.withIndex()) { val probability = probabilities.get(index) val ballAmount = inventory.items.getOrPut(ballType, { AtomicInteger(0) }).get() if (ballAmount == 0) { //Log.yellow("Don't have any ${ballType}") continue } else { //Log.yellow("Have ${ballAmount} of ${ballType}") highestAvailable = ballType catchProbability = probability } if (probability >= desiredCatchProbability) { catchProbability = probability ball = ballType break } else if (probability >= desiredCatchProbability - 0.1) { ball = ballType needCurve = true catchProbability = probability + 0.1f break } else if (probability >= desiredCatchProbability - 0.2) { ball = ballType needCurve = true needRazzBerry = true catchProbability = probability + 0.2f break } } if (highestAvailable == null) { /*Log.red("No pokeballs?!") Log.red("Has pokeballs: ${itemBag.hasPokeballs()}")*/ return rx.Observable.just(null) } if (ball == null) { ball = highestAvailable needCurve = true needRazzBerry = true catchProbability += 0.2f } var logMessage = "Using ${ball.name}" val razzBerryCount = inventory.items.getOrPut(ItemId.ITEM_RAZZ_BERRY, { AtomicInteger(0) }).get() if (allowBerries && razzBerryCount > 0 && needRazzBerry) { logMessage += "; Using Razz Berry" poGoApi.queueRequest(UseItemCapture().withEncounterId(encounterId).withItemId(ItemId.ITEM_RAZZ_BERRY).withSpawnPointId(spawnPointId)).toBlocking() } if (needCurve) { logMessage += "; Using curve" } logMessage += "; achieved catch probability: ${Math.round(catchProbability * 100.0)}%, desired: ${Math.round(desiredCatchProbability * 100.0)}%" Log.yellow(logMessage) //excellent throw value var recticleSize = 1.7 + Math.random() * 0.3 if (randomBallThrows) { //excellent throw if capture probability is still less then desired if (catchProbability <= desiredCatchProbability) { // the recticle size is already set for an excelent throw } //if catch probability is too high... else { // we substract the difference from the recticle size, the lower this size, the worse the ball recticleSize = 1 + Math.random() - (catchProbability - desiredCatchProbability) * 0.5 if (recticleSize > 2) { recticleSize = 2.0 } else if (recticleSize < 0) { recticleSize = 0.01 } if (recticleSize < 1) { Log.blue("Your trainer threw a normal ball, no xp/catching bonus, good for pretending to be not a bot however") } else if (recticleSize >= 1 && recticleSize < 1.3) { Log.blue("Your trainer got a 'Nice throw' - nice") } else if (recticleSize >= 1.3 && recticleSize < 1.7) { Log.blue("Your trainer got a 'Great throw!'") } else if (recticleSize > 1.7) { Log.blue("Your trainer got an 'Excellent throw!' - that's suspicious, might he be a bot?") } } } return catch( normalizedHitPosition = 1.0, normalizedReticleSize = recticleSize, spinModifier = if (needCurve) 0.85 + Math.random() * 0.15 else Math.random() * 0.10, ballType = ball ) }
gpl-3.0
1205f57cb5a916510f14be152aa56c57
42.141104
291
0.641923
4.243814
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/reader/repository/usecases/tags/FollowInterestTagsUseCase.kt
1
2297
package org.wordpress.android.ui.reader.repository.usecases.tags import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.wordpress.android.fluxc.store.AccountStore import org.wordpress.android.models.ReaderTag import org.wordpress.android.ui.reader.ReaderEvents.FollowedTagsChanged import org.wordpress.android.ui.reader.actions.ReaderTagActions import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication.Error.NetworkUnavailable import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication.Error.RemoteRequestFailure import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication.Success import org.wordpress.android.util.EventBusWrapper import org.wordpress.android.util.NetworkUtilsWrapper import javax.inject.Inject import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class FollowInterestTagsUseCase @Inject constructor( private val eventBusWrapper: EventBusWrapper, private val networkUtilsWrapper: NetworkUtilsWrapper, private val accountStore: AccountStore ) { private var continuation: Continuation<ReaderRepositoryCommunication>? = null @Suppress("UseCheckOrError") suspend fun followInterestTags(tags: List<ReaderTag>): ReaderRepositoryCommunication { if (continuation != null) { throw IllegalStateException("Follow interest tags already in progress.") } val isLoggedIn = accountStore.hasAccessToken() if (isLoggedIn && !networkUtilsWrapper.isNetworkAvailable()) { return NetworkUnavailable } return suspendCoroutine { cont -> continuation = cont eventBusWrapper.register(this) ReaderTagActions.addTags(tags, isLoggedIn) } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.BACKGROUND) fun onFollowedTagsChanged(event: FollowedTagsChanged) { val result = if (event.didSucceed()) { Success } else { RemoteRequestFailure } continuation?.resume(result) eventBusWrapper.unregister(this) continuation = null } }
gpl-2.0
be52a7190e8606d552056f1439ca31ee
38.603448
106
0.762299
5.173423
false
false
false
false
JoeSteven/HuaBan
app/src/main/java/com/joe/zatuji/repo/RecommendRepository.kt
1
2112
package com.joe.zatuji.repo import com.google.gson.reflect.TypeToken import com.joe.zatuji.exception.ApiResponseException import com.joe.zatuji.helper.GsonHelper import com.joe.zatuji.repo.bean.* import com.joe.zatuji.repo.bean.request.RecommendListParams import com.joe.zatuji.repo.bean.request.RecommendParams import com.joe.zatuji.repo.bean.request.TableQueryParams import com.joe.zatuji.storege.UserKeeper import io.reactivex.Single import java.lang.reflect.Type /** * Description: * author:Joey * date:2018/11/26 */ class RecommendRepository: TableRepository() { companion object { private const val RECOMMEND = "Recommend" } fun createRecommend(picture:IDetailPicture, desc:String): Single<BaseBmobBean> { val user = UserKeeper.user!! val map = HashMap<String,String>() map["img_url"] = picture.getPicUrl() val type: Type = object : TypeToken<BaseListBean<Recommend>>(){}.type return queryWhere<BaseListBean<Recommend>>(RECOMMEND, TableQueryParams(map), type) .flatMap { if (it.results != null && !it.results.isEmpty()) { throw ApiResponseException(30002,"已经有人推荐过了") } else { create(RECOMMEND, RecommendParams(picture.getPicUrl(), picture.getPicType(), picture.getPicWidth(), picture.getPicHeight(), user.objectId, user.nickname, desc, user.avatar, user.email)) } } } fun getRecommendList(offset:Int, limit:Int):Single<List<Recommend>> { val type: Type = object : TypeToken<BaseListBean<Recommend>>(){}.type return queryWhere<BaseListBean<Recommend>>(RECOMMEND, TableQueryParams(RecommendListParams(),order = "-createdAt",limit = limit, skip = offset), type) .map { it.results } } }
apache-2.0
838d0f4c261c7c122f2a5aa6b79acd5d
39.326923
158
0.591126
4.536797
false
false
false
false
delr3ves/HaveANiceDayAndroid
mobile/src/main/kotlin/com/emaginalabs/haveaniceday/app/notification/HappyNotificationMessagingService.kt
1
5172
package com.emaginalabs.haveaniceday.app.notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.Drawable import android.support.v4.app.NotificationCompat import com.bumptech.glide.Glide import com.bumptech.glide.request.target.SimpleTarget import com.bumptech.glide.request.transition.Transition import com.emabinalabs.haveaniceday.R import com.emaginalabs.haveaniceday.app.HaveANiceDayApplication import com.emaginalabs.haveaniceday.app.MainActivity import com.emaginalabs.haveaniceday.core.dao.NotificationDAO import com.emaginalabs.haveaniceday.core.model.Notification import com.emaginalabs.haveaniceday.core.usecase.UpdateNotificationBudget import com.emaginalabs.haveaniceday.core.utils.TimeProvider import com.github.salomonbrys.kodein.LazyKodein import com.github.salomonbrys.kodein.LazyKodeinAware import com.github.salomonbrys.kodein.android.appKodein import com.github.salomonbrys.kodein.instance import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import org.jetbrains.anko.runOnUiThread import java.util.* object HappyNotificationMessaging { val RECEIVED_NOTIFICATION = "receivedNotification" } class HappyNotificationMessagingService : FirebaseMessagingService(), LazyKodeinAware { override val kodein = LazyKodein(appKodein) private val notificationDAO: NotificationDAO by instance() private val timeProvider: TimeProvider by instance() private val updateNotificationBudget: UpdateNotificationBudget by instance() override fun onMessageReceived(remoteMessage: RemoteMessage) { val title = remoteMessage.data.get("title") val message = remoteMessage.data.get("message") val photo = remoteMessage.data.get("photoUrl") val notification = Notification( title = title, message = message, photoUrl = photo, createdAt = timeProvider.now().millis, read = false ) val createdNotification = notification.copy(id = notificationDAO.insert(notification)) sendNotification(createdNotification) updateNotificationBudget.execute() } private fun sendNotification(notification: Notification) { val intent = Intent(this, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) intent.putExtra(HappyNotificationMessaging.RECEIVED_NOTIFICATION, notification) val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT) val appName = getString(R.string.app_name) val notificationBuilder = NotificationCompat.Builder(this, (this.application as HaveANiceDayApplication).channelId()) .setSmallIcon(R.mipmap.ic_notify) .setBadgeIconType(R.mipmap.ic_launcher) .setChannelId(appName) .setContentTitle(notification.title) .setContentText(notification.message) .setAutoCancel(true) .setContentIntent(pendingIntent) .setNumber(1) .setColor(255) .setWhen(System.currentTimeMillis()) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationId = notification.id?.toInt() ?: Random().nextInt() if (notification.photoUrl != null) { runOnUiThread { Glide.with(applicationContext) .asBitmap() .load(notification.photoUrl) .into(object : SimpleTarget<Bitmap>() { override fun onResourceReady(resource: Bitmap?, transition: Transition<in Bitmap>?) { notifyWithImage(resource, notification, notificationBuilder, notificationManager, notificationId) } override fun onLoadFailed(errorDrawable: Drawable?) { val picture = BitmapFactory.decodeResource(resources, R.mipmap.happy_loader) notifyWithImage(picture, notification, notificationBuilder, notificationManager, notificationId) } }) } } else { notificationManager.notify(notificationId, notificationBuilder.build()) } } private fun notifyWithImage( picture: Bitmap?, notification: Notification, notificationBuilder: NotificationCompat.Builder, notificationManager: NotificationManager, notificationId: Int) { val bigPictureStyle = NotificationCompat.BigPictureStyle() .bigPicture(picture) .setSummaryText(notification.message) notificationBuilder.setStyle(bigPictureStyle) notificationManager.notify(notificationId, notificationBuilder.build()) } }
apache-2.0
14a93ae9da1701eee4e9ed0ddffc35ed
43.586207
129
0.689675
5.293756
false
false
false
false
profan/mal
kotlin/src/mal/step5_tco.kt
1
3814
package mal fun read(input: String?): MalType = read_str(input) fun eval(_ast: MalType, _env: Env): MalType { var ast = _ast var env = _env while (true) { if (ast is MalList) { val first = ast.first() if (first is MalSymbol && first.value == "def!") { return env.set(ast.nth(1) as MalSymbol, eval(ast.nth(2), env)) } else if (first is MalSymbol && first.value == "let*") { val childEnv = Env(env) val bindings = ast.nth(1) as? ISeq ?: throw MalException("expected sequence as the first parameter to let*") val it = bindings.seq().iterator() while (it.hasNext()) { val key = it.next() if (!it.hasNext()) throw MalException("odd number of binding elements in let*") childEnv.set(key as MalSymbol, eval(it.next(), childEnv)) } env = childEnv ast = ast.nth(2) } else if (first is MalSymbol && first.value == "fn*") { return fn_STAR(ast, env) } else if (first is MalSymbol && first.value == "do") { eval_ast(ast.slice(1, ast.seq().count() - 1), env) ast = ast.seq().last() } else if (first is MalSymbol && first.value == "if") { val check = eval(ast.nth(1), env) if (check !== NIL && check !== FALSE) { ast = ast.nth(2) } else if (ast.seq().asSequence().count() > 3) { ast = ast.nth(3) } else return NIL } else { val evaluated = eval_ast(ast, env) as ISeq val firstEval = evaluated.first() if (firstEval is MalFnFunction) { ast = firstEval.ast env = Env(firstEval.env, firstEval.params, evaluated.rest().seq()) } else if (firstEval is MalFunction) { return firstEval.apply(evaluated.rest()) } else throw MalException("cannot execute non-function") } } else return eval_ast(ast, env) } } fun eval_ast(ast: MalType, env: Env): MalType = if (ast is MalSymbol) { env.get(ast) } else if (ast is MalList) { ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a }) } else if (ast is MalVector) { ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a }) } else if (ast is MalHashMap) { ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a }) } else ast private fun fn_STAR(ast: MalList, env: Env): MalType { val binds = ast.nth(1) as? ISeq ?: throw MalException("fn* requires a binding list as first parameter") val params = binds.seq().filterIsInstance<MalSymbol>() val body = ast.nth(2) return MalFnFunction(body, params, env, { s: ISeq -> eval(body, Env(env, params, s.seq())) }) } fun print(result: MalType) = pr_str(result, print_readably = true) fun rep(input: String, env: Env): String = print(eval(read(input), env)) fun main(args: Array<String>) { val repl_env = Env() ns.forEach({ it -> repl_env.set(it.key, it.value) }) rep("(def! not (fn* (a) (if a false true)))", repl_env) while (true) { val input = readline("user> ") try { println(rep(input, repl_env)) } catch (e: EofException) { break } catch (e: MalContinue) { } catch (e: MalException) { println("Error: " + e.message) } catch (t: Throwable) { println("Uncaught " + t + ": " + t.message) t.printStackTrace() } } }
mpl-2.0
3e3da684ea5f804114aac50ba777f356
36.762376
124
0.511536
3.868154
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Block.kt
4
1392
// 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.j2k.ast import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.j2k.append class Block(val statements: List<Statement>, val lBrace: LBrace, val rBrace: RBrace, val notEmpty: Boolean = false) : Statement() { override val isEmpty: Boolean get() = !notEmpty && statements.all { it.isEmpty } override fun generateCode(builder: CodeBuilder) { if (statements.all { it.isEmpty }) { if (!isEmpty) builder.append(lBrace).append(rBrace) return } builder.append(lBrace).append(statements, "\n", "\n", "\n").append(rBrace) } companion object { val Empty = Block(listOf(), LBrace(), RBrace()) fun of(statement: Statement) = of(listOf(statement)) fun of(statements: List<Statement>) = Block(statements, LBrace().assignNoPrototype(), RBrace().assignNoPrototype(), notEmpty = true) } } // we use LBrace and RBrace elements to better handle comments around them class LBrace : Element() { override fun generateCode(builder: CodeBuilder) { builder.append("{") } } class RBrace : Element() { override fun generateCode(builder: CodeBuilder) { builder.append("}") } }
apache-2.0
ea36863ee269736406286633fcb50c59
33.8
158
0.670259
4.058309
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/base/plugin/test/org/jetbrains/kotlin/idea/artifacts/TestKotlinArtifacts.kt
1
5639
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.plugin.artifacts import com.intellij.openapi.application.PathManager import org.jetbrains.kotlin.idea.compiler.configuration.KotlinArtifactsDownloader.downloadArtifactForIdeFromSources import org.jetbrains.kotlin.idea.compiler.configuration.KotlinMavenUtils import java.io.File object TestKotlinArtifacts { private fun getLibraryFile(groupId: String, artifactId: String, libraryFileName: String): File { val version = KotlinMavenUtils.findLibraryVersion(libraryFileName) ?: error("Cannot find library version for library $libraryFileName") return KotlinMavenUtils.findArtifactOrFail(groupId, artifactId, version).toFile() } private fun getJar(artifactId: String) = downloadArtifactForIdeFromSources("kotlinc_kotlin_stdlib.xml", artifactId) private fun getSourcesJar(artifactId: String) = downloadArtifactForIdeFromSources("kotlinc_kotlin_stdlib.xml", artifactId, suffix = "-sources.jar") .copyTo( // Some tests hardcode jar names in their test data File(PathManager.getCommunityHomePath()) // (KotlinReferenceTypeHintsProviderTestGenerated). .resolve("out") // That's why we need to strip version from the jar name .resolve("kotlin-from-sources-deps-renamed") .resolve("$artifactId-sources.jar"), overwrite = true ) @JvmStatic val androidExtensionsRuntime: File by lazy { getJar("android-extensions-compiler-plugin-for-ide") } @JvmStatic val kotlinAnnotationsJvm: File by lazy { getJar("kotlin-annotations-jvm") } @JvmStatic val kotlinCompiler: File by lazy { getJar("kotlin-compiler") } @JvmStatic val kotlinDaemon: File by lazy { getJar("kotlin-daemon") } @JvmStatic val kotlinReflect: File by lazy { getJar("kotlin-reflect") } @JvmStatic val kotlinReflectSources: File by lazy { getSourcesJar("kotlin-reflect") } @JvmStatic val kotlinScriptRuntime: File by lazy { getJar("kotlin-script-runtime") } @JvmStatic val kotlinScriptingCommon: File by lazy { getJar("kotlin-scripting-common") } @JvmStatic val kotlinScriptingCompiler: File by lazy { getJar("kotlin-scripting-compiler") } @JvmStatic val kotlinScriptingCompilerImpl: File by lazy { getJar("kotlin-scripting-compiler-impl") } @JvmStatic val kotlinScriptingJvm: File by lazy { getJar("kotlin-scripting-jvm") } @JvmStatic val kotlinStdlib: File by lazy { getJar("kotlin-stdlib") } @JvmStatic val kotlinStdlibCommon: File by lazy { getJar("kotlin-stdlib-common") } @JvmStatic val kotlinStdlibCommonSources: File by lazy { getSourcesJar("kotlin-stdlib-common") } @JvmStatic val kotlinStdlibJdk7: File by lazy { getJar("kotlin-stdlib-jdk7") } @JvmStatic val kotlinStdlibJdk7Sources: File by lazy { getSourcesJar("kotlin-stdlib-jdk7") } @JvmStatic val kotlinStdlibJdk8: File by lazy { getJar("kotlin-stdlib-jdk8") } @JvmStatic val kotlinStdlibJdk8Sources: File by lazy { getSourcesJar("kotlin-stdlib-jdk8") } @JvmStatic val kotlinStdlibJs: File by lazy { getJar("kotlin-stdlib-js") } @JvmStatic val kotlinStdlibSources: File by lazy { getSourcesJar("kotlin-stdlib") } @JvmStatic val kotlinTest: File by lazy { getJar("kotlin-test") } @JvmStatic val kotlinTestJs: File by lazy { getJar("kotlin-test-js") } @JvmStatic val kotlinTestJunit: File by lazy { getJar("kotlin-test-junit") } @JvmStatic val parcelizeRuntime: File by lazy { getJar("parcelize-compiler-plugin-for-ide") } @JvmStatic val trove4j: File by lazy { getLibraryFile("org.jetbrains.intellij.deps", "trove4j", "Trove4j.xml") } @JvmStatic val jetbrainsAnnotations: File by lazy { getLibraryFile("org.jetbrains", "annotations", "jetbrains_annotations.xml") } @JvmStatic val jsr305: File by lazy { getLibraryFile("com.google.code.findbugs", "jsr305", "jsr305.xml") } @JvmStatic val junit3: File by lazy { getLibraryFile("junit", "junit", "JUnit3.xml") } @JvmStatic val compilerTestDataDir: File by lazy { downloadAndUnpack( libraryFileName = "kotlinc_kotlin_compiler_cli.xml", artifactId = "kotlin-compiler-testdata-for-ide", dirName = "kotlinc-testdata-2", ) } @JvmStatic fun compilerTestData(compilerTestDataPath: String): String { return compilerTestDataDir.resolve(compilerTestDataPath).canonicalPath } @JvmStatic val jpsPluginTestDataDir: File by lazy { downloadAndUnpack( libraryFileName = "kotlinc_kotlin_jps_plugin_tests.xml", artifactId = "kotlin-jps-plugin-testdata-for-ide", dirName = "kotlinc-jps-testdata", ) } @JvmStatic val jsIrRuntimeDir: File by lazy { downloadArtifactForIdeFromSources( libraryFileName = "kotlinc_kotlin_jps_plugin_tests.xml", artifactId = "js-ir-runtime-for-ide", suffix = ".klib" ) } @JvmStatic fun jpsPluginTestData(jpsTestDataPath: String): String { return jpsPluginTestDataDir.resolve(jpsTestDataPath).canonicalPath } private fun downloadAndUnpack(libraryFileName: String, artifactId: String, dirName: String): File { val jar = downloadArtifactForIdeFromSources(libraryFileName, artifactId) return LazyZipUnpacker(File(PathManager.getCommunityHomePath()).resolve("out").resolve(dirName)).lazyUnpack(jar) } }
apache-2.0
1eeb0ae6f7cb4c50bec2f43824837be6
55.39
133
0.704735
4.518429
false
true
false
false
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/refactoring/suggested/ChangeSignaturePopup.kt
8
14075
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.suggested import com.intellij.codeInsight.completion.LookupElementListPresenter import com.intellij.codeInsight.lookup.LookupManager import com.intellij.lang.LangBundle import com.intellij.lang.Language import com.intellij.lang.LanguageNamesValidation import com.intellij.openapi.Disposable import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComponentValidator import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Disposer import com.intellij.psi.PsiDocumentManager import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.suggested.SuggestedRefactoringExecution.NewParameterValue import com.intellij.ui.LanguageTextField import com.intellij.util.ui.JBUI import com.intellij.util.ui.UI import org.jetbrains.annotations.Nls import java.awt.* import java.awt.font.FontRenderContext import java.awt.geom.AffineTransform import java.util.function.Supplier import javax.swing.* import kotlin.math.roundToInt internal class ChangeSignaturePopup( signatureChangeModel: SignatureChangePresentationModel, nameOfStuffToUpdate: String, newParameterData: List<SuggestedRefactoringUI.NewParameterData>, project: Project, refactoringSupport: SuggestedRefactoringSupport, language: Language, colorsScheme: EditorColorsScheme, screenSize: Dimension ) : JPanel(BorderLayout()), Disposable { private val button = object : JButton() { override fun isDefaultButton() = true } @Nls private val updateButtonText = RefactoringBundle.message("suggested.refactoring.update.button.text") @Nls private val nextButtonText = RefactoringBundle.message("suggested.refactoring.next.button.text") private val editorFont = colorsScheme.getFont(EditorFontType.PLAIN) private val signatureChangePage = SignatureChangesPage(signatureChangeModel, editorFont, screenSize, nameOfStuffToUpdate) private val parameterValuesPage = if (newParameterData.isNotEmpty()) { ParameterValuesPage(project, language, refactoringSupport, editorFont, newParameterData, this::onParameterValueChanged).also { Disposer.register(this, it) } } else { null } private enum class Page { SignatureChange, ParameterValues } private var currentPage = Page.SignatureChange init { val buttonPanel = JPanel(BorderLayout()).apply { add(button, BorderLayout.EAST) } add(signatureChangePage, BorderLayout.CENTER) add(buttonPanel, BorderLayout.SOUTH) border = JBUI.Borders.empty(5, 2) button.text = if (parameterValuesPage == null) updateButtonText else nextButtonText button.addActionListener { when (currentPage) { Page.SignatureChange -> { if (parameterValuesPage != null) { parameterValuesPage.initialize() remove(signatureChangePage) add(parameterValuesPage, BorderLayout.CENTER) button.text = updateButtonText onParameterValueChanged(null) currentPage = Page.ParameterValues onNext() parameterValuesPage.defaultFocus() } else { onOk(newParameterData.map { data -> NewParameterInfo(data, data.presentableName, NewParameterValue.None) }) } } Page.ParameterValues -> { val updatedValues = parameterValuesPage!!.getUpdatedValues() if (updatedValues != null) { onOk(updatedValues) } } } } } lateinit var onNext: () -> Unit lateinit var onOk: (newParameterValues: List<NewParameterInfo>) -> Unit fun onEnter() { button.doClick() } fun isEnterEnabled(): Boolean { return when (currentPage) { Page.SignatureChange -> true Page.ParameterValues -> !parameterValuesPage!!.isLookupShown() && parameterValuesPage.areAllValuesCorrect() } } fun isEscapeEnabled(): Boolean { return when (currentPage) { Page.SignatureChange -> true Page.ParameterValues -> !parameterValuesPage!!.isLookupShown() } } override fun dispose() {} private fun onParameterValueChanged(validationInfo: ValidationInfo?) { button.isEnabled = (validationInfo == null || validationInfo.okEnabled) && (parameterValuesPage == null || parameterValuesPage.areAllValuesCorrect()) } } data class NewParameterInfo(val newParameterData: SuggestedRefactoringUI.NewParameterData, val name: String, val value: NewParameterValue) private class SignatureChangesPage( signatureChangeModel: SignatureChangePresentationModel, editorFont: Font, screenSize: Dimension, nameOfStuffToUpdate: String ) : JPanel(BorderLayout()) { init { val presentation = createPresentation(signatureChangeModel, editorFont, screenSize) add(JLabel(RefactoringBundle.message("suggested.refactoring.change.signature.label.text", nameOfStuffToUpdate)), BorderLayout.NORTH) add( object : JComponent() { init { preferredSize = presentation.requiredSize } override fun paint(g: Graphics) { presentation.paint(g as Graphics2D, Rectangle(0, 0, width, height)) } }, BorderLayout.CENTER ) border = JBUI.Borders.empty(0, 4) } private fun createPresentation( model: SignatureChangePresentationModel, editorFont: Font, screenSize: Dimension ): SignatureChangePresentation { // we use editor scheme that is the default for the current UI theme // (we don't use one from the current editor because one can have light UI theme and dark editor scheme or vise versa) val themeColorsScheme = EditorColorsManager.getInstance().schemeForCurrentUITheme var font = editorFont val maxWidthHorizontalMode = screenSize.width * 0.75 val maxWidth = screenSize.width * 0.9 val maxHeight = screenSize.height * 0.9 val minFontSize = 8 while (true) { var presentation = SignatureChangePresentation(model, font, themeColorsScheme, verticalMode = false) if (presentation.requiredSize.width > maxWidthHorizontalMode) { presentation = SignatureChangePresentation(model, font, themeColorsScheme, verticalMode = true) } if (presentation.requiredSize.width <= maxWidth && presentation.requiredSize.height <= maxHeight || font.size <= minFontSize) { return presentation } font = Font(font.name, font.style, font.size - 1) } } } private class ParameterValuesPage( private val project: Project, private val language: Language, private val refactoringSupport: SuggestedRefactoringSupport, private val editorFont: Font, private val newParameterData: List<SuggestedRefactoringUI.NewParameterData>, private val onValueChanged: (ValidationInfo?) -> Unit ) : JPanel(BorderLayout()), Disposable { private val newParameterControls = mutableListOf<ParameterControls>() private val focusSequence = mutableListOf<() -> JComponent>() private inner class ParameterControls( val data: SuggestedRefactoringUI.NewParameterData, val nameField: JTextField?, val useAny: JCheckBox?, val valueField: LanguageTextField) { fun isLookupShown(): Boolean = (LookupManager.getActiveLookup(valueField.editor) as LookupElementListPresenter?)?.isShown ?: false fun isValid(): Boolean = getValue() != null && isNameCorrect(nameField?.text) fun toInfo(): NewParameterInfo? { return if (!isValid()) null else NewParameterInfo(data, nameField?.text?:data.presentableName, getValue()!!) } fun getValue(): NewParameterValue? { if (useAny != null && useAny.isSelected) return NewParameterValue.AnyVariable if (refactoringSupport.ui.validateValue(data, null).let { it != null && !it.okEnabled }) return null return when { valueField.text.isBlank() -> NewParameterValue.None else -> refactoringSupport.ui.extractValue(data.valueFragment) } } } fun initialize() { val label = JLabel(RefactoringBundle.message("suggested.refactoring.parameter.values.label.text")).apply { border = JBUI.Borders.empty(0, 6, 0, 6) } add(label, BorderLayout.NORTH) val panel = JPanel(GridBagLayout()).apply { border = JBUI.Borders.empty(10, 6, 18, 6) } add(panel, BorderLayout.CENTER) val dummyContext = FontRenderContext(AffineTransform(), false, false) val textFieldWidth = (editorFont.getMaxCharBounds(dummyContext).width * 25).roundToInt() val c = GridBagConstraints() c.gridy = 0 c.anchor = GridBagConstraints.LINE_START c.fill = GridBagConstraints.HORIZONTAL var isFirstCheckbox = true val documentManager = PsiDocumentManager.getInstance(project) for (data in newParameterData) { c.gridx = 0 c.weightx = 1.0 c.insets = Insets(0, 0, 0, 0) val nameComponent: JComponent if (data.suggestRename) { nameComponent = JTextField(data.presentableName).apply { font = editorFont preferredSize = Dimension(textFieldWidth / 2, preferredSize.height) } nameComponent.selectAll() ComponentValidator(this@ParameterValuesPage) .withValidator( Supplier { if (!isNameCorrect(nameComponent.text)) { ValidationInfo(LangBundle.message("popup.title.inserted.identifier.valid"), nameComponent).also(onValueChanged) } else { null.also(onValueChanged) } } ) .installOn(nameComponent) .andRegisterOnDocumentListener(nameComponent) .andStartOnFocusLost() focusSequence.add { nameComponent } } else { nameComponent = JLabel(data.presentableName).apply { font = editorFont } } panel.add(nameComponent, c) c.gridx++ c.weightx = 0.0 panel.add(JLabel("=").apply { font = editorFont }) c.gridx++ c.weightx = 1.0 c.insets = Insets(0, 4, 0, 0) val document = documentManager.getDocument(data.valueFragment)!! val textField = MyTextField(language, project, document, data.placeholderText).apply { setPreferredWidth(textFieldWidth) ComponentValidator(this@ParameterValuesPage) .withValidator( Supplier { documentManager.commitDocument(document) refactoringSupport.ui.validateValue(data, component).also { onValueChanged(it) } } ) .installOn(component) .andRegisterOnDocumentListener(this) .andStartOnFocusLost() } panel.add(textField, c) focusSequence.add { textField.editor!!.contentComponent } c.gridx++ val checkBox: JCheckBox? if (data.offerToUseAnyVariable) { c.weightx = 0.0 c.insets = Insets(0, 10, 0, 0) checkBox = JCheckBox(RefactoringBundle.message("suggested.refactoring.use.any.variable.checkbox.text")) panel.add(checkBox, c) focusSequence.add { checkBox } checkBox.addItemListener { textField.isEnabled = !checkBox.isSelected } if (isFirstCheckbox) { val hint = RefactoringBundle.message("suggested.refactoring.use.any.variable.checkbox.hint") panel.add(UI.PanelFactory.panel(checkBox).withTooltip(hint).createPanel(), c) } isFirstCheckbox = false } else { checkBox = null } newParameterControls.add(ParameterControls(data, nameComponent as? JTextField, checkBox, textField)) c.gridy++ } isFocusCycleRoot = true focusTraversalPolicy = MyFocusTraversalPolicy() } fun defaultFocus() { focusSequence.first()().requestFocusInWindow() } fun isLookupShown(): Boolean { return newParameterControls.any(ParameterControls::isLookupShown) } fun areAllValuesCorrect(): Boolean { return newParameterControls.all(ParameterControls::isValid) } fun isNameCorrect(name: String?): Boolean = name == null || LanguageNamesValidation.isIdentifier(language, name, project) override fun dispose() {} fun getUpdatedValues(): List<NewParameterInfo>? { return newParameterControls.map { it.toInfo() ?: return null } } private class MyTextField(language: Language, project: Project, document: Document, @Nls private val placeholderText: String?) : LanguageTextField(language, project, "", { _, _, _ -> document }, true) { override fun createEditor(): EditorEx { return super.createEditor().apply { setPlaceholder(placeholderText ?: RefactoringBundle.message("suggested.refactoring.parameter.values.placeholder")) setShowPlaceholderWhenFocused(true) } } } private inner class MyFocusTraversalPolicy : FocusTraversalPolicy() { override fun getComponentAfter(aContainer: Container, aComponent: Component?): Component? { val index = focusSequence.indexOfFirst { it() == aComponent } if (index < 0) return null return if (index < focusSequence.lastIndex) focusSequence[index + 1]() else focusSequence.first()() } override fun getComponentBefore(aContainer: Container, aComponent: Component?): Component? { val index = focusSequence.indexOfFirst { it() == aComponent } if (index < 0) return null return if (index > 0) focusSequence[index - 1]() else focusSequence.last()() } override fun getDefaultComponent(aContainer: Container) = focusSequence.first()() override fun getFirstComponent(aContainer: Container) = focusSequence.first()() override fun getLastComponent(aContainer: Container) = focusSequence.last()() } }
apache-2.0
f174d63ca9257853c791c7ac253b6a2c
35.275773
140
0.701812
4.743849
false
false
false
false
ChristopherGittner/OSMBugs
app/src/main/java/org/gittner/osmbugs/ui/ErrorViewModel.kt
1
9624
package org.gittner.osmbugs.ui import android.annotation.SuppressLint import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.android.schedulers.AndroidSchedulers import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.gittner.osmbugs.keepright.KeeprightApi import org.gittner.osmbugs.keepright.KeeprightDao import org.gittner.osmbugs.keepright.KeeprightError import org.gittner.osmbugs.mapdust.MapdustApi import org.gittner.osmbugs.mapdust.MapdustDao import org.gittner.osmbugs.mapdust.MapdustError import org.gittner.osmbugs.osmnotes.OsmNote import org.gittner.osmbugs.osmnotes.OsmNoteDao import org.gittner.osmbugs.osmnotes.OsmNotesApi import org.gittner.osmbugs.osmose.OsmoseApi import org.gittner.osmbugs.osmose.OsmoseDao import org.gittner.osmbugs.osmose.OsmoseError import org.gittner.osmbugs.statics.Settings import org.koin.core.KoinComponent import org.koin.core.inject import org.osmdroid.api.IGeoPoint import org.osmdroid.util.BoundingBox @SuppressLint("CheckResult") class ErrorViewModel : ViewModel(), KoinComponent { private val mSettings = Settings.getInstance() private val mError = MutableLiveData<String>() private val mOsmNotesApi: OsmNotesApi by inject() private val mOsmNoteDao: OsmNoteDao by inject() private val mOsmNotes = MutableLiveData<ArrayList<OsmNote>>(ArrayList()) private val mOsmNotesEnabled = MutableLiveData(mSettings.OsmNotes.Enabled) private val mKeeprightApi: KeeprightApi by inject() private val mKeeprightDao: KeeprightDao by inject() private val mKeeprightErrors = MutableLiveData<ArrayList<KeeprightError>>(ArrayList()) private val mKeeprightEnabled = MutableLiveData(mSettings.Keepright.Enabled) private val mMapdustApi: MapdustApi by inject() private val mMapdustDao: MapdustDao by inject() private val mMapdustErrors = MutableLiveData<ArrayList<MapdustError>>(ArrayList()) private val mMapdustEnabled = MutableLiveData(mSettings.Mapdust.Enabled) private val mOsmoseApi: OsmoseApi by inject() private val mOsmoseDao: OsmoseDao by inject() private val mOsmoseErrors = MutableLiveData<ArrayList<OsmoseError>>(ArrayList()) private val mOsmoseEnabled = MutableLiveData(mSettings.Osmose.Enabled) private val mContentLoading = MutableLiveData(false) init { mOsmNoteDao.getAll() .observeOn(AndroidSchedulers.mainThread()) .subscribe { mOsmNotes.value!!.clear() mOsmNotes.value!!.addAll(it) mOsmNotes.value = mOsmNotes.value } mKeeprightDao.getAll() .observeOn(AndroidSchedulers.mainThread()) .subscribe { mKeeprightErrors.value!!.clear() mKeeprightErrors.value!!.addAll(it) mKeeprightErrors.value = mKeeprightErrors.value } mMapdustDao.getAll() .observeOn(AndroidSchedulers.mainThread()) .subscribe { mMapdustErrors.value!!.clear() mMapdustErrors.value!!.addAll(it) mMapdustErrors.value = mMapdustErrors.value } mOsmoseDao.getAll() .observeOn(AndroidSchedulers.mainThread()) .subscribe { mOsmoseErrors.value!!.clear() mOsmoseErrors.value!!.addAll(it) mOsmoseErrors.value = mOsmoseErrors.value } } fun getError(): LiveData<String> { return mError } fun getOsmNotes(): LiveData<ArrayList<OsmNote>> { return mOsmNotes } fun getOsmNotesEnabled(): LiveData<Boolean> { return mOsmNotesEnabled } fun setOsmNotesEnabled(enabled: Boolean) { mOsmNotesEnabled.value = enabled } fun getKeeprightErrors(): LiveData<ArrayList<KeeprightError>> { return mKeeprightErrors } fun getKeeprightEnabled(): LiveData<Boolean> { return mKeeprightEnabled } fun setKeeprightEnabled(enabled: Boolean) { mKeeprightEnabled.value = enabled } fun getMapdustErrors(): LiveData<ArrayList<MapdustError>> { return mMapdustErrors } fun getMapdustEnabled(): LiveData<Boolean> { return mMapdustEnabled } fun setMapdustEnabled(enabled: Boolean) { mMapdustEnabled.value = enabled } fun getOsmoseErrors(): LiveData<ArrayList<OsmoseError>> { return mOsmoseErrors } fun getOsmoseEnabled(): LiveData<Boolean> { return mOsmoseEnabled } fun setOsmoseEnabled(enabled: Boolean) { mOsmoseEnabled.value = enabled } fun toggleOsmNotesEnabled() { val new = !mOsmNotesEnabled.value!! mSettings.OsmNotes.Enabled = new mOsmNotesEnabled.value = new } fun toggleKeeprightEnabled() { val new = !mKeeprightEnabled.value!! mSettings.Keepright.Enabled = new mKeeprightEnabled.value = new } fun toggleMapdustEnabled() { val new = !mMapdustEnabled.value!! mSettings.Mapdust.Enabled = new mMapdustEnabled.value = new } fun toggleOsmoseEnabled() { val new = !mOsmoseEnabled.value!! mSettings.Osmose.Enabled = new mOsmoseEnabled.value = new } fun getContentLoading(): LiveData<Boolean> { return mContentLoading } fun reloadErrors(mapCenter: IGeoPoint, boundingBox: BoundingBox) { if (mContentLoading.value!!) { return } GlobalScope.launch(Dispatchers.Main) { mContentLoading.value = true try { if (mOsmNotesEnabled.value!!) { val errors = mOsmNotesApi.download( boundingBox, mSettings.OsmNotes.ShowClosed, mSettings.OsmNotes.ErrorLimit ) mOsmNoteDao.replaceAll(errors) } } catch (err: Exception) { mError.value = err.message } try { if (mKeeprightEnabled.value!!) { val errors = mKeeprightApi.download( mapCenter, mSettings.Keepright.ShowIgnored, mSettings.Keepright.ShowTmpIgnored, mSettings.isLanguageGerman() ) mKeeprightDao.replaceAll(errors) } } catch (err: Exception) { mError.value = err.message } try { if (mMapdustEnabled.value!!) { val errors = mMapdustApi.download(boundingBox) mMapdustDao.replaceAll(errors) } } catch (err: Exception) { mError.value = err.message } try { if (mOsmoseEnabled.value!!) { val errors = mOsmoseApi.download(boundingBox) mOsmoseDao.replaceAll(errors) } } catch (err: Exception) { mError.value = err.message } mContentLoading.value = false } } suspend fun updateOsmNote(osmNote: OsmNote, newComment: String, newState: OsmNote.STATE) { try { if (osmNote.State == OsmNote.STATE.OPEN && newState == OsmNote.STATE.CLOSED) { mOsmNotesApi.closeNote(osmNote.Id, newComment) } else if (osmNote.State == OsmNote.STATE.OPEN && newState == OsmNote.STATE.OPEN) { mOsmNotesApi.addComment(osmNote.Id, newComment) } else if (osmNote.State == OsmNote.STATE.CLOSED && newState == OsmNote.STATE.OPEN) { mOsmNotesApi.reopenNote(osmNote.Id, newComment) } else { throw RuntimeException("Closed Notes cannot be commented on") } } finally { // Try to reload this note and replace the old one. // If we can not load the new Node, we at least remove the old one try { mOsmNoteDao.insert(mOsmNotesApi.download(osmNote.Id)) } catch (err: Exception) { mOsmNoteDao.delete(osmNote) } } } suspend fun updateKeeprightError(error: KeeprightError, newComment: String, newState: KeeprightError.STATE) { mKeeprightApi.comment(error.Schema, error.Id, newComment, newState) val newError = KeeprightError(error, newComment, newState) mKeeprightDao.insert(newError) } suspend fun updateMapdustError(error: MapdustError, newComment: String, newState: MapdustError.STATE) { if (newState != error.State) { mMapdustApi.changeErrorStatus(error.Id, newComment, newState) error.State = newState } else { mMapdustApi.commentError(error.Id, newComment) } // Add the New Comment to the Error error.Comments.add(MapdustError.MapdustComment(newComment, mSettings.Mapdust.Username)) mMapdustDao.insert(error) } suspend fun addOsmNote(point: IGeoPoint, comment: String) { mOsmNoteDao.insert(mOsmNotesApi.addNote(point, comment)) } suspend fun addMapdustError(point: IGeoPoint, type: MapdustError.ERROR_TYPE, description: String) { val newId = mMapdustApi.addBug(point, type, description) val newError = mMapdustApi.download(newId) mMapdustDao.insert(newError) } }
mit
90399fc3ab7997f6e2b7a028a6109338
31.516892
113
0.632273
4.44732
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/abl-api-client/src/main/kotlin/dev/mfazio/abl/api/models/ScheduledGameApiModel.kt
1
1448
package dev.mfazio.abl.api.models import java.time.LocalDateTime data class ScheduledGameApiModel( val gameId: String, val gameStatus: ScheduledGameStatusApiModel, val gameStartTime: LocalDateTime, val homeTeam: ScheduledGameTeamApiModel, val awayTeam: ScheduledGameTeamApiModel, val inning: Int? = null, val isTopOfInning: Boolean = false, val outs: Int? = null, val occupiedBases: OccupiedBasesApiModel? = null ) data class ScheduledGameTeamApiModel( val teamId: String, val teamNickname: String, val score: Int = 0, val wins: Int = 0, val losses: Int = 0, val startingPitcher: ScheduledGamePitcherApiModel? = null, val currentPitcher: ScheduledGamePitcherApiModel? = null, val currentBatter: ScheduledGameBatterApiModel? = null, val pitcherOfRecord: ScheduledGamePitcherApiModel? = null, val savingPitcher: ScheduledGamePitcherApiModel? = null ) data class ScheduledGamePitcherApiModel( val playerId: String, val playerName: String, val wins: Int = 0, val losses: Int = 0, val era: Double = 0.0, val saves: Int = 0 ) data class ScheduledGameBatterApiModel( val playerId: String, val playerName: String, val hitsToday: Int = 0, val atBatsToday: Int = 0, val battingAverage: Double = 0.0 ) data class OccupiedBasesApiModel( val first: Boolean = false, val second: Boolean = false, val third: Boolean = false )
apache-2.0
83ebc06a8da222aae53e05884d3104da
27.411765
62
0.714779
4
false
false
false
false
icela/FriceEngine
src/org/frice/obj/button/SimpleButton.kt
1
846
package org.frice.obj.button import org.frice.event.MOUSE_PRESSED import org.frice.event.OnMouseEvent import org.frice.resource.graphics.ColorResource import org.frice.util.shape.FShapeQuad import java.util.function.Consumer /** * Created by ice1000 on 2016/8/18. * * @author ice1000 * @since v0.3.3 */ open class SimpleButton @JvmOverloads constructor( var originalColor: ColorResource = ColorResource.GRAY, override var text: String, override var x: Double, override var y: Double, override var width: Double, override var height: Double) : FButton, FText(), FShapeQuad { private var bool = false override var onMouseListener: Consumer<OnMouseEvent>? = null override val color get() = if (bool) originalColor.darker() else originalColor override fun buttonStateChange(e: OnMouseEvent) { bool = e.type == MOUSE_PRESSED } }
agpl-3.0
20ab41b8a9530372e014a6e0b625df44
24.666667
79
0.762411
3.439024
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/player/profile/FriendProfileViewController.kt
1
13959
package io.ipoli.android.player.profile import android.annotation.SuppressLint import android.content.res.ColorStateList import android.graphics.PorterDuff import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.annotation.ColorInt import android.support.annotation.DrawableRes import android.support.constraint.ConstraintSet import android.support.design.widget.TabLayout import android.support.v4.graphics.drawable.DrawableCompat import android.support.v7.widget.GridLayoutManager import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.RouterTransaction import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import io.ipoli.android.R import io.ipoli.android.common.ViewUtils import io.ipoli.android.common.datetime.startOfDayUTC import io.ipoli.android.common.redux.android.ReduxViewController import io.ipoli.android.common.view.* import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel import io.ipoli.android.common.view.recyclerview.SimpleViewHolder import io.ipoli.android.pet.AndroidPetAvatar import io.ipoli.android.pet.PetItem import io.ipoli.android.player.data.AndroidAttribute import io.ipoli.android.player.data.AndroidAvatar import io.ipoli.android.player.data.AndroidRank import io.ipoli.android.player.profile.ProfileViewState.StateType.* import kotlinx.android.synthetic.main.controller_profile_friend.view.* import kotlinx.android.synthetic.main.item_friend_profile_attribute.view.* import kotlinx.android.synthetic.main.view_loader.view.* import kotlinx.android.synthetic.main.view_profile_pet.view.* import org.threeten.bp.LocalDate import org.threeten.bp.Period import java.util.* class FriendProfileViewController(args: Bundle? = null) : ReduxViewController<ProfileAction, ProfileViewState, ProfileReducer>(args) { override val reducer = ProfileReducer(ProfileReducer.FRIEND_KEY + UUID.randomUUID().toString()) private var friendId: String = "" private val tabListener = object : TabLayout.OnTabSelectedListener { override fun onTabReselected(tab: TabLayout.Tab?) { } override fun onTabUnselected(tab: TabLayout.Tab?) { } override fun onTabSelected(tab: TabLayout.Tab) { showPageAtPosition(view, tab.position) } } private fun showPageAtPosition(view: View?, position: Int) { view?.let { val childRouter = getChildRouter(it.profileTabContainer) childRouter.setRoot(RouterTransaction.with(getViewControllerForPage(position))) } } constructor(friendId: String) : this() { this.friendId = friendId } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { setHasOptionsMenu(true) val view = container.inflate(io.ipoli.android.R.layout.controller_profile_friend) setToolbar(view.toolbar) val collapsingToolbar = view.collapsingToolbarContainer collapsingToolbar.isTitleEnabled = false view.toolbar.title = stringRes(io.ipoli.android.R.string.controller_profile_title) view.toolbar.setBackgroundColor(attrData(R.attr.colorPrimary)) var coloredBackground = view.coloredBackground.background.mutate() coloredBackground = DrawableCompat.wrap(coloredBackground) DrawableCompat.setTint(coloredBackground, attrData(R.attr.colorPrimary)) DrawableCompat.setTintMode(coloredBackground, PorterDuff.Mode.SRC_IN) val avatarBackground = view.friendPlayerAvatar.background as GradientDrawable avatarBackground.setColor(attrData(android.R.attr.colorBackground)) view.attributes.adapter = AttributeAdapter() view.attributes.layoutManager = object : GridLayoutManager(view.context, 6) { override fun canScrollVertically() = false } view.post { view.requestFocus() } view.follow.dispatchOnClick { ProfileAction.Follow(friendId) } view.unfollow.dispatchOnClick { ProfileAction.Unfollow(friendId) } return view } override fun onAttach(view: View) { super.onAttach(view) showBackButton() view.tabLayout.getTabAt(0)!!.select() view.tabLayout.addOnTabSelectedListener(tabListener) showPageAtPosition(view, 0) } override fun onDetach(view: View) { view.tabLayout.removeOnTabSelectedListener(tabListener) resetDecorView() super.onDetach(view) } private fun resetDecorView() { activity?.let { it.window.decorView.systemUiVisibility = 0 } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> return router.handleBack() } return super.onOptionsItemSelected(item) } override fun onCreateLoadAction() = ProfileAction.Load(friendId) override fun render(state: ProfileViewState, view: View) { when (state.type) { LOADING -> { view.profileContainer.gone() view.loader.visible() } PROFILE_DATA_LOADED -> { activity!!.invalidateOptionsMenu() view.loader.gone() view.profileContainer.visible() renderMembershipStatus(state, view) renderAvatar(state, view) renderInfo(state, view) renderPet(state, view) renderAttributes(state, view) if (state.isCurrentPlayerGuest!!) { view.follow.visible() view.follow.setOnClickListener { showShortToast(R.string.error_need_registration) } view.unfollow.gone() view.isFollower.gone() return } if (state.isFollower!!) { view.isFollower.visible() view.isFollower.text = stringRes(R.string.player_is_follower, state.displayNameText!!) } else { view.isFollower.gone() } if (state.isFollowing!!) { view.unfollow.visible() view.follow.gone() } else { view.unfollow.gone() view.follow.visible() } } FOLLOWING_STATUS_CHANGED -> { if (state.isFollowing!!) { view.unfollow.visible() view.follow.gone() } else { view.unfollow.gone() view.follow.visible() } } else -> { } } } private fun renderAttributes(state: ProfileViewState, view: View) { (view.attributes.adapter as AttributeAdapter).updateAll(state.attributeViewModels) } private fun renderPet( state: ProfileViewState, view: View ) { val pet = state.pet!! val avatar = AndroidPetAvatar.valueOf(pet.avatar.name) view.pet.setImageResource(avatar.image) view.petState.setImageResource(avatar.stateImage[pet.state]!!) val setItem: (ImageView, EquipmentItemViewModel?) -> Unit = { iv, vm -> if (vm == null) iv.invisible() else iv.setImageResource(vm.image) } setItem(view.hat, state.toItemViewModel(pet.equipment.hat)) setItem(view.mask, state.toItemViewModel(pet.equipment.mask)) setItem(view.bodyArmor, state.toItemViewModel(pet.equipment.bodyArmor)) if (pet.equipment.hat == null) { val set = ConstraintSet() val layout = view.petContainer set.clone(layout) set.connect(R.id.pet, ConstraintSet.START, R.id.petContainer, ConstraintSet.START, 0) set.connect(R.id.pet, ConstraintSet.END, R.id.petContainer, ConstraintSet.END, 0) set.connect(R.id.pet, ConstraintSet.TOP, R.id.petContainer, ConstraintSet.TOP, 0) set.connect(R.id.pet, ConstraintSet.BOTTOM, R.id.petContainer, ConstraintSet.BOTTOM, 0) set.applyTo(layout) } val background = view.friendPetAvatar.background as GradientDrawable background.setColor(colorRes(R.color.md_grey_50)) } private fun renderMembershipStatus(state: ProfileViewState, view: View) { if (state.isMember!!) { view.friendMembershipStatus.visible() view.friendMembershipStatusIcon.visible() val background = view.friendMembershipStatus.background as GradientDrawable background.setStroke( ViewUtils.dpToPx(2f, view.context).toInt(), attrData(io.ipoli.android.R.attr.colorAccent) ) } else { view.friendMembershipStatus.gone() view.friendMembershipStatusIcon.gone() } } private fun renderInfo(state: ProfileViewState, view: View) { view.friendDisplayName.text = state.displayNameText if (state.username.isNullOrBlank()) { view.friendUsername.gone() } else { view.friendUsername.visible() @SuppressLint("SetTextI18n") view.friendUsername.text = "@${state.username}" } view.description.text = state.bioText view.level.text = state.level.toString() view.joined.text = state.createdAgoText view.rank.text = state.rankText } private fun renderAvatar(state: ProfileViewState, view: View) { Glide.with(view.context).load(state.avatarImage) .apply(RequestOptions.circleCropTransform()) .into(view.friendPlayerAvatar) val background = view.friendPlayerAvatar.background as GradientDrawable background.setColor(colorRes(AndroidAvatar.valueOf(state.avatar.name).backgroundColor)) } private val ProfileViewState.avatarImage get() = AndroidAvatar.valueOf(avatar.name).image private val ProfileViewState.displayNameText get() = if (displayName.isNullOrBlank()) stringRes(io.ipoli.android.R.string.unknown_hero) else displayName private val ProfileViewState.createdAgoText: String get() { val p = Period.between(createdAgo.startOfDayUTC, LocalDate.now()) return when { p.isZero || p.isNegative -> stringRes(io.ipoli.android.R.string.today).toLowerCase() p.years > 0 -> "${p.years} years ago" p.months > 0 -> "${p.months} months ago" else -> "${p.days} days ago" } } private val ProfileViewState.bioText get() = if (bio.isNullOrBlank()) stringRes(io.ipoli.android.R.string.blank_bio) else bio private val ProfileViewState.rankText get() = stringRes(AndroidRank.valueOf(rank!!.name).title) private fun getViewControllerForPage(position: Int): Controller { return when (position) { 0 -> ProfileInfoViewController(reducer.stateKey, friendId) 1 -> ProfilePostListViewController(reducer.stateKey, friendId) 2 -> ProfilePlayerListViewController( reducerKey = reducer.stateKey, showFollowers = false, playerId = friendId ) 3 -> ProfilePlayerListViewController( reducerKey = reducer.stateKey, showFollowers = true, playerId = friendId ) 4 -> ProfileChallengeListViewController(reducer.stateKey, friendId) else -> throw IllegalArgumentException("Unknown controller position $position") } } data class AttributeViewModel( override val id: String, val level: String, @DrawableRes val background: Int, @DrawableRes val icon: Int, @ColorInt val levelColor: Int ) : RecyclerViewViewModel inner class AttributeAdapter : BaseRecyclerViewAdapter<AttributeViewModel>(R.layout.item_friend_profile_attribute) { override fun onBindViewModel(vm: AttributeViewModel, view: View, holder: SimpleViewHolder) { view.attrBackground.setImageResource(vm.background) view.attrIcon.setImageResource(vm.icon) view.attrLevel.text = vm.level val square = view.attrLevelBackground.drawable as GradientDrawable square.mutate() square.color = ColorStateList.valueOf(vm.levelColor) view.attrLevelBackground.setImageDrawable(square) } } data class EquipmentItemViewModel( @DrawableRes val image: Int, val item: PetItem ) private fun ProfileViewState.toItemViewModel(petItem: PetItem?): EquipmentItemViewModel? { val petItems = AndroidPetAvatar.valueOf(pet!!.avatar.name).items return petItem?.let { EquipmentItemViewModel(petItems[it]!!, it) } } private val ProfileViewState.attributeViewModels: List<AttributeViewModel> get() = attributes!!.map { val attr = AndroidAttribute.valueOf(it.type.name) AttributeViewModel( id = attr.name, level = it.level.toString(), background = attr.background, icon = attr.whiteIcon, levelColor = colorRes(attr.colorPrimaryDark) ) } }
gpl-3.0
79183776c3afe807b908da730c82cbf1
35.449086
100
0.638871
4.805164
false
false
false
false
iMeiji/Daily
app/src/main/java/com/meiji/daily/module/postscontent/PostsContentViewModel.kt
1
2759
package com.meiji.daily.module.postscontent import android.app.Application import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import com.meiji.daily.data.remote.IApi import com.meiji.daily.io import com.meiji.daily.mainThread import com.meiji.daily.util.ErrorAction import io.reactivex.disposables.CompositeDisposable import io.reactivex.functions.Consumer import retrofit2.Retrofit /** * Created by Meiji on 2017/12/5. */ class PostsContentViewModel internal constructor(application: Application, slug: String, private val mRetrofit: Retrofit) : AndroidViewModel(application) { private val mDisposable: CompositeDisposable var isLoading: MutableLiveData<Boolean> private set var html: MutableLiveData<String> private set init { isLoading = MutableLiveData() html = MutableLiveData() mDisposable = CompositeDisposable() handleData(slug) } private fun handleData(slug: String) { isLoading.value = true mRetrofit.create(IApi::class.java).getPostsContentBean(slug) .subscribeOn(io) .observeOn(mainThread) .subscribe(Consumer { bean -> isLoading.value = false html.value = parserHTML(bean.content) }, object : ErrorAction() { override fun doAction() { isLoading.value = false html.value = null } }.action()).let { mDisposable.add(it) } } private fun parserHTML(content: String): String { val css = "<link rel=\"stylesheet\" href=\"file:///android_asset/master.css\" type=\"text/css\">" return ("<!DOCTYPE html>\n" + "<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n" + "<head>\n" + "\t<meta charset=\"utf-8\" />\n</head>\n" + css + "\n<body>" + content + "</body>\n</html>") } override fun onCleared() { mDisposable.clear() super.onCleared() } class Factory internal constructor(private val mApplication: Application, private val mSlug: String, private val mRetrofit: Retrofit) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel> create(modelClass: Class<T>): T { return com.meiji.daily.module.postscontent.PostsContentViewModel(mApplication, mSlug, mRetrofit) as T } } }
apache-2.0
264bc808d21a36dd172efc899e7a9e67
33.061728
114
0.595868
4.80662
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/Cell.kt
2
9152
// 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.ui.dsl.builder import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.ui.validation.DialogValidation import com.intellij.openapi.ui.validation.DialogValidationRequestor import com.intellij.openapi.util.NlsContexts import com.intellij.ui.dsl.gridLayout.* import com.intellij.ui.layout.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import javax.swing.JComponent import javax.swing.JEditorPane import javax.swing.JLabel @ApiStatus.Internal internal const val DSL_INT_TEXT_RANGE_PROPERTY = "dsl.intText.range" enum class LabelPosition { LEFT, TOP } @ApiStatus.NonExtendable @JvmDefaultWithCompatibility interface Cell<out T : JComponent> : CellBase<Cell<T>> { @Deprecated("Use align method instead") override fun horizontalAlign(horizontalAlign: HorizontalAlign): Cell<T> @Deprecated("Use align method instead") override fun verticalAlign(verticalAlign: VerticalAlign): Cell<T> override fun align(align: Align): Cell<T> override fun resizableColumn(): Cell<T> override fun gap(rightGap: RightGap): Cell<T> override fun customize(customGaps: Gaps): Cell<T> /** * Component that occupies the cell */ val component: T /** * Comment assigned to the cell */ val comment: JEditorPane? fun focused(): Cell<T> fun applyToComponent(task: T.() -> Unit): Cell<T> override fun enabled(isEnabled: Boolean): Cell<T> override fun enabledIf(predicate: ComponentPredicate): Cell<T> override fun visible(isVisible: Boolean): Cell<T> override fun visibleIf(predicate: ComponentPredicate): Cell<T> /** * Changes [component] font to bold */ fun bold(): Cell<T> /** * Adds comment under the cell aligned by left edge with appropriate color and font size (macOS and Linux use smaller font). * * [comment] can contain HTML tags except &lt;html&gt;, which is added automatically * * \n does not work as new line in html, use &lt;br&gt; instead * * Links with href to http/https are automatically marked with additional arrow icon * * Use bundled icons with `<code>` tag, for example `<icon src='AllIcons.General.Information'>` * * The comment occupies the available width before the next comment (if present) or * whole remaining width. Visibility and enabled state of the cell affects comment as well. * * For layout [RowLayout.LABEL_ALIGNED] comment after second columns is placed in second column (there are technical problems, * can be implemented later) * * @see MAX_LINE_LENGTH_WORD_WRAP * @see MAX_LINE_LENGTH_NO_WRAP */ fun comment(@NlsContexts.DetailedDescription comment: String?, maxLineLength: Int = DEFAULT_COMMENT_WIDTH, action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<T> /** * Adds the label with optional mnemonic related to the cell component. * See also doc for overloaded method */ fun label(@NlsContexts.Label label: String, position: LabelPosition = LabelPosition.LEFT): Cell<T> /** * Adds the label related to the cell component at specified [position]. * [LabelPosition.TOP] labels occupy available width before the next top label (if present) or * whole remaining width. Visibility and enabled state of the cell affects the label as well. * * For layout [RowLayout.LABEL_ALIGNED] labels for two first columns are supported only (there are technical problems, * can be implemented later) */ fun label(label: JLabel, position: LabelPosition = LabelPosition.LEFT): Cell<T> /** * All components from the same width group will have the same width equals to maximum width from the group. */ fun widthGroup(group: String): Cell<T> /** * If this method is called, the value of the component will be stored to the backing property only if the component is enabled */ fun applyIfEnabled(): Cell<T> fun accessibleName(@Nls name: String): Cell<T> fun accessibleDescription(@Nls description: String): Cell<T> /** * Binds component value that is provided by [componentGet] and [componentSet] methods to specified [prop] property. * The property is applied only when [DialogPanel.apply] is invoked. Methods [DialogPanel.isModified] and [DialogPanel.reset] * are also supported automatically for bound properties. * This method is rarely used directly, see [Cell] extension methods named like "bindXXX" for specific components */ fun <V> bind(componentGet: (T) -> V, componentSet: (T, V) -> Unit, prop: MutableProperty<V>): Cell<T> @Deprecated("Use overloaded method") fun <V> bind(componentGet: (T) -> V, componentSet: (T, V) -> Unit, binding: PropertyBinding<V>): Cell<T> /** * Installs [property] as validation requestor. * @deprecated use [validationRequestor] instead */ @Deprecated("Use validationRequestor instead", ReplaceWith("validationRequestor(property::afterPropagation)")) @ApiStatus.ScheduledForRemoval fun graphProperty(property: GraphProperty<*>): Cell<T> = validationRequestor(property::afterPropagation) /** * Registers custom validation requestor for current [component]. * @param validationRequestor gets callback (component validator) that should be subscribed on custom event. */ fun validationRequestor(validationRequestor: (() -> Unit) -> Unit): Cell<T> /** * Registers custom [validationRequestor] for current [component]. * It allows showing validation waring/error on custom [component] event. For example on text change. */ fun validationRequestor(validationRequestor: DialogValidationRequestor): Cell<T> /** * Registers custom [validationRequestor] for current [component]. * It allows showing validation waring/error on custom [component] event. For example on text change. */ fun validationRequestor(validationRequestor: DialogValidationRequestor.WithParameter<T>): Cell<T> /** * Registers custom component data [validation]. * [validation] will be called on [validationRequestor] events and * when [DialogPanel.apply] event is happens. */ fun validation(validation: ValidationInfoBuilder.(T) -> ValidationInfo?): Cell<T> /** * Registers custom component data [validations]. * [validations] will be called on [validationRequestor] events and * when [DialogPanel.apply] event is happens. */ fun validation(vararg validations: DialogValidation): Cell<T> /** * Registers custom component data [validations]. * [validations] will be called on [validationRequestor] events and * when [DialogPanel.apply] event is happens. */ fun validation(vararg validations: DialogValidation.WithParameter<T>): Cell<T> /** * Registers custom component data [validation]. * [validation] will be called on [validationRequestor] events. */ fun validationOnInput(validation: ValidationInfoBuilder.(T) -> ValidationInfo?): Cell<T> /** * Registers custom component data [validations]. * [validations] will be called on [validationRequestor] events. */ fun validationOnInput(vararg validations: DialogValidation): Cell<T> /** * Registers custom component data [validations]. * [validations] will be called on [validationRequestor] events. */ fun validationOnInput(vararg validations: DialogValidation.WithParameter<T>): Cell<T> /** * Registers custom component data [validation]. * [validation] will be called when [DialogPanel.apply] event is happens. */ fun validationOnApply(validation: ValidationInfoBuilder.(T) -> ValidationInfo?): Cell<T> /** * Registers custom component data [validations]. * [validations] will be called when [DialogPanel.apply] event is happens. */ fun validationOnApply(vararg validations: DialogValidation): Cell<T> /** * Registers custom component data [validations]. * [validations] will be called when [DialogPanel.apply] event is happens. */ fun validationOnApply(vararg validations: DialogValidation.WithParameter<T>): Cell<T> /** * Shows error [message] if [condition] is true. Short version for particular case of [validationOnApply] */ fun errorOnApply(@NlsContexts.DialogMessage message: String, condition: (T) -> Boolean): Cell<T> /** * Shows error [message] if [condition] is true. Short version for particular case of [validationOnApply] */ fun addValidationRule(@NlsContexts.DialogMessage message: String, condition: (T) -> Boolean): Cell<T> /** * Registers [callback] that will be called for [component] from [DialogPanel.apply] method */ fun onApply(callback: () -> Unit): Cell<T> /** * Registers [callback] that will be called for [component] from [DialogPanel.reset] method */ fun onReset(callback: () -> Unit): Cell<T> /** * Registers [callback] that will be called for [component] from [DialogPanel.isModified] method */ fun onIsModified(callback: () -> Boolean): Cell<T> }
apache-2.0
57747f816e7f6d314f4ec5aa61ef804b
36.818182
129
0.728912
4.475306
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/ButtonStripItemView.kt
2
1513
package org.thoughtcrime.securesms.components import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.widget.ImageView import android.widget.TextView import androidx.appcompat.content.res.AppCompatResources import androidx.constraintlayout.widget.ConstraintLayout import org.thoughtcrime.securesms.R class ButtonStripItemView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { private val iconView: ImageView private val labelView: TextView init { inflate(context, R.layout.button_strip_item_view, this) iconView = findViewById(R.id.icon) labelView = findViewById(R.id.label) val array = context.obtainStyledAttributes(attrs, R.styleable.ButtonStripItemView) val iconId = array.getResourceId(R.styleable.ButtonStripItemView_bsiv_icon, -1) val icon: Drawable? = if (iconId > 0) AppCompatResources.getDrawable(context, iconId) else null val contentDescription = array.getString(R.styleable.ButtonStripItemView_bsiv_icon_contentDescription) val label = array.getString(R.styleable.ButtonStripItemView_bsiv_label) iconView.setImageDrawable(icon) iconView.contentDescription = contentDescription labelView.text = label array.recycle() } fun setOnIconClickedListener(onIconClickedListener: (() -> Unit)?) { iconView.setOnClickListener { onIconClickedListener?.invoke() } } }
gpl-3.0
982dc2327128e4c025aa53d95530b48a
32.622222
106
0.783873
4.52994
false
false
false
false
jk1/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/testPanels.kt
3
5921
// 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.ui.layout import com.intellij.CommonBundle import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ui.ComboBox import com.intellij.ui.JBIntSpinner import com.intellij.ui.components.CheckBox import com.intellij.ui.components.JBPasswordField import com.intellij.ui.components.RadioButton import com.intellij.ui.components.textFieldWithHistoryWithBrowseButton import java.awt.Dimension import java.awt.GridLayout import javax.swing.* fun labelRowShouldNotGrow(): JPanel { return panel { row("Create Android module") { CheckBox("Android module name:")() } row("Android module name:") { JTextField("input")() } } } fun secondColumnSmallerPanel(): JPanel { val selectForkButton = JButton("Select Other Fork") val branchCombobox = ComboBox<String>() val diffButton = JButton("Show Diff") val titleTextField = JTextField() val panel = panel { row("Base fork:") { JComboBox<String>(arrayOf())(growX, CCFlags.pushX) selectForkButton(growX) } row("Base branch:") { branchCombobox(growX, pushX) diffButton(growX) } row("Title:") { titleTextField() } row("Description:") { scrollPane(JTextArea()) } } // test scrollPane panel.preferredSize = Dimension(512, 256) return panel } @Suppress("unused") fun visualPaddingsPanelOnlyComboBox(): JPanel { return panel { row("Combobox:") { JComboBox<String>(arrayOf("one", "two"))(growX) } row("Combobox Editable:") { val field = JComboBox<String>(arrayOf("one", "two")) field.isEditable = true field(growX) } } } @Suppress("unused") fun visualPaddingsPanelOnlyButton(): JPanel { return panel { row("Button:") { button("label", growX) {} } } } @Suppress("unused") fun visualPaddingsPanelOnlyLabeledScrollPane(): JPanel { return panel { row("Description:") { scrollPane(JTextArea()) } } } @Suppress("unused") fun visualPaddingsPanelOnlyTextField(): JPanel { return panel { row("Text field:") { JTextField("text")() } } } fun visualPaddingsPanel(): JPanel { // we use growX to test right border return panel { row("Text field:") { JTextField("text")() } row("Password:") { JPasswordField("secret")() } row("Combobox:") { JComboBox<String>(arrayOf("one", "two"))(growX) } row("Combobox Editable:") { val field = JComboBox<String>(arrayOf("one", "two")) field.isEditable = true field(growX) } row("Button:") { button("label", growX) {} } row("CheckBox:") { CheckBox("enabled")() } row("RadioButton:") { JRadioButton("label")() } row("Spinner:") { JBIntSpinner(0, 0, 7)() } row("Text with browse:") { textFieldWithBrowseButton("File") } // test text baseline alignment row("All:") { cell { JTextField("t")() JPasswordField("secret")() JComboBox<String>(arrayOf("c1", "c2"))(growX) button("b") {} CheckBox("c")() JRadioButton("rb")() } } row("Scroll pane:") { scrollPane(JTextArea("first line baseline equals to label")) } } } fun fieldWithGear(): JPanel { return panel { row("Database:") { JTextField()() gearButton() } row("Master Password:") { JBPasswordField()() } } } fun alignFieldsInTheNestedGrid(): JPanel { return panel { buttonGroup { row { RadioButton("In KeePass")() row("Database:") { JTextField()() gearButton() } row("Master Password:") { JBPasswordField()(comment = "Stored using weak encryption.") } } } } } fun noteRowInTheDialog(): JPanel { val passwordField = JPasswordField() return panel { noteRow("Profiler requires access to the kernel-level API.\nEnter the sudo password to allow this. ") row("Sudo password:") { passwordField() } row { CheckBox(CommonBundle.message("checkbox.remember.password"), true)() } noteRow("Should be an empty row above as a gap. <a href=''>Click me</a>.") { System.out.println("Hello") } } } fun cellPanel(): JPanel { return panel { row("Repository:") { cell { ComboBox<String>()(comment = "Use File -> Settings Repository... to configure") JButton("Delete")() } } row { // need some pushx/grow component to test label cell grow policy if there is cell with several components scrollPane(JTextArea()) } } } fun commentAndPanel(): JPanel { return panel { row("Repository:") { cell { checkBox("Auto Sync", comment = "Use File -> Settings Repository... to configure") } } row { panel("Foo", JScrollPane(JTextArea())) } } } fun createLafTestPanel(): JPanel { val spacing = createIntelliJSpacingConfiguration() val panel = JPanel(GridLayout(0, 1, spacing.horizontalGap, spacing.verticalGap)) panel.add(JTextField("text")) panel.add(JPasswordField("secret")) panel.add(ComboBox<String>(arrayOf("one", "two"))) val field = ComboBox<String>(arrayOf("one", "two")) field.isEditable = true panel.add(field) panel.add(JButton("label")) panel.add(CheckBox("enabled")) panel.add(JRadioButton("label")) panel.add(JBIntSpinner(0, 0, 7)) panel.add(textFieldWithHistoryWithBrowseButton(null, "File", FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor())) return panel } fun withVerticalButtons(): JPanel { return panel { row { label("<html>Merging branch <b>foo</b> into <b>bar</b>") } row { scrollPane(JTextArea(), pushX) cell(isVerticalFlow = true) { button("Accept Yours", growX) {} button("Accept Theirs", growX) {} button("Merge ...", growX) {} } } } }
apache-2.0
083d0aaeb864f2e1626647f7ca1398ab
25.556054
140
0.637055
4.103257
false
false
false
false
santaevpavel/ClipboardTranslator
domain/src/test/kotlin/ru/santaev/clipboardtranslator/domain/MockApiService.kt
1
1432
package ru.santaev.clipboardtranslator.domain import com.example.santaev.domain.api.IApiService import com.example.santaev.domain.api.LanguagesResponseDto import com.example.santaev.domain.api.TranslateRequestDto import com.example.santaev.domain.api.TranslateResponseDto import com.example.santaev.domain.dto.LanguageDto import io.reactivex.Single class MockApiService : IApiService { override fun translate(request: TranslateRequestDto): Single<TranslateResponseDto> { val response = TranslateResponseDto( 200, request.targetLang, arrayListOf("translated ${request.originText} from ${request.originLang.code} " + "to ${request.targetLang.code}") ) return Single.just(response) } override fun getLanguages(): Single<LanguagesResponseDto> { val response = LanguagesResponseDto( arrayListOf(), listOf( kotlinLang, javaLang, cSharpLang, cPlusPlusLang ) ) return Single.just(response) } companion object { val kotlinLang = LanguageDto(0, "kotlin", "kt") val javaLang = LanguageDto(0, "java", "java") val cSharpLang = LanguageDto(0, "c sharp", "c#") val cPlusPlusLang = LanguageDto(0, "c plus plus", "c++") } }
apache-2.0
61944a5c7e5dc1e10d225b03740c888d
33.119048
97
0.613827
4.789298
false
false
false
false
avarun42/peer-pressure
app/src/main/java/me/arora/varun/peerpressure/MainActivity.kt
1
1695
package me.arora.varun.peerpressure import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import android.widget.TextClock import java.util.Locale import android.text.format.DateFormat.getBestDateTimePattern class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "Text Alarm" val dateView = findViewById(R.id.dateClock) as TextClock val db = DatabaseHelper.getInstance(this) /* If db is empty, must be populated */ if (db.isEmpty) { val initialContactsIntent = Intent(this@MainActivity, InitialContactsActivity::class.java) startActivity(initialContactsIntent) } val skeleton = "MMMddyyyy" val bestPattern = getBestDateTimePattern(Locale.getDefault(), skeleton) dateView.format12Hour = bestPattern dateView.format24Hour = bestPattern //view the time val intent = Intent(this@MainActivity, AlarmReceiver::class.java) stopService(intent) } fun addButtonClicked(V: View) { //open the new activity val intent = Intent(this@MainActivity, AddAlarmActivity::class.java) startActivity(intent) } fun contactButtonClicked(V: View) { val intent = Intent(this@MainActivity, AddContactActivity::class.java) startActivity(intent) } fun facebookButtonClicked(V: View) { val intent = Intent(this@MainActivity, ImportFacebookContactsActivity::class.java) startActivity(intent) } }
bsd-3-clause
62b85fffcbf570b219fdb7ff2c2e8e8b
29.818182
102
0.686726
4.496021
false
false
false
false
airbnb/lottie-android
lottie-compose/src/main/java/com/airbnb/lottie/compose/rememberLottieComposition.kt
1
12841
package com.airbnb.lottie.compose import android.content.Context import android.graphics.BitmapFactory import android.graphics.Typeface import android.util.Base64 import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import com.airbnb.lottie.LottieComposition import com.airbnb.lottie.LottieCompositionFactory import com.airbnb.lottie.LottieImageAsset import com.airbnb.lottie.LottieTask import com.airbnb.lottie.model.Font import com.airbnb.lottie.utils.Logger import com.airbnb.lottie.utils.Utils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import java.io.FileInputStream import java.io.IOException import java.util.zip.ZipInputStream import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException /** * Use this with [rememberLottieComposition#cacheKey]'s cacheKey parameter to generate a default * cache key for the composition. */ private const val DefaultCacheKey = "__LottieInternalDefaultCacheKey__" /** * Takes a [LottieCompositionSpec], attempts to load and parse the animation, and returns a [LottieCompositionResult]. * * [LottieCompositionResult] allows you to explicitly check for loading, failures, call * [LottieCompositionResult.await], or invoke it like a function to get the nullable composition. * * [LottieCompositionResult] implements State<LottieComposition?> so if you don't need the full result class, * you can use this function like: * ``` * val compositionResult: LottieCompositionResult = lottieComposition(spec) * // or... * val composition: State<LottieComposition?> by lottieComposition(spec) * ``` * * The loaded composition will automatically load and set images that are embedded in the json as a base64 string * or will load them from assets if an imageAssetsFolder is supplied. * * @param spec The [LottieCompositionSpec] that defines which LottieComposition should be loaded. * @param imageAssetsFolder A subfolder in `src/main/assets` that contains the exported images * that this composition uses. DO NOT rename any images from your design tool. The * filenames must match the values that are in your json file. * @param fontAssetsFolder The default folder Lottie will look in to find font files. Fonts will be matched * based on the family name specified in the Lottie json file. * Defaults to "fonts/" so if "Helvetica" was in the Json file, Lottie will auto-match * fonts located at "src/main/assets/fonts/Helvetica.ttf". Missing fonts will be skipped * and should be set via fontRemapping or via dynamic properties. * @param fontFileExtension The default file extension for font files specified in the fontAssetsFolder or fontRemapping. * Defaults to ttf. * @param cacheKey Set a cache key for this composition. When set, subsequent calls to fetch this composition will * return directly from the cache instead of having to reload and parse the animation. Set this to * null to skip the cache. By default, this will automatically generate a cache key derived * from your [LottieCompositionSpec]. * @param onRetry An optional callback that will be called if loading the animation fails. * It is passed the failed count (the number of times it has failed) and the exception * from the previous attempt to load the composition. [onRetry] is a suspending function * so you can do things like add a backoff delay or await an internet connection before * retrying again. [rememberLottieRetrySignal] can be used to handle explicit retires. */ @Composable fun rememberLottieComposition( spec: LottieCompositionSpec, imageAssetsFolder: String? = null, fontAssetsFolder: String = "fonts/", fontFileExtension: String = ".ttf", cacheKey: String? = DefaultCacheKey, onRetry: suspend (failCount: Int, previousException: Throwable) -> Boolean = { _, _ -> false }, ): LottieCompositionResult { val context = LocalContext.current val result by remember(spec) { mutableStateOf(LottieCompositionResultImpl()) } // Warm the task cache. We can start the parsing task before the LaunchedEffect gets dispatched and run. // The LaunchedEffect task will join the task created inline here via LottieCompositionFactory's task cache. remember(spec, cacheKey) { lottieTask(context, spec, cacheKey, isWarmingCache = true) } LaunchedEffect(spec, cacheKey) { var exception: Throwable? = null var failedCount = 0 while (!result.isSuccess && (failedCount == 0 || onRetry(failedCount, exception!!))) { try { val composition = lottieComposition( context, spec, imageAssetsFolder.ensureTrailingSlash(), fontAssetsFolder.ensureTrailingSlash(), fontFileExtension.ensureLeadingPeriod(), cacheKey, ) result.complete(composition) } catch (e: Throwable) { exception = e failedCount++ } } if (!result.isComplete && exception != null) { result.completeExceptionally(exception) } } return result } private suspend fun lottieComposition( context: Context, spec: LottieCompositionSpec, imageAssetsFolder: String?, fontAssetsFolder: String?, fontFileExtension: String, cacheKey: String?, ): LottieComposition { val task = requireNotNull(lottieTask(context, spec, cacheKey, isWarmingCache = false)) { "Unable to create parsing task for $spec." } val composition = task.await() loadImagesFromAssets(context, composition, imageAssetsFolder) loadFontsFromAssets(context, composition, fontAssetsFolder, fontFileExtension) return composition } private fun lottieTask( context: Context, spec: LottieCompositionSpec, cacheKey: String?, isWarmingCache: Boolean, ): LottieTask<LottieComposition>? { return when (spec) { is LottieCompositionSpec.RawRes -> { if (cacheKey == DefaultCacheKey) { LottieCompositionFactory.fromRawRes(context, spec.resId) } else { LottieCompositionFactory.fromRawRes(context, spec.resId, cacheKey) } } is LottieCompositionSpec.Url -> { if (cacheKey == DefaultCacheKey) { LottieCompositionFactory.fromUrl(context, spec.url) } else { LottieCompositionFactory.fromUrl(context, spec.url, cacheKey) } } is LottieCompositionSpec.File -> { if (isWarmingCache) { // Warming the cache is done from the main thread so we can't // create the FileInputStream needed in this path. null } else { val fis = FileInputStream(spec.fileName) when { spec.fileName.endsWith("zip") -> LottieCompositionFactory.fromZipStream( ZipInputStream(fis), if (cacheKey == DefaultCacheKey) spec.fileName else cacheKey, ) else -> LottieCompositionFactory.fromJsonInputStream( fis, if (cacheKey == DefaultCacheKey) spec.fileName else cacheKey, ) } } } is LottieCompositionSpec.Asset -> { if (cacheKey == DefaultCacheKey) { LottieCompositionFactory.fromAsset(context, spec.assetName) } else { LottieCompositionFactory.fromAsset(context, spec.assetName, cacheKey) } } is LottieCompositionSpec.JsonString -> { val jsonStringCacheKey = if (cacheKey == DefaultCacheKey) spec.jsonString.hashCode().toString() else cacheKey LottieCompositionFactory.fromJsonString(spec.jsonString, jsonStringCacheKey) } is LottieCompositionSpec.ContentProvider -> { val inputStream = context.contentResolver.openInputStream(spec.uri) LottieCompositionFactory.fromJsonInputStream(inputStream, if (cacheKey == DefaultCacheKey) spec.uri.toString() else cacheKey) } } } private suspend fun <T> LottieTask<T>.await(): T = suspendCancellableCoroutine { cont -> addListener { c -> if (!cont.isCompleted) cont.resume(c) }.addFailureListener { e -> if (!cont.isCompleted) cont.resumeWithException(e) } } private suspend fun loadImagesFromAssets( context: Context, composition: LottieComposition, imageAssetsFolder: String?, ) { if (!composition.hasImages()) { return } withContext(Dispatchers.IO) { for (asset in composition.images.values) { maybeDecodeBase64Image(asset) maybeLoadImageFromAsset(context, asset, imageAssetsFolder) } } } private fun maybeLoadImageFromAsset( context: Context, asset: LottieImageAsset, imageAssetsFolder: String?, ) { if (asset.bitmap != null || imageAssetsFolder == null) return val filename = asset.fileName val inputStream = try { context.assets.open(imageAssetsFolder + filename) } catch (e: IOException) { Logger.warning("Unable to open asset.", e) return } try { val opts = BitmapFactory.Options() opts.inScaled = true opts.inDensity = 160 var bitmap = BitmapFactory.decodeStream(inputStream, null, opts) bitmap = Utils.resizeBitmapIfNeeded(bitmap, asset.width, asset.height) asset.bitmap = bitmap } catch (e: IllegalArgumentException) { Logger.warning("Unable to decode image.", e) } } private fun maybeDecodeBase64Image(asset: LottieImageAsset) { if (asset.bitmap != null) return val filename = asset.fileName if (filename.startsWith("data:") && filename.indexOf("base64,") > 0) { // Contents look like a base64 data URI, with the format data:image/png;base64,<data>. try { val data = Base64.decode(filename.substring(filename.indexOf(',') + 1), Base64.DEFAULT) val opts = BitmapFactory.Options() opts.inScaled = true opts.inDensity = 160 asset.bitmap = BitmapFactory.decodeByteArray(data, 0, data.size, opts) } catch (e: IllegalArgumentException) { Logger.warning("data URL did not have correct base64 format.", e) } } } private suspend fun loadFontsFromAssets( context: Context, composition: LottieComposition, fontAssetsFolder: String?, fontFileExtension: String, ) { if (composition.fonts.isEmpty()) return withContext(Dispatchers.IO) { for (font in composition.fonts.values) { maybeLoadTypefaceFromAssets(context, font, fontAssetsFolder, fontFileExtension) } } } private fun maybeLoadTypefaceFromAssets( context: Context, font: Font, fontAssetsFolder: String?, fontFileExtension: String, ) { val path = "$fontAssetsFolder${font.family}${fontFileExtension}" val typefaceWithDefaultStyle = try { Typeface.createFromAsset(context.assets, path) } catch (e: Exception) { Logger.error("Failed to find typeface in assets with path $path.", e) return } try { val typefaceWithStyle = typefaceForStyle(typefaceWithDefaultStyle, font.style) font.typeface = typefaceWithStyle } catch (e: Exception) { Logger.error("Failed to create ${font.family} typeface with style=${font.style}!", e) } } private fun typefaceForStyle(typeface: Typeface, style: String): Typeface? { val containsItalic = style.contains("Italic") val containsBold = style.contains("Bold") val styleInt = when { containsItalic && containsBold -> Typeface.BOLD_ITALIC containsItalic -> Typeface.ITALIC containsBold -> Typeface.BOLD else -> Typeface.NORMAL } return if (typeface.style == styleInt) typeface else Typeface.create(typeface, styleInt) } private fun String?.ensureTrailingSlash(): String? = when { isNullOrBlank() -> null endsWith('/') -> this else -> "$this/" } private fun String.ensureLeadingPeriod(): String = when { isBlank() -> this startsWith(".") -> this else -> ".$this" }
apache-2.0
c4d77a6065846b8938ed83f672c18875
40.160256
137
0.665758
4.856657
false
false
false
false
WilliamHester/Breadit-2
app/app/src/main/java/me/williamhester/reddit/apis/RedditHttpRequestExecutor.kt
1
5079
package me.williamhester.reddit.apis import android.util.Base64 import android.util.Log import com.google.gson.JsonElement import com.google.gson.JsonParser import io.realm.Realm import me.williamhester.reddit.BuildConfig import me.williamhester.reddit.convert.RedditGsonConverter import me.williamhester.reddit.models.Account import me.williamhester.reddit.models.managers.AccountManager import okhttp3.* import java.io.IOException /** An HTTP request that */ class RedditHttpRequestExecutor( private val httpClient: OkHttpClient, private val accountManager: AccountManager, private val jsonParser: JsonParser, private val redditGsonConverter: RedditGsonConverter ) { private fun getBaseUrl(accessToken: String?): String { return if (accessToken != null) OAUTH_URL else API_URL } private fun getHeaders(accessToken: String?): Headers { val builder = Headers.Builder() if (accessToken != null) { builder.add("Authorization", "bearer $accessToken") } else { val encoded = Base64.encodeToString("${BuildConfig.REDDIT_CLIENT_ID}:".toByteArray(), 0).trim() builder.add("Authorization", "Basic $encoded") } return builder.build() } internal fun execute(request: RedditHttpRequest, hasAttemptedRefresh: Boolean = false) { val urlBuilder = HttpUrl.parse(getBaseUrl(request.accessToken))!! .newBuilder() .addPathSegments(request.path) request.queries?.forEach { urlBuilder.addQueryParameter(it.key, it.value) } val method = if (request.params != null) POST else GET val requestBody: RequestBody? = if (method != GET) { val requestBodyBuilder = FormBody.Builder() request.params?.forEach { requestBodyBuilder.add(it.key, it.value) } requestBodyBuilder.build() } else { null } val httpRequest = Request.Builder() .url(urlBuilder.build()) .method(method, requestBody) .headers(getHeaders(request.accessToken)) .build() Log.d("RedditRequestFactory", httpRequest.toString()) httpClient.newCall(httpRequest).enqueue(JsonCallback(request, hasAttemptedRefresh)) } private fun refreshToken() { val urlBuilder = HttpUrl.parse(getBaseUrl(null))!! .newBuilder() .addPathSegments("api/v1/access_token") val params = mapOf( "grant_type" to "refresh_token", "refresh_token" to accountManager.refreshToken) val requestBody = FormBody.Builder() params.forEach { requestBody.add(it.key, it.value) } val request = Request.Builder() .url(urlBuilder.build()) .method(POST, requestBody.build()) .headers(getHeaders(null)) .build() Log.d("RedditRequestFactory", request.toString()) // This is the lazy way to do it, not returning anything. // TODO actually determine if something useful can be returned from this val response = httpClient.newCall(request).execute() if (response.isSuccessful) { Log.d("RedditRequestFactory", "Got a new access token!") val accessTokenJson = redditGsonConverter.toAccessTokenJson(jsonParser.parse(response.body()!!.charStream())) Realm.getDefaultInstance().executeTransaction { val account = it .where(Account::class.java) .equalTo("username", accountManager.username) .findFirst()!! account.accessToken = accessTokenJson.accessToken accountManager.setAccount(account) } } else { Log.d("RedditRequestFactory", "Failed to get a new access token. :(") } } private inner class JsonCallback( private val request: RedditHttpRequest, private val hasAttemptedRefresh: Boolean ) : Callback { override fun onFailure(call: Call, e: IOException) { request.callback.onFailure(e) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { if (!response.isSuccessful) { Log.d("RedditClient", response.toString()) } if (response.code() == 401 && !hasAttemptedRefresh && accountManager.isLoggedIn) { // TODO: Refresh the token Log.d("RedditRequestFactory", "Requesting new access token") refreshToken() execute(request.toBuilder().accessToken(accountManager.accessToken).build(), true) } else { try { Log.i("RedditHttpRequestFac", "Got response") val element = jsonParser.parse(response.body()!!.charStream()) request.callback.onResponse(element) } catch (e: Exception) { Log.d("RedditClient", "Request failed", e) request.callback.onFailure(e) } } response.close() } } interface JsonResponseCallback { fun onFailure(e: Exception) fun onResponse(element: JsonElement) } companion object { private const val POST = "POST" private const val GET = "GET" private const val API_URL = "https://api.reddit.com/" private const val OAUTH_URL = "https://oauth.reddit.com/" } }
apache-2.0
ccbeabb4906221edc3794ce5d4fce14b
32.635762
101
0.669423
4.498671
false
false
false
false
android/project-replicator
code/codegen/src/main/kotlin/com/android/gradle/replicator/codegen/PrettyPrintStream.kt
1
1566
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.android.gradle.replicator.codegen import java.io.PrintStream class PrettyPrintStream( private val printStream: PrintStream ): PrintStream(printStream) { private var indentationLevel = 0 fun addBlock(vararg strings: String) { strings.forEach(this::printlnIndented) indentationLevel++ } fun endBlock(x: String = "}") { indentationLevel-- printlnIndented(x) } fun printlnIndented(s: String) { val prettyPrintedString = s.replace("\n", "\n${indentationString()}") super.println(prettyPrintedString.prependIndent(indentationString())) } fun printIndented(s: String) { super.print(s.prependIndent(indentationString())) } private fun indentationString() = "\t".repeat(indentationLevel) fun prependIndent(): String = "\t".repeat(indentationLevel) fun prependIndent(s: String): String = "\t".repeat(indentationLevel) + s }
apache-2.0
9c9001c7b5b791be5ae233650ff19cc0
29.72549
77
0.701788
4.325967
false
false
false
false
binhonglee/LibrarySystem
src/main/kotlin/libsys/UserFactory.kt
1
5906
package libsys /* * Written by : Bin Hong Lee * Last edited : 7/4/2017 */ import org.json.JSONObject import org.json.JSONTokener import java.io.FileInputStream import java.io.PrintWriter import java.util.ArrayList /** * Handles all the User(s) */ class UserFactory { private val users = ArrayList<User>() private var id: Int = 0 private var userFilename: String? = null /** * @constructor Create a new empty UserFactory */ constructor() { id = 0 userFilename = "users.json" } /** * @constructor Create a new UserFactory and fill it with information from a JSON file * @param userFilename Name of the input JSON file */ constructor(userFilename: String) { try { val `in` = FileInputStream(userFilename) val obj = JSONObject(JSONTokener(`in`)) val ids = JSONObject.getNames(obj) for (id1 in ids) { val jsonUser = obj.getJSONObject(id1) val id = Integer.parseInt(id1) val name = jsonUser.getString("Name") val limit = jsonUser.getInt("Limit") val jsonBooks = jsonUser.getJSONArray("Books") val books = (0..jsonBooks.length() - 1).mapTo(ArrayList<Int>()) { Integer.parseInt(jsonBooks.get(it).toString()) } users.add(User(name, id, limit, books)) } `in`.close() id = getUser(users.size - 1).id + 1 } catch (ex: Exception) { println("Exception importing from json: " + ex.message) id = 0 } this.userFilename = userFilename } /** * Output the data into a JSON file replacing the input file (or if filename not given, "users.json") */ fun toJsonFile() { try { val out = PrintWriter(userFilename!!) val usersObj = JSONObject() for (user in users) { val userObj = JSONObject() userObj.put("Name", user.name) userObj.put("Limit", user.limit) userObj.put("Books", user.bookStatus()) usersObj.put(Integer.toString(user.id), userObj) } out.println(usersObj.toString(4)) out.close() } catch (e: Exception) { println("Invalid output filename") } } /** * Update the output filename for the object * @param userFilename The new filename */ fun setUserFileName(userFilename: String) { this.userFilename = userFilename } /** * Adds a new User into this class * @param name Name of the User * @param limit Limit of Book the User can borrow * * @return The new User that is just created */ fun newUser(name: String, limit: Int): User { val temp = User(name, id, limit) users.add(temp) id++ toJsonFile() return temp } /** * Looks for the User with the given name * @param name Name of the User to be found * * @return User with the given name */ fun getUser(name: String): User { users .asSequence() .filter { it.name == name } .forEach { return it } throw NullPointerException() } /** * Looks for a User with the given id * @param index id of the User to be found * * @return User with the given id */ fun getUser(index: Int): User { try { return search(index, 0, users.size - 1) } catch (e: Exception) { throw NullPointerException() } } /** * Recursive binary search through the array list for the User with the given id * @param index id of the User to be found * @param start Starting point to search * @param end Ending point to search * * @return User with the given id */ private fun search(index: Int, start: Int, end: Int): User { if (start == end && users[start].id == index) { return users[start] } if (start >= end) { throw NullPointerException() } val currentId = (start + end) / 2 if (users[currentId].id == index) { return users[currentId] } else if (users[currentId].id > index) { return search(index, start, currentId - 1) } else { return search(index, currentId + 1, end) } } /** * Deletes the given User from the class (if found) * @param user User to be deleted * * @return if User deletion is successful */ fun deleteUser(user: User): Boolean { return users.remove(user) } /** * Deletes the User with the given id from the class (if found) * @param id id of the User to be deleted * * @return if User deletion is successful */ fun deleteUser(id: Int): Boolean { try { return users.remove(getUser(id)) } catch (e: Exception) { return false } } /** * Replacing a User in the array list with a new User * @param oldUser User to be replaced * @param newUser User replacing it */ fun update(oldUser: User, newUser: User) { for (i in users.indices) { val temp = users[i] if (temp.id == oldUser.id) { users[i] = newUser } } toJsonFile() } }
mit
5f68b3d110f6e70269b94e2c0e5def20
23.204918
105
0.507958
4.404176
false
false
false
false
mdanielwork/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUClass.kt
6
4410
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.* import org.jetbrains.uast.* import org.jetbrains.uast.java.internal.JavaUElementWithComments abstract class AbstractJavaUClass(givenParent: UElement?) : JavaAbstractUElement( givenParent), UClassTypeSpecific, JavaUElementWithComments, UAnchorOwner, UDeclarationEx { abstract override val javaPsi: PsiClass @Suppress("unused") // Used in Kotlin, to be removed in 2018.1 @Deprecated("use AbstractJavaUClass(givenParent)", ReplaceWith("AbstractJavaUClass(givenParent)")) constructor() : this(null) override val uastDeclarations: MutableList<UDeclaration> by lz { mutableListOf<UDeclaration>().apply { addAll(fields) addAll(initializers) addAll(methods) addAll(innerClasses) } } protected fun createJavaUTypeReferenceExpression(referenceElement: PsiJavaCodeReferenceElement): LazyJavaUTypeReferenceExpression = LazyJavaUTypeReferenceExpression(referenceElement, this) { JavaPsiFacade.getElementFactory(referenceElement.project).createType(referenceElement) } override val uastSuperTypes: List<UTypeReferenceExpression> by lazy { psi.extendsList?.referenceElements?.map { createJavaUTypeReferenceExpression(it) }.orEmpty() + psi.implementsList?.referenceElements?.map { createJavaUTypeReferenceExpression(it) }.orEmpty() } override val uastAnchor: UIdentifier? get() = UIdentifier(psi.nameIdentifier, this) override val annotations: List<UAnnotation> get() = psi.annotations.map { JavaUAnnotation(it, this) } override fun equals(other: Any?): Boolean = other is AbstractJavaUClass && psi == other.psi override fun hashCode(): Int = psi.hashCode() } class JavaUClass private constructor(psi: PsiClass, val givenParent: UElement?) : AbstractJavaUClass(givenParent), UAnchorOwner, PsiClass by psi { override val psi: PsiClass get() = javaPsi override val javaPsi: PsiClass = unwrap<UClass, PsiClass>(psi) override fun getSuperClass(): UClass? = super.getSuperClass() override fun getFields(): Array<UField> = super.getFields() override fun getInitializers(): Array<UClassInitializer> = super.getInitializers() override fun getMethods(): Array<UMethod> = super.getMethods() override fun getInnerClasses(): Array<UClass> = super.getInnerClasses() companion object { fun create(psi: PsiClass, containingElement: UElement?): UClass { return if (psi is PsiAnonymousClass) JavaUAnonymousClass(psi, containingElement) else JavaUClass(psi, containingElement) } } } class JavaUAnonymousClass( psi: PsiAnonymousClass, uastParent: UElement? ) : AbstractJavaUClass(uastParent), UAnonymousClass, UAnchorOwner, PsiAnonymousClass by psi { override val psi: PsiAnonymousClass get() = javaPsi override val javaPsi: PsiAnonymousClass = unwrap<UAnonymousClass, PsiAnonymousClass>(psi) override val uastSuperTypes: List<UTypeReferenceExpression> by lazy { listOf(createJavaUTypeReferenceExpression(psi.baseClassReference)) + super.uastSuperTypes } override val uastAnchor: UIdentifier? by lazy { when (javaPsi) { is PsiEnumConstantInitializer -> (javaPsi.parent as? PsiEnumConstant)?.let { UIdentifier(it.nameIdentifier, this) } else -> UIdentifier(psi.baseClassReference.referenceNameElement, this) } } override fun getSuperClass(): UClass? = super<AbstractJavaUClass>.getSuperClass() override fun getFields(): Array<UField> = super<AbstractJavaUClass>.getFields() override fun getInitializers(): Array<UClassInitializer> = super<AbstractJavaUClass>.getInitializers() override fun getMethods(): Array<UMethod> = super<AbstractJavaUClass>.getMethods() override fun getInnerClasses(): Array<UClass> = super<AbstractJavaUClass>.getInnerClasses() }
apache-2.0
1d13c999bfd7ed4c017aadf5d31922b4
38.72973
133
0.758957
4.9
false
false
false
false
Apolline-Lille/apolline-android
app/src/main/java/science/apolline/service/database/AppDatabase.kt
1
2189
package science.apolline.service.database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.arch.persistence.room.TypeConverters import android.arch.persistence.room.Database import android.content.Context import science.apolline.models.Device import android.arch.persistence.db.SupportSQLiteDatabase import android.arch.persistence.room.migration.Migration import science.apolline.models.TimestampSync /** * Created by sparow on 11/5/17. */ @Database(entities = [(Device::class), (TimestampSync::class)], version = 3, exportSchema = true) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { abstract fun sensorDao(): SensorDao abstract fun timestampSyncDao() : TimestampSyncDao companion object { var TEST_MODE = false private const val databaseName = "sensors-database" private var db: AppDatabase? = null fun getInstance(context: Context): AppDatabase { if (db == null) db = if (TEST_MODE) { Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) .allowMainThreadQueries() .fallbackToDestructiveMigration() .build() } else { Room.databaseBuilder(context, AppDatabase::class.java, databaseName) .addMigrations(MIGRATION_1_2, MIGRATION_2_3) .build() } return db!! } private fun close() { db?.close() } private val MIGRATION_1_2: Migration = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { // Since we didn't alter the table, there's nothing else to do here. } } private val MIGRATION_2_3 = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE TimestampSync (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date INTEGER NOT NULL);") } } } }
gpl-3.0
17e1d300390d0e7bbb82405f271e8b6e
34.901639
134
0.620831
4.963719
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/ui/base/detail/BaseDetailPresenter.kt
1
4667
package com.ashish.movieguide.ui.base.detail import com.ashish.movieguide.R import com.ashish.movieguide.data.models.CreditResults import com.ashish.movieguide.data.models.FullDetailContent import com.ashish.movieguide.data.models.ImageItem import com.ashish.movieguide.ui.base.mvp.RxPresenter import com.ashish.movieguide.utils.AuthException import com.ashish.movieguide.utils.Logger import com.ashish.movieguide.utils.Utils import com.ashish.movieguide.utils.extensions.getBackdropUrl import com.ashish.movieguide.utils.extensions.getPosterUrl import com.ashish.movieguide.utils.extensions.isNotNullOrEmpty import com.ashish.movieguide.utils.schedulers.BaseSchedulerProvider import io.reactivex.Single import java.io.IOException import java.util.ArrayList /** * Created by Ashish on Jan 03. */ abstract class BaseDetailPresenter<I, V : BaseDetailView<I>>( schedulerProvider: BaseSchedulerProvider ) : RxPresenter<V>(schedulerProvider) { protected var fullDetailContent: FullDetailContent<I>? = null fun loadDetailContent(id: Long?) { if (fullDetailContent != null) { showDetailContent(fullDetailContent!!) } else { loadFreshData(id) } } private fun loadFreshData(id: Long?) { if (Utils.isOnline()) { if (id != null) { getView()?.showProgress() addDisposable(getDetailContent(id) .doOnSuccess { fullDetailContent = it } .observeOn(schedulerProvider.ui()) .subscribe({ showDetailContent(it) }, { onLoadDetailError(it, getErrorMessageId()) })) } } else { getView()?.apply { showToastMessage(R.string.error_no_internet) finishActivity() } } } abstract fun getDetailContent(id: Long): Single<FullDetailContent<I>> protected open fun showDetailContent(fullDetailContent: FullDetailContent<I>) { getView()?.apply { val contentList = getContentList(fullDetailContent) showDetailContentList(contentList) val detailContent = fullDetailContent.detailContent if (detailContent != null) { showDetailContent(detailContent) showAllImages(detailContent) showCredits(getCredits(detailContent)) } fullDetailContent.omdbDetail?.let { showOMDbDetail(it) } hideProgress() } } private fun showAllImages(detailContent: I) { val imageUrlList = ArrayList<String>() addImages(imageUrlList, getPosterImages(detailContent), String?::getPosterUrl) addImages(imageUrlList, getBackdropImages(detailContent), String?::getBackdropUrl) if (imageUrlList.isNotEmpty()) { getView()?.showImageList(imageUrlList) } } private fun addImages(urlList: ArrayList<String>, imageItemList: List<ImageItem>?, getImageUrl: (String?) -> String?) { if (imageItemList.isNotNullOrEmpty()) { val posterImageUrlList = imageItemList!! .map { getImageUrl(it.filePath) } .filterNotNull() .toList() urlList.addAll(posterImageUrlList) } } abstract fun getContentList(fullDetailContent: FullDetailContent<I>): List<String> abstract fun getBackdropImages(detailContent: I): List<ImageItem>? abstract fun getPosterImages(detailContent: I): List<ImageItem>? abstract fun getCredits(detailContent: I): CreditResults? private fun showCredits(creditResults: CreditResults?) { getView()?.apply { showItemList(creditResults?.cast) { showCastList(it) } showItemList(creditResults?.crew) { showCrewList(it) } } } private fun onLoadDetailError(t: Throwable, messageId: Int) { Logger.e(t) getView()?.apply { showErrorToast(t, messageId) finishActivity() } } abstract fun getErrorMessageId(): Int private fun showErrorToast(t: Throwable, messageId: Int) { getView()?.apply { if (t is IOException) { showToastMessage(R.string.error_no_internet) } else if (t is AuthException) { showToastMessage(R.string.error_not_logged_in) } else { showToastMessage(messageId) } } } protected fun <T> showItemList(itemList: List<T>?, showData: (List<T>) -> Unit) { if (itemList != null && itemList.isNotEmpty()) showData(itemList) } }
apache-2.0
e056746d76a67079c1ac9865c8a0c962
34.097744
110
0.637026
4.776868
false
false
false
false
fabianonline/telegram_backup
src/main/kotlin/de/fabianonline/telegram_backup/exporter/CSVLinkExporter.kt
1
5195
/* Telegram_Backup * Copyright (C) 2016 Fabian Schlenz * * 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.fabianonline.telegram_backup.exporter import java.io.File import java.io.PrintWriter import java.io.OutputStreamWriter import java.io.FileOutputStream import java.nio.charset.Charset import java.io.FileWriter import java.io.IOException import java.io.FileNotFoundException import java.net.URL import org.apache.commons.io.FileUtils import java.util.LinkedList import java.util.HashMap import java.time.LocalDate import java.time.LocalTime import java.time.LocalDateTime import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.sql.Time import java.text.SimpleDateFormat import com.github.mustachejava.DefaultMustacheFactory import com.github.mustachejava.Mustache import com.github.mustachejava.MustacheFactory import de.fabianonline.telegram_backup.* import com.github.badoualy.telegram.tl.api.* import com.google.gson.* import com.github.salomonbrys.kotson.* import org.slf4j.Logger import org.slf4j.LoggerFactory class CSVLinkExporter(val db: Database, val file_base: String, val settings: Settings) { val logger = LoggerFactory.getLogger(CSVLinkExporter::class.java) val mustache = DefaultMustacheFactory().compile("templates/csv/links.csv") val dialogs = db.getListOfDialogsForExport() val chats = db.getListOfChatsForExport() val datetime_format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val base = file_base + "files" + File.separatorChar val invalid_entity_index = "[INVALID ENTITY INDEX]" fun export() { val today = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT) val timezone = ZoneOffset.systemDefault() val days = if (settings.max_file_age==-1) 7 else settings.max_file_age // Create base dir logger.debug("Creating base dir") File(base).mkdirs() if (days > 0) { for (dayOffset in days downTo 1) { val day = today.minusDays(dayOffset.toLong()) val start = day.toEpochSecond(timezone.rules.getOffset(day)) val end = start + 24 * 60 * 60 val filename = base + "links.${day.format(DateTimeFormatter.ISO_LOCAL_DATE)}.csv" if (!File(file_base + filename).exists()) { logger.debug("Range: {} to {}", start, end) println("Processing messages for ${day}...") exportToFile(start, end, filename) } } } else { println("Processing all messages...") exportToFile(0, Long.MAX_VALUE, base + "links.all.csv") } } fun exportToFile(start: Long, end: Long, filename: String) { //val messages: List<Map<String, Any>> = db.getMessagesForCSVExport(start, end) val list = mutableListOf<Map<String, String?>>() val parser = JsonParser() //logger.debug("Got {} messages", messages.size) db.getMessagesForCSVExport(start, end) {data: HashMap<String, Any> -> //val msg: TLMessage = data.get("message_object") as TLMessage val json = parser.parse(data.get("json") as String).obj if (!json.contains("entities")) return@getMessagesForCSVExport val urls: List<String>? = json["entities"].array.filter{it.obj.isA("messageEntityTextUrl") || it.obj.isA("messageEntityUrl")}?.map { var url: String try { url = if (it.obj.contains("url")) it["url"].string else json["message"].string.substring(it["offset"].int, it["offset"].int + it["length"].int) if (!url.toLowerCase().startsWith("http:") && !url.toLowerCase().startsWith("https://")) url = "http://${url}" } catch (e: StringIndexOutOfBoundsException) { url = invalid_entity_index } url } if (urls != null) for(url in urls) { val scope = HashMap<String, String?>() scope.put("url", url) if (url == invalid_entity_index) { scope.put("host", invalid_entity_index) } else { scope.put("host", URL(url).getHost()) } val timestamp = data["time"] as Time scope.put("time", datetime_format.format(timestamp)) scope.put("username", if (data["user_username"]!=null) data["user_username"] as String else null) if (data["source_type"]=="dialog") { scope.put("chat_name", "@" + (dialogs.firstOrNull{it.id==data["source_id"]}?.username ?: "")) } else { scope.put("chat_name", chats.firstOrNull{it.id==data["source_id"]}?.name) } list.add(scope) } } val writer = getWriter(filename) mustache.execute(writer, mapOf("links" to list)) writer.close() } private fun getWriter(filename: String): OutputStreamWriter { logger.trace("Creating writer for file {}", filename.anonymize()) return OutputStreamWriter(FileOutputStream(filename), Charset.forName("UTF-8").newEncoder()) } }
gpl-3.0
8246df75aa2ddedfd142c4218260ca1b
36.374101
148
0.711068
3.582759
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/gradle/GradleTaskIR.kt
6
2742
// 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.tools.projectWizard.ir.buildsystem.gradle import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.FreeIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.render import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter interface GradleTaskAccessIR : GradleIR data class GradleNamedTaskAccessIR( val name: String, val taskClass: String? = null ) : GradleTaskAccessIR { override fun GradlePrinter.renderGradle() { when (dsl) { GradlePrinter.GradleDsl.GROOVY -> { +"tasks.named('$name')" } GradlePrinter.GradleDsl.KOTLIN -> { +"tasks.named" taskClass?.let { +"<$it>" } +"(${name.quotified})" } } } } data class GradleByClassTasksAccessIR( @NonNls val taskClass: String ) : GradleTaskAccessIR { override fun GradlePrinter.renderGradle() { when (dsl) { GradlePrinter.GradleDsl.GROOVY -> { +"tasks.withType($taskClass)" } GradlePrinter.GradleDsl.KOTLIN -> { +"tasks.withType<$taskClass>" } } } } data class GradleByClassTasksCreateIR( val taskName: String, val taskClass: String ) : GradleTaskAccessIR { override fun GradlePrinter.renderGradle() { when (dsl) { GradlePrinter.GradleDsl.KOTLIN -> { +"val $taskName by tasks.creating($taskClass::class)" } GradlePrinter.GradleDsl.GROOVY -> { +"task($taskName, type: $taskClass)" } } } } data class GradleConfigureTaskIR( val taskAccess: GradleTaskAccessIR, val dependsOn: List<BuildSystemIR> = emptyList(), val irs: List<BuildSystemIR> = emptyList() ) : GradleIR, FreeIR { constructor( taskAccess: GradleTaskAccessIR, dependsOn: List<BuildSystemIR> = emptyList(), createIrs: IRsListBuilderFunction ) : this(taskAccess, dependsOn, createIrs.build()) override fun GradlePrinter.renderGradle() { taskAccess.render(this) +" " inBrackets { if (dependsOn.isNotEmpty()) { indent() call("dependsOn", forceBrackets = true) { dependsOn.list { it.render(this) } } nl() } irs.listNl() } } }
apache-2.0
d7c8dfd7f3981589bbc9470a607b9753
30.517241
158
0.60795
4.577629
false
false
false
false
cdietze/klay
src/main/kotlin/klay/core/json/JsonArray.kt
1
4118
package klay.core.json import klay.core.Json import klay.core.Json.TypedArray import kotlin.reflect.KClass /** * Extends an [ArrayList] with helper methods to determine the underlying JSON type of the list element. */ internal class JsonArray : Json.Array { private val list: ArrayList<Any?> /** * Creates an empty [JsonArray] with the default capacity. */ constructor() { list = ArrayList<Any?>() } /** * Creates an empty [JsonArray] from the given collection of objects. */ constructor(collection: Collection<Any?>) { list = ArrayList(collection) } override fun add(value: Any?): JsonArray { JsonImpl.checkJsonType(value) list.add(value) return this } override fun add(index: Int, value: Any?): JsonArray { JsonImpl.checkJsonType(value) // TODO(mmastrac): Use an array rather than ArrayList to make this more efficient while (list.size < index) list.add(null) list.add(index, value) return this } override fun getArray(index: Int): Json.Array? { return get(index) as? Json.Array? } override fun <T : Any> getArray(index: Int, jsonType: KClass<T>): TypedArray<T>? { val array = getArray(index) return if (array == null) null else JsonTypedArray(array, jsonType) } override fun getBoolean(index: Int): Boolean? { return get(index) as? Boolean? } override fun getDouble(index: Int): Double? { return (get(index) as? Number?)?.toDouble() } override fun getFloat(index: Int): Float? { return (get(index) as? Number?)?.toFloat() } override fun getInt(index: Int): Int? { return (get(index) as? Number?)?.toInt() } override fun getLong(index: Int): Long? { return (get(index) as? Number?)?.toLong() } override fun getObject(index: Int): Json.Object? { return get(index) as? Json.Object? } override fun getString(index: Int): String? { return get(index) as? String? } override fun isArray(index: Int): Boolean { return get(index) is Json.Array } override fun isBoolean(index: Int): Boolean { return get(index) is Boolean } override fun isNull(index: Int): Boolean { return get(index) == null } override fun isNumber(index: Int): Boolean { return get(index) is Number } override fun isString(index: Int): Boolean { return get(index) is String } override fun isObject(index: Int): Boolean { return get(index) is Json.Object } override fun length(): Int { return list.size } override fun remove(index: Int): JsonArray { if (index < 0 || index >= list.size) return this list.removeAt(index) return this } override fun set(index: Int, value: Any?): JsonArray { JsonImpl.checkJsonType(value) // TODO(mmastrac): Use an array rather than ArrayList to make this more efficient while (list.size <= index) list.add(null) list[index] = value return this } override fun toString(): String { return list.toString() } override fun <T : JsonSink<T>> write(sink: JsonSink<T>): JsonSink<T> { for (i in list.indices) sink.value(list[i]) return sink } /** * Returns the underlying object at the given index, or null if it does not exist or is out of * bounds (to match the HTML implementation). */ operator fun get(key: Int): Any? { return if (key >= 0 && key < list.size) list[key] else null } companion object { /** * Creates a [JsonArray] from an array of contents. */ fun from(vararg contents: Any): JsonArray { return JsonArray(contents.toList()) } /** * Creates a [JsonBuilder] for a [JsonArray]. */ fun builder(): JsonBuilder<JsonArray> { return JsonBuilder(JsonArray()) } } }
apache-2.0
cb8624ee663323875083b0ad8f97fa2c
25.063291
104
0.590821
4.214944
false
false
false
false
android/privacy-codelab
PhotoLog_start/src/main/java/com/example/photolog_start/ui/theme/Color.kt
1
911
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.photolog_start.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
apache-2.0
8b2cb4f20e78bb385c0b2e2401636d9c
32.777778
75
0.758507
3.544747
false
false
false
false
ediTLJ/novelty
app/src/main/java/ro/edi/novelty/ui/FeedFragment.kt
1
10264
/* * Copyright 2019 Eduard Scarlat * * 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 ro.edi.novelty.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.google.android.material.tabs.TabLayout import ro.edi.novelty.R import ro.edi.novelty.databinding.FragmentFeedBinding import ro.edi.novelty.ui.adapter.NewsAdapter import ro.edi.novelty.ui.viewmodel.NewsViewModel import ro.edi.util.applyWindowInsetsPadding import ro.edi.util.getColorRes import timber.log.Timber.Forest.i as logi class FeedFragment : Fragment() { companion object { const val ARG_FEED_ID = "ro.edi.novelty.ui.feed.arg_feed_id" fun newInstance(feedId: Int) = FeedFragment().apply { arguments = Bundle().apply { putInt(ARG_FEED_ID, feedId) } } } private var newestDate = 0L private lateinit var newsModel: NewsViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) newsModel = ViewModelProvider(viewModelStore, factory)[NewsViewModel::class.java] } override fun onPause() { val v = view ?: return // val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(v.context) // val newestDate = sharedPrefs.getLong(KEY_NEWEST_SEEN_DATE, 0) val rvNews = v.findViewById<RecyclerView>(R.id.news) val llManager = rvNews.layoutManager as LinearLayoutManager val pos = llManager.findFirstVisibleItemPosition() val date = newsModel.getNews(pos)?.pubDate ?: 0 // val sharedPrefsEditor = sharedPrefs.edit() if (date > newestDate) { newestDate = date // FIXME if starred feed, put newestDate to sharedPrefs? // logi("saving newest seen date $date") // sharedPrefsEditor // .putLong(KEY_NEWEST_SEEN_DATE, date) // .apply() } super.onPause() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = DataBindingUtil.inflate<FragmentFeedBinding>( inflater, R.layout.fragment_feed, container, false ) binding.lifecycleOwner = viewLifecycleOwner return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val vRefresh = view.findViewById<SwipeRefreshLayout>(R.id.swipe_refresh) vRefresh.apply { setColorSchemeResources(getColorRes(view.context, R.attr.colorPrimaryVariant)) setOnRefreshListener { newsModel.refresh(arguments?.getInt(ARG_FEED_ID, 0) ?: 0) } } val rvNews = view.findViewById<RecyclerView>(R.id.news) rvNews.apply { applyWindowInsetsPadding( applyLeft = true, applyTop = false, applyRight = true, applyBottom = true ) isNestedScrollingEnabled = true clearOnScrollListeners() addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dy < 0) { val llManager = layoutManager as LinearLayoutManager val pos = llManager.findFirstVisibleItemPosition() val date = (recyclerView.adapter as NewsAdapter).currentList[pos]?.pubDate ?: 0 // logi("test pos: $pos") // logi("test date: $date") // logi("test newest date: $newestDate") // FIXME if starred feed, get newestDate from sharedPrefs, if it's newer // newestDate = sharedPrefs.getLong(KEY_NEWEST_SEEN_DATE, 0) if (date >= newestDate) { newestDate = date // FIXME if starred feed, put newestDate to sharedPrefs? // sharedPrefs // .edit() // .putLong(KEY_NEWEST_SEEN_DATE, date) // .apply() } if (llManager.findFirstVisibleItemPosition() == 0) { clearTabBadge() } else { if (date > newestDate) { updateTabBadge(-1) } } } } }) // listView.setVelocityScale(2.0f) setHasFixedSize(true) setItemViewCacheSize(20) adapter = NewsAdapter(activity, newsModel).apply { setHasStableIds(true) } } val vEmpty = view.findViewById<View>(R.id.empty) newsModel.isFetching.observe(viewLifecycleOwner) { isFetching -> logi("isFetching changed: %b", isFetching) if (isFetching) { vRefresh.isRefreshing = true } else { vRefresh.isRefreshing = false if (newsModel.news.value.isNullOrEmpty()) { logi("no news => show empty message") vEmpty.visibility = View.VISIBLE rvNews.visibility = View.GONE } else { logi("we have news! => show them") vEmpty.visibility = View.GONE rvNews.visibility = View.VISIBLE } } } newsModel.news.observe(viewLifecycleOwner) { newsList -> logi("news changed: %d news", newsList.size) if (newsList.isEmpty()) { vEmpty.visibility = if (newsModel.isFetching.value == false) View.VISIBLE else View.GONE rvNews.visibility = View.GONE } else { vEmpty.visibility = View.GONE rvNews.visibility = View.VISIBLE val rvAdapter = rvNews.adapter as NewsAdapter val llManager = rvNews.layoutManager as LinearLayoutManager val pos = llManager.findFirstVisibleItemPosition() val date = if (pos < 0) 0 else rvAdapter.currentList[pos]?.pubDate ?: 0 // FIXME if starred feed, get newestDate from sharedPrefs, if it's newer // newestDate = sharedPrefs.getLong(KEY_NEWEST_SEEN_DATE, 0) if (date >= newestDate) { newestDate = date } // logi("newestDate: $newestDate") val prevNewsCount = rvAdapter.itemCount logi("prevNewsCount: $prevNewsCount") rvAdapter.submitList(newsList) // if (prevNewsCount == 0) { // // } if (newsList[0].pubDate > newestDate) { val posNew = newsList.indexOfFirst { it.pubDate <= newestDate } logi("pos: $posNew") setTabBadge(posNew) } } } } @Suppress("SameParameterValue") private fun updateTabBadge(offset: Int) { // logi("test offset: $offset") val tab = findTabByTag(newsModel.getNews(0)?.feedId) ?: return val badge = tab.badge ?: return badge.number += offset logi("tab badge set to ${badge.number}") } private fun setTabBadge(count: Int) { val tab = findTabByTag(newsModel.getNews(0)?.feedId) ?: return if (count <= 0) { tab.removeBadge() logi("tab badge cleared") return } val badge = tab.orCreateBadge badge.number = count logi("tab badge set to $count") } private fun clearTabBadge() { val tab = findTabByTag(newsModel.getNews(0)?.feedId) ?: return tab.removeBadge() // or hide it? logi("tab badge removed") } private fun findTabByTag(feedId: Int?): TabLayout.Tab? { feedId ?: return null val tabs = activity?.findViewById<TabLayout>(R.id.tabs) ?: return null for (idx in 2 until tabs.tabCount) { val tab = tabs.getTabAt(idx) ?: continue if (tab.tag == feedId) { return tab } } return null } private val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return NewsViewModel( (activity as AppCompatActivity).application, NewsViewModel.TYPE_FEED, arguments?.getInt(ARG_FEED_ID, 0) ?: 0 ) as T } } }
apache-2.0
6c8ddd91e4bd9f96e00a409ca5baf935
33.4
96
0.547642
4.989791
false
false
false
false
googlecodelabs/tv-recommendations-kotlin
step_final/src/main/java/com/android/tv/classics/workers/TvMediaSynchronizer.kt
3
7977
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.classics.workers import android.content.Context import android.net.Uri import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters import com.android.tv.classics.R import com.android.tv.classics.models.TvMediaBackground import com.android.tv.classics.utils.TvLauncherUtils import com.android.tv.classics.models.TvMediaDatabase import com.android.tv.classics.models.TvMediaMetadata import com.android.tv.classics.models.TvMediaCollection import org.json.JSONArray import org.json.JSONObject import java.nio.charset.StandardCharsets /** Maps a JSONArray of strings */ private fun <T>JSONArray.mapString(transform: (String) -> T): List<T> = (0 until length()).map { transform(getString(it)) } /** Maps a JSONArray of objects */ private fun <T>JSONArray.mapObject(transform: (JSONObject) -> T): List<T> = (0 until length()).map { transform(getJSONObject(it)) } /** Worker that parses metadata from our assets folder and synchronizes the database */ class TvMediaSynchronizer(private val context: Context, params: WorkerParameters) : Worker(context, params) { /** Helper data class used to pass results around functions */ private data class FeedParseResult( val metadata: List<TvMediaMetadata>, val collections: List<TvMediaCollection>, val backgrounds: List<TvMediaBackground>) override fun doWork(): Result = try { synchronize(context) Result.success() } catch (exc: Exception) { Result.failure() } companion object { private val TAG = TvMediaSynchronizer::class.java.simpleName /** Fetches the metadata feed from our assets folder and parses its metadata */ private fun parseMediaFeed(context: Context): FeedParseResult { // Reads JSON input into a JSONArray // We are using a local file, in your app you most likely will be using a remote URL val stream = context.resources.assets.open("media-feed.json") val data = JSONObject( String(stream.readBytes(), StandardCharsets.UTF_8)) // Initializes an empty list to populate with metadata metadata val metadatas: MutableList<TvMediaMetadata> = mutableListOf() // Traverses the feed and maps each collection val feed = data.getJSONArray("feed") val collections = feed.mapObject { obj -> val collection = TvMediaCollection( id = obj.getString("id"), title = obj.getString("title"), description = obj.getString("description"), artUri = obj.getString("image")?.let { Uri.parse(it) }) // Traverses the collection and map each content item metadata val subItemsMetadata = obj.getJSONArray("items").mapObject { subItem -> TvMediaMetadata( collectionId = collection.id, id = subItem.getString("id"), title = subItem.getString("title"), ratings = subItem.optJSONArray("ratings")?.mapString { x -> x }, contentUri = subItem.getString("url")?.let { Uri.parse(it) }!!, playbackDurationMillis = subItem.getLong("duration") * 1000, year = subItem.getInt("year"), author = subItem.getString("director"), description = subItem.getString("description"), artUri = subItem.getString("art")?.let { Uri.parse(it) }) } // Adds all the subitems to the flat list metadatas.addAll(subItemsMetadata) // Returns parsed collection collection } // Gets background images from metadata feed as well val bgArray = data.getJSONArray("backgrounds") val backgrounds = (0 until bgArray.length()).map { idx -> TvMediaBackground("$idx", Uri.parse(bgArray.getString(idx))) } return FeedParseResult(metadatas, collections, backgrounds) } /** Parses metadata from our assets folder and synchronizes the database */ @Synchronized fun synchronize(context: Context) { Log.d(TAG, "Starting synchronization work") val database = TvMediaDatabase.getInstance(context) val feed = parseMediaFeed(context) // Gets a list of the metadata IDs for comparisons val metadataIdList = feed.metadata.map { it.id } // Deletes items in our database that have been deleted from the metadata feed // NOTE: It's important to keep the things added to the TV launcher in sync database.metadata().findAll() .filter { !metadataIdList.contains(it.id) } .forEach { database.metadata().delete(it) // Removes programs no longer present from TV launcher TvLauncherUtils.removeProgram(context, it) // Removes programs no longer present from Watch Next row TvLauncherUtils.removeFromWatchNext(context, it) } database.collections().findAll() .filter { !feed.collections.contains(it) } .forEach { database.collections().delete(it) // Removes channels from TV launcher TvLauncherUtils.removeChannel(context, it) } database.backgrounds().findAll() .filter { !feed.backgrounds.contains(it) } .forEach { database.backgrounds().delete(it) } // Upon insert, we will replace all metadata already added so we can update titles, // images, descriptions, etc. Note that we overloaded the `equals` function in our data // class to avoid replacing metadata which has an updated state such as playback // position. database.metadata().insert(*feed.metadata.toTypedArray()) database.collections().insert(*feed.collections.toTypedArray()) database.backgrounds().insert(*feed.backgrounds.toTypedArray()) // Inserts the first collection as the "default" channel val defaultChannelTitle = context.getString(R.string.default_channel_name) val defaultChannelArtUri = TvLauncherUtils.resourceUri( context.resources, R.mipmap.ic_channel_logo) val defaultChannelCollection = feed.collections.first().copy( title = defaultChannelTitle, artUri = defaultChannelArtUri) val defaultChannelUri = TvLauncherUtils.upsertChannel( context, defaultChannelCollection, database.metadata().findByCollection(defaultChannelCollection.id)) // Inserts the rest of the collections as channels that user can add to home screen // TODO: step 5 add more channels. feed.collections.subList(1, feed.collections.size).forEach { TvLauncherUtils.upsertChannel( context, it, database.metadata().findByCollection(it.id)) } // TODO: End of step 5. } } }
apache-2.0
9df2a9fe461a209dc8dce54acd064e26
45.377907
99
0.624295
4.963908
false
false
false
false
PaulWoitaschek/MaterialAudiobookPlayer
data/src/test/java/de/ph1b/audiobook/data/ChapterFactory.kt
1
596
package de.ph1b.audiobook.data import androidx.collection.SparseArrayCompat import de.ph1b.audiobook.common.sparseArray.emptySparseArray import java.io.File import java.util.UUID internal object ChapterFactory { fun create( file: String = "First.mp3", parent: String = "/root/", duration: Int = 100, lastModified: Long = 12345L, bookId: UUID, marks: SparseArrayCompat<String> = emptySparseArray() ) = Chapter( file = File(parent, file), name = file, duration = duration, fileLastModified = lastModified, marks = marks, bookId = bookId ) }
lgpl-3.0
fb5a02ecd1411726dabb9a79ed6080a0
22.84
60
0.696309
3.87013
false
false
false
false
JetBrains/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineMergingModel.kt
1
4679
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.timeline import com.intellij.openapi.application.ApplicationManager import com.intellij.util.text.DateFormatUtil import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestCommitShort import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineEvent import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem import javax.swing.AbstractListModel import kotlin.math.max class GHPRTimelineMergingModel : AbstractListModel<GHPRTimelineItem>() { private val list = mutableListOf<GHPRTimelineItem>() override fun getElementAt(index: Int): GHPRTimelineItem = list[index] override fun getSize(): Int = list.size fun add(items: List<GHPRTimelineItem>) { var lastListIdx = list.lastIndex var lastItem: GHPRTimelineItem? = list.lastOrNull() if (lastItem != null) { list.removeAt(lastListIdx) fireIntervalRemoved(this, lastListIdx, lastListIdx) lastListIdx-- } var added = false val hideUnknown = ApplicationManager.getApplication().let { !it.isInternal && !it.isEAP } for (item in items) { if (item is GHPRTimelineItem.Unknown && (hideUnknown || item.__typename in GHPRTimelineItem.IGNORED_TYPES)) continue val merged = mergeIfPossible(lastItem, item) if (merged != null) { lastItem = merged } else { if (lastItem != null && !isCollapsedMerge(lastItem)) { list.add(lastItem) added = true } lastItem = item } } if (lastItem != null && !isCollapsedMerge(lastItem)) { list.add(lastItem) added = true } if (added) fireIntervalAdded(this, lastListIdx + 1, list.lastIndex) } fun update(item: GHPRTimelineItem) { val idx = list.indexOf(item) if (idx >= 0) list[idx] = item fireContentsChanged(this, idx, idx) } fun remove(item: GHPRTimelineItem) { val idx = list.indexOf(item) if (idx >= 0) list.removeAt(idx) fireIntervalRemoved(this, idx, idx) } fun removeAll() { val lastIdx = max(0, size - 1) list.clear() if (lastIdx > 0) fireIntervalRemoved(this, 0, lastIdx) } companion object { private const val MERGE_THRESHOLD_MS = DateFormatUtil.MINUTE * 2 private fun mergeIfPossible(existing: GHPRTimelineItem?, new: GHPRTimelineItem?): GHPRTimelineItem? { val groupedCommits = tryGroupCommits(existing, new) if (groupedCommits != null) { return groupedCommits } if (existing !is GHPRTimelineEvent || new !is GHPRTimelineEvent) return null if (existing.actor != new.actor) return null if (new.createdAt.time - existing.createdAt.time > MERGE_THRESHOLD_MS) return null if (existing is GHPRTimelineEvent.Simple && new is GHPRTimelineEvent.Simple) { if (existing is GHPRTimelineMergedSimpleEvents) { existing.add(new) return existing } else { return GHPRTimelineMergedSimpleEvents().apply { add(existing) add(new) } } } else if (existing is GHPRTimelineEvent.State && new is GHPRTimelineEvent.State) { if (existing is GHPRTimelineMergedStateEvents) { existing.add(new) return existing } else { return GHPRTimelineMergedStateEvents(existing).apply { add(new) } } } return null } private fun tryGroupCommits(existing: GHPRTimelineItem?, new: GHPRTimelineItem?): GHPRTimelineItem? { if (existing is GHPullRequestCommitShort && new is GHPullRequestCommitShort) { return GHPRTimelineGroupedCommits().apply { add(existing) add(new) } } if (existing is GHPRTimelineGroupedCommits && new is GHPullRequestCommitShort) { return existing.apply { add(new) } } if (existing is GHPullRequestCommitShort && new is GHPRTimelineGroupedCommits) { return GHPRTimelineGroupedCommits().apply { add(existing) for (item in new.items) { add(item) } } } if (existing is GHPRTimelineGroupedCommits && new is GHPRTimelineGroupedCommits) { return existing.apply { for (item in new.items) { add(item) } } } return null } private fun isCollapsedMerge(event: GHPRTimelineItem) = event is GHPRTimelineMergedEvents<*> && !event.hasAnyChanges() } }
apache-2.0
54b2020049ad8e9848be7e69485a0fca
31.72028
140
0.655696
4.582762
false
false
false
false