repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
WijayaPrinting/wp-javafx | openpss-client-javafx/src/com/hendraanggrian/openpss/ui/wage/record/Record.kt | 1 | 6355 | package com.hendraanggrian.openpss.ui.wage.record
import com.hendraanggrian.openpss.PATTERN_DATETIME
import com.hendraanggrian.openpss.R2
import com.hendraanggrian.openpss.StringResources
import com.hendraanggrian.openpss.ui.wage.Attendee
import com.hendraanggrian.openpss.ui.wage.IntervalWrapper
import com.hendraanggrian.openpss.util.START_OF_TIME
import com.hendraanggrian.openpss.util.round
import javafx.beans.property.BooleanProperty
import javafx.beans.property.DoubleProperty
import javafx.beans.property.ObjectProperty
import javafx.beans.property.ReadOnlyObjectWrapper
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleDoubleProperty
import javafx.beans.property.SimpleStringProperty
import javafx.beans.property.StringProperty
import kotlin.math.absoluteValue
import ktfx.doubleBindingOf
import ktfx.getValue
import ktfx.plus
import ktfx.setValue
import ktfx.stringBindingOf
import ktfx.toDoubleBinding
import org.joda.time.DateTime
import org.joda.time.LocalTime
class Record(
resources: StringResources,
val index: Int,
val attendee: Attendee,
val startProperty: ObjectProperty<DateTime>,
val endProperty: ObjectProperty<DateTime>,
val dailyDisabledProperty: BooleanProperty = SimpleBooleanProperty(),
val dailyProperty: DoubleProperty = SimpleDoubleProperty(),
val overtimeProperty: DoubleProperty = SimpleDoubleProperty(),
val dailyIncomeProperty: DoubleProperty = SimpleDoubleProperty(),
val overtimeIncomeProperty: DoubleProperty = SimpleDoubleProperty(),
val totalProperty: DoubleProperty = SimpleDoubleProperty()
) : StringResources by resources {
var start: DateTime? by startProperty
var end: DateTime? by endProperty
var isDailyDisabled: Boolean by dailyDisabledProperty
var daily: Double by dailyProperty
var overtime: Double by overtimeProperty
var dailyIncome: Double by dailyIncomeProperty
var overtimeIncome: Double by overtimeIncomeProperty
var total: Double by totalProperty
companion object {
const val WORKING_HOURS = 8
/** Parent row displaying name and its settings. */
const val INDEX_NODE = -2
/** Last child row of a node, displaying calculated total. */
const val INDEX_TOTAL = -1
/** Dummy for invisible [javafx.scene.control.TreeTableView] rootLayout. */
fun getDummy(resources: StringResources) = Record(
resources, Int.MIN_VALUE, Attendee.DUMMY,
ReadOnlyObjectWrapper(START_OF_TIME), ReadOnlyObjectWrapper(START_OF_TIME)
)
}
init {
dailyDisabledProperty.set(false)
if (isNode()) {
dailyProperty.set(0.0)
overtimeProperty.set(0.0)
dailyIncomeProperty.set(attendee.daily.toDouble())
overtimeIncomeProperty.set(attendee.hourlyOvertime.toDouble())
totalProperty.set(0.0)
}
if (isChild()) {
dailyProperty.bind(doubleBindingOf(startProperty, endProperty, dailyDisabledProperty) {
if (isDailyDisabled) 0.0 else {
val hours = workingHours
when {
hours <= WORKING_HOURS -> hours.round()
else -> WORKING_HOURS.toDouble()
}
}
})
overtimeProperty.bind(doubleBindingOf(startProperty, endProperty) {
val hours = workingHours
val overtime = (hours - WORKING_HOURS).round()
when {
hours <= WORKING_HOURS -> 0.0
else -> overtime
}
})
}
if (isChild() || isTotal()) {
dailyIncomeProperty.bind(dailyProperty.toDoubleBinding { (it * attendee.daily / WORKING_HOURS).round() })
overtimeIncomeProperty.bind(overtimeProperty.toDoubleBinding { (it * attendee.hourlyOvertime).round() })
totalProperty.bind(dailyIncomeProperty + overtimeIncomeProperty)
}
}
fun isNode(): Boolean = index == INDEX_NODE
fun isTotal(): Boolean = index == INDEX_TOTAL
fun isChild(): Boolean = index >= 0
val displayedName: String
get() = when {
isNode() -> attendee.toString()
isChild() -> attendee.recesses.getOrNull(index)?.toString().orEmpty()
isTotal() -> ""
else -> throw UnsupportedOperationException()
}
val displayedStart: StringProperty
get() = SimpleStringProperty().apply {
bind(stringBindingOf(startProperty, dailyDisabledProperty) {
when {
isNode() -> attendee.role.orEmpty()
isChild() -> start!!.toString(PATTERN_DATETIME).let { if (isDailyDisabled) "($it)" else it }
isTotal() -> ""
else -> throw UnsupportedOperationException()
}
})
}
val displayedEnd: StringProperty
get() = SimpleStringProperty().apply {
bind(stringBindingOf(endProperty, dailyDisabledProperty) {
when {
isNode() -> "${attendee.attendances.size / 2} ${getString(R2.string.day)}"
isChild() -> end!!.toString(PATTERN_DATETIME).let { if (isDailyDisabled) "($it)" else it }
isTotal() -> getString(R2.string.total)
else -> throw UnsupportedOperationException()
}
})
}
fun cloneStart(time: LocalTime): DateTime =
DateTime(
start!!.year,
start!!.monthOfYear,
start!!.dayOfMonth,
time.hourOfDay,
time.minuteOfHour
)
fun cloneEnd(time: LocalTime): DateTime =
DateTime(end!!.year, end!!.monthOfYear, end!!.dayOfMonth, time.hourOfDay, time.minuteOfHour)
private val workingHours: Double
get() {
val interval = IntervalWrapper.of(start!!, end!!)
var minutes = interval.minutes
attendee.recesses
.map { it.getInterval(start!!) }
.forEach {
minutes -= interval.overlap(it)?.toDuration()?.toStandardMinutes()?.minutes?.absoluteValue
?: 0
}
return minutes / 60.0
}
}
| apache-2.0 | c29a96576bfb746375c490c701ea7bd2 | 36.382353 | 117 | 0.629111 | 5.16247 | false | false | false | false |
ratabb/Hishoot2i | template/src/main/java/template/Template.kt | 1 | 2775 | @file:Suppress("SpellCheckingInspection")
package template
import entity.Glare
import entity.Sizes
import template.TemplateConstants.DEFAULT_TEMPLATE_ID
sealed class Template {
abstract val id: String
abstract val author: String
abstract val name: String
abstract val desc: String
abstract val frame: String
abstract val preview: String
abstract val sizes: Sizes
abstract val coordinate: List<Float>
abstract val installedDate: Long
/** @since HiShoot */
data class Default(
override val frame: String,
override val preview: String,
override val sizes: Sizes,
override val coordinate: List<Float>,
override val installedDate: Long
) : Template() {
override val author: String = "DCSMS aka JMKL"
override val desc: String = "Template Default"
override val id: String = DEFAULT_TEMPLATE_ID
override val name: String = "Default"
}
/** @since HiShoot */
data class Version1(
override val id: String,
override val author: String,
override val name: String,
override val desc: String,
override val frame: String,
override val sizes: Sizes,
override val coordinate: List<Float>,
override val installedDate: Long
) : Template() {
override val preview: String = frame
}
/** @since 1.0.0 (20151223) */
data class VersionHtz(
override val id: String,
override val author: String,
override val name: String,
override val desc: String,
override val frame: String,
override val preview: String,
override val sizes: Sizes,
override val coordinate: List<Float>,
override val installedDate: Long,
val glare: Glare?
) : Template()
/** @since 1.0.0 (20151223) */
data class Version2(
override val id: String,
override val author: String,
override val name: String,
override val desc: String,
override val frame: String,
override val preview: String,
override val sizes: Sizes,
override val coordinate: List<Float>,
override val installedDate: Long,
val shadow: String,
val glare: Glare?
) : Template()
/** @since 1.2.0 (20180730) */
data class Version3(
override val id: String,
override val author: String,
override val name: String,
override val desc: String,
override val frame: String,
override val preview: String,
override val sizes: Sizes,
override val coordinate: List<Float>,
override val installedDate: Long,
val shadow: String?,
val glares: List<Glare>?
) : Template()
}
| apache-2.0 | eb4c63505634ea4abdef9ef090b7d079 | 29.494505 | 54 | 0.624505 | 4.632721 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/advancement/LanternPlayerAdvancements.kt | 1 | 15712 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.advancement
import com.google.common.collect.ImmutableList
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import it.unimi.dsi.fastutil.objects.Object2LongMap
import org.lanternpowered.api.util.optional.orNull
import org.lanternpowered.server.LanternGame
import org.lanternpowered.server.advancement.criteria.LanternScoreCriterion
import org.lanternpowered.server.entity.player.LanternPlayer
import org.lanternpowered.server.game.Lantern
import org.lanternpowered.server.network.vanilla.advancement.NetworkAdvancement
import org.lanternpowered.server.network.vanilla.advancement.NetworkAdvancementDisplay
import org.lanternpowered.server.network.vanilla.packet.type.play.AdvancementsPacket
import org.lanternpowered.server.registry.type.advancement.AdvancementRegistry
import org.lanternpowered.server.registry.type.advancement.AdvancementTreeRegistry
import org.lanternpowered.server.util.gson.fromJson
import org.spongepowered.api.advancement.Advancement
import org.spongepowered.api.advancement.AdvancementTree
import org.spongepowered.api.advancement.DisplayInfo
import org.spongepowered.api.advancement.TreeLayoutElement
import org.spongepowered.api.advancement.criteria.AdvancementCriterion
import org.spongepowered.api.advancement.criteria.AndCriterion
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.text.ParseException
import java.text.SimpleDateFormat
import java.time.Instant
import java.util.ArrayList
import java.util.Date
import java.util.HashMap
import java.util.HashSet
import java.util.function.Consumer
class LanternPlayerAdvancements(val player: LanternPlayer) {
// TODO: Hook saving/loading into user data service
private val progress: MutableMap<Advancement, LanternAdvancementProgress> = HashMap()
// All the "dirty" progress that should be updated for the client
@JvmField
val dirtyProgress: MutableSet<LanternAdvancementProgress> = HashSet()
/**
* Gets the [Path] of the save file.
*
* @return The path
*/
private val savePath: Path
get() = LanternGame.gameDirectory
.resolve("advancements")
.resolve(this.player.uniqueId.toString().toLowerCase() + ".json")
fun init() {
init0()
// Load progress from the file
val file = savePath
if (Files.exists(file)) {
try {
Files.newBufferedReader(file).use { reader -> loadProgressFromJson(gson.fromJson(reader)) }
} catch (e: IOException) {
Lantern.getLogger().error("Failed to load the advancements progress for the player: ${player.uniqueId}", e)
}
}
}
fun initClient() {
this.player.connection.send(createUpdateMessage(true)!!)
}
fun save() {
val file = this.savePath
try {
// Make sure the parent directory exists
val parent = file.parent
if (!Files.exists(parent)) {
Files.createDirectories(parent)
}
Files.newBufferedWriter(file).use { writer -> gson.toJson(saveProgressToJson(), writer) }
} catch (e: IOException) {
Lantern.getLogger().error("Failed to save the advancements progress for the player: ${player.uniqueId}", e)
}
}
/**
* Reloads the progress. This should be called when the
* [Advancement]s are getting reloaded.
*/
fun reload() {
// Save the progress
val progressMap = saveProgress()
// Initialize the new advancements
this.init0()
// Load the progress again
this.loadProgress(progressMap)
// Resend the advancements to the player
this.initClient()
}
private fun init0() {
this.cleanup()
// Load all the advancements into this progress tracker
for (advancement in AdvancementRegistry) {
val progress = get(advancement)
// Update the visibility
progress.dirtyVisibility = true
this.dirtyProgress.add(progress)
}
}
fun update() {
val advancementsMessage = this.createUpdateMessage(false)
if (advancementsMessage != null)
this.player.connection.send(advancementsMessage)
}
fun cleanup() {
// Clear all the current progress
this.dirtyProgress.clear()
this.progress.values.forEach(Consumer { obj: LanternAdvancementProgress -> obj.cleanup() })
this.progress.clear()
}
/**
* Gets the [LanternAdvancementProgress] for the specified [Advancement].
*
* @param advancement The advancement
* @return The advancement progress
*/
operator fun get(advancement: Advancement): LanternAdvancementProgress {
return this.progress.computeIfAbsent(advancement) {
LanternAdvancementProgress(this, advancement as LanternAdvancement)
}
}
val unlockedAdvancementTrees: Collection<AdvancementTree>
get() {
val builder = ImmutableList.builder<AdvancementTree>()
for (tree in AdvancementTreeRegistry) {
val advancement = tree.rootAdvancement
val progress = get(advancement)
if (!progress.dirtyVisibility && progress.visible ||
progress.dirtyVisibility && shouldBeVisible(advancement)) {
builder.add(tree)
}
}
return builder.build()
}
private fun loadProgress(progressMap: Map<String, Map<String, Instant>>) {
for (advancement in AdvancementRegistry) {
val entry = progressMap[advancement.key.toString()]
if (entry != null)
this.get(advancement).loadProgress(entry)
}
}
private fun saveProgress(): Map<String, Map<String, Instant>> {
val progressMap: MutableMap<String, Map<String, Instant>> = HashMap()
for (entry in this.progress.values) {
val entryProgress = entry.saveProgress()
if (entryProgress.isNotEmpty())
progressMap[entry.advancement.key.toString()] = entryProgress
}
return progressMap
}
private fun loadProgressFromJson(json: JsonObject) {
for (advancement in AdvancementRegistry) {
val entry = json.getAsJsonObject(advancement.key.toString())
if (entry != null)
this.loadAdvancementProgressFromJson(get(advancement), entry)
}
}
private fun saveProgressToJson(): JsonObject {
val json = JsonObject()
for (entry in this.progress.values) {
val entryJson = saveAdvancementProgressToJson(entry)
if (entryJson != null)
json.add(entry.advancement.key.toString(), entryJson)
}
return json
}
private fun loadAdvancementProgressFromJson(progress: LanternAdvancementProgress, json: JsonObject) {
if (!json.has("criteria")) {
return
}
val progressMap: MutableMap<String, Instant> = HashMap()
// Convert all the string instants
for ((key, value) in json.getAsJsonObject("criteria").entrySet()) {
try {
progressMap[key] = Instant.ofEpochMilli(DATE_TIME_FORMATTER.parse(value.asString).time)
} catch (e: ParseException) {
e.printStackTrace()
progressMap[key] = Instant.now()
}
}
progress.loadProgress(progressMap)
}
private fun saveAdvancementProgressToJson(progress: LanternAdvancementProgress): JsonObject? {
val progressMap = progress.saveProgress()
val done = progress.achieved()
if (progressMap.isEmpty() && !done) {
return null
}
val json = JsonObject()
json.addProperty("done", done)
if (!progressMap.isEmpty()) {
val progressJson = JsonObject()
for ((key, value) in progressMap) {
progressJson.addProperty(key, DATE_TIME_FORMATTER.format(Date(value.toEpochMilli())))
}
json.add("criteria", progressJson)
}
return json
}
private fun createUpdateMessage(init: Boolean): AdvancementsPacket? {
if (!init && dirtyProgress.isEmpty()) {
return null
}
val added: MutableList<NetworkAdvancement> = ArrayList()
val progressMap: MutableMap<String, Object2LongMap<String>> = HashMap()
val removed: List<String>
if (init) {
removed = emptyList()
for (progress in dirtyProgress) {
// Update the visibility
update(progress, null, null, null, true)
}
for (progress in progress.values) {
if (progress.visible) {
// Add the advancement
added.add(createAdvancement(progress.advancement))
val progressMap1 = progress.collectProgress()
if (!progressMap1.isEmpty()) {
// Fill the progress map
progressMap[progress.advancement.key.toString()] = progressMap1
}
}
}
} else {
removed = ArrayList()
for (progress in dirtyProgress) {
update(progress, added, removed, progressMap, false)
}
}
// Clear the dirty progress
dirtyProgress.clear()
return AdvancementsPacket(init, added, removed, progressMap)
}
private fun update(
progress: LanternAdvancementProgress,
added: MutableList<NetworkAdvancement>?,
removed: MutableList<String>?,
progressByAdvancement: MutableMap<String, Object2LongMap<String>>?,
force: Boolean
) {
val advancement = progress.advancement
var updateParentAndChildren = false
if (progress.dirtyVisibility || force) {
val visible = shouldBeVisible(advancement)
progress.dirtyVisibility = false
if (progress.visible != visible) {
progress.visible = visible
if (visible && added != null) {
added.add(createAdvancement(advancement))
// The progress is now visible, send the complete data
if (progressByAdvancement != null) {
val progressByCriterion = progress.collectProgress()
if (!progressByCriterion.isEmpty())
progressByAdvancement[advancement.key.toString()] = progressByCriterion
// The progress is already updated, prevent from doing it again
progress.dirtyProgress = false
}
} else removed?.add(advancement.key.toString())
updateParentAndChildren = true
}
}
if (progress.visible && progress.dirtyProgress && progressByAdvancement != null)
progressByAdvancement[advancement.key.toString()] = progress.collectProgress()
// Reset dirty state, even if nothing changed
progress.dirtyProgress = false
if (updateParentAndChildren) {
for (child in advancement.children)
this.update(get(child), added, removed, progressByAdvancement, true)
val parent = advancement.parent.orNull()
if (parent != null)
this.update(get(parent), added, removed, progressByAdvancement, true)
}
}
/**
* Gets whether the [Advancement] should be visible.
*
* @param advancement The advancement
* @return Whether it should be visible
*/
private fun shouldBeVisible(advancement: Advancement): Boolean {
if (!advancement.tree.isPresent)
return false
if (this.shouldBeVisibleByChildren(advancement))
return true
var display = advancement.displayInfo.orNull()
if (display == null || display.isHidden)
return false
var depth = 2
var parent = advancement
while (depth-- > 0) {
parent = parent.parent.orNull() ?: break
display = advancement.displayInfo.orNull()
if (display == null)
return false
if (this[advancement].achieved())
return true
if (display.isHidden)
return false
}
return false
}
private fun shouldBeVisibleByChildren(advancement: Advancement): Boolean {
if (this[advancement].achieved())
return true
return advancement.children
.any { child -> this.shouldBeVisibleByChildren(child) }
}
companion object {
private val gson = GsonBuilder().setPrettyPrinting().create()
private val DATE_TIME_FORMATTER = SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z")
fun createCriteria(criterion: AdvancementCriterion): Pair<List<AdvancementCriterion>, Array<Array<String>>> {
val criteria = mutableListOf<AdvancementCriterion>()
val names = mutableListOf<Array<String>>()
if (criterion is AndCriterion) {
for (child in criterion.criteria) {
if (child is LanternScoreCriterion) {
for (id in child.ids)
names.add(arrayOf(id))
} else {
names.add(arrayOf(child.name))
}
criteria.add(child)
}
} else {
if (criterion is LanternScoreCriterion) {
for (id in criterion.ids)
names.add(arrayOf(id))
} else {
names.add(arrayOf(criterion.name))
}
criteria.add(criterion)
}
return criteria to names.toTypedArray()
}
private fun createAdvancement(advancement: Advancement): NetworkAdvancement {
val parentId = advancement.parent.map { obj -> obj.key.formatted }.orNull()
val background = if (parentId == null) advancement.tree.get().backgroundPath else null
val displayInfo = advancement.displayInfo.orNull()
val layoutElement = (advancement as LanternAdvancement).layoutElement
val criteriaRequirements = advancement.clientCriteria.second
val criteria = HashSet<String>()
for (array in criteriaRequirements)
criteria.addAll(array.asList())
val display = if (displayInfo != null) createDisplay(displayInfo, layoutElement!!, background) else null
return NetworkAdvancement(advancement.key.toString(), parentId, display, criteria, criteriaRequirements)
}
private fun createDisplay(
displayInfo: DisplayInfo, layoutElement: TreeLayoutElement, background: String?
): NetworkAdvancementDisplay {
return NetworkAdvancementDisplay(displayInfo.title, displayInfo.description, displayInfo.icon,
displayInfo.type, background, layoutElement.position, displayInfo.doesShowToast(), displayInfo.isHidden)
}
}
}
| mit | 9e569dba93cd68162e2e91eadd081da5 | 38.576826 | 124 | 0.617553 | 5.2182 | false | false | false | false |
kantega/niagara | niagara-json/src/main/kotlin/org/kantega/niagara/json/JsonEncoder.kt | 1 | 1826 | package org.kantega.niagara.json
import io.vavr.collection.List
import io.vavr.kotlin.*
import org.kantega.niagara.data.*
import java.math.BigDecimal
typealias JsonEncoder<A> = (A) -> JsonValue
fun <A, B> JsonEncoder<B>.comap(f: (A) -> B): JsonEncoder<A> = { a ->
invoke(f(a))
}
data class JsonObjectBuilder<A, B>(val f: (JsonObject, A) -> P2<JsonObject, B>) : JsonEncoder<A> {
override fun invoke(a: A): JsonValue =
f(JsonObject(), a)._1
fun <C> append(f: (JsonObject, B) -> P2<JsonObject, C>): JsonObjectBuilder<A, C> = JsonObjectBuilder { jsonObject, a ->
val (nextObj, b) = f(jsonObject, a)
f(nextObj, b)
}
}
fun <A, B, T : HList> encode(destructor: (A) -> HCons<B, T>): JsonObjectBuilder<A, HCons<B, T>> =
JsonObjectBuilder({ jsonObj, a -> p(jsonObj, destructor(a)) })
fun <A, B, T, L : HCons<B, T>> JsonObjectBuilder<A, L>.field(name: String, aEncoder: JsonEncoder<B>): JsonObjectBuilder<A, T> =
append { jsonObj, hList ->
p(jsonObj.set(name, aEncoder(hList.head)), hList.tail)
}
fun <A, L : HList> JsonObjectBuilder<A, L>.value(name: String, value: JsonValue): JsonObjectBuilder<A, L> =
append { jsonObj, hList ->
p(jsonObj.set(name, value), hList)
}
val encodeString: JsonEncoder<String> = ::JsonString
val encodeNumber: JsonEncoder<BigDecimal> = ::JsonNumber
val encodeInt: JsonEncoder<Int> = { n -> JsonNumber(n.toBigDecimal()) }
val encodeLong: JsonEncoder<Long> = { n -> JsonNumber(n.toBigDecimal()) }
val encodeDouble: JsonEncoder<Double> = { n -> JsonNumber(n.toBigDecimal()) }
val encodeBool: JsonEncoder<Boolean> = ::JsonBool
fun <A> encodeArray(elemEncoder: JsonEncoder<A>): JsonEncoder<List<A>> = { list ->
JsonArray(list.map { a -> elemEncoder(a) })
}
data class User(val name: String, val age: Int) : Product2<String, Int> | apache-2.0 | 43815ade9f9a717435e053f51659ef68 | 31.052632 | 127 | 0.666484 | 3.175652 | false | false | false | false |
KotlinKit/Reactant | Core/src/main/kotlin/org/brightify/reactant/autolayout/internal/solver/SimplexSolver.kt | 1 | 12044 | package org.brightify.reactant.autolayout.internal.solver
import android.util.Log
import org.brightify.reactant.autolayout.ConstraintOperator
import org.brightify.reactant.autolayout.ConstraintPriority
import org.brightify.reactant.autolayout.ConstraintVariable
import org.brightify.reactant.autolayout.internal.ConstraintItem
import org.brightify.reactant.autolayout.internal.util.isAlmostZero
import java.util.HashSet
/**
* @author <a href="mailto:[email protected]">Filip Dolnik</a>
*/
internal class SimplexSolver {
private val errorSymbols = LinkedHashMap<Equation, HashSet<Symbol>>()
private val objective = Symbol(Symbol.Type.objective)
private var columns = HashMap<Symbol, HashSet<Symbol>>()
private var rows = LinkedHashMap<Symbol, Row>().apply { put(objective, Row()) }
private val symbolForEquation = LinkedHashMap<Equation, Symbol>()
private val symbolForVariable = HashMap<ConstraintVariable, Symbol>()
fun addEquation(equation: Equation, constraintItem: ConstraintItem) {
try {
addEquationImmediately(equation)
} catch (_: InternalSolverError) {
Log.e("AutoLayout", "Constraint ($constraintItem) cannot be satisfied and will be ignored.")
}
}
fun removeEquation(equation: Equation) {
removeEquationImmediately(equation)
}
fun solve() {
optimize(objective)
}
fun getValueForVariable(variable: ConstraintVariable): Double {
return symbolForVariable[variable]?.let { rows[it]?.constant } ?: 0.0
}
private fun addEquationImmediately(equation: Equation) {
val expression = createRow(equation)
try {
if (!tryAddingDirectly(expression)) {
addWithArtificialVariable(expression)
}
} catch (e: InternalSolverError) {
removeEquationImmediately(equation)
throw e
}
}
private fun removeEquationImmediately(equation: Equation) {
val marker = symbolForEquation.remove(equation) ?: return
removeEquationEffects(equation, marker)
removeRow(marker)
errorSymbols[equation]?.forEach {
if (it != marker) {
removeColumn(it)
}
}
errorSymbols.remove(equation)
}
private fun createRow(equation: Equation): Row {
val row = Row(-equation.constant)
equation.terms.forEach {
val symbol = getSymbolForVariable(it.variable)
val rowWithSymbol = rows[symbol]
if (rowWithSymbol != null) {
row.addExpression(rowWithSymbol, it.coefficient)
} else {
row.addVariable(symbol, it.coefficient)
}
}
if (equation.operator == ConstraintOperator.equal) {
if (equation.priority == ConstraintPriority.required) {
val symbol = Symbol(Symbol.Type.dummy)
row.addVariable(symbol, 1.0)
symbolForEquation[equation] = symbol
} else {
val slackPlus = Symbol(Symbol.Type.slack)
val slackMinus = Symbol(Symbol.Type.slack)
row.addVariable(slackPlus, -1.0)
row.addVariable(slackMinus, 1.0)
symbolForEquation[equation] = slackPlus
rows[objective]?.let {
it.addVariable(slackPlus, equation.priority.value.toDouble())
onSymbolAdded(slackPlus, objective)
it.addVariable(slackMinus, equation.priority.value.toDouble())
onSymbolAdded(slackMinus, objective)
insertErrorSymbol(equation, slackMinus)
insertErrorSymbol(equation, slackPlus)
}
}
} else {
if (equation.operator == ConstraintOperator.lessOrEqual) {
row.multiplyBy(-1.0)
}
val slack = Symbol(Symbol.Type.slack)
row.addVariable(slack, -1.0)
symbolForEquation[equation] = slack
if (equation.priority != ConstraintPriority.required) {
val slackMinus = Symbol(Symbol.Type.slack)
row.addVariable(slackMinus, 1.0)
rows[objective]?.addVariable(slackMinus, equation.priority.value.toDouble())
insertErrorSymbol(equation, slackMinus)
onSymbolAdded(slackMinus, objective)
}
}
if (row.constant < 0) {
row.multiplyBy(-1.0)
}
return row
}
private fun removeEquationEffects(equation: Equation, marker: Symbol) {
errorSymbols[equation]?.forEach {
val row = rows[it]
if (row != null) {
rows[objective]?.addExpression(row, -equation.priority.value.toDouble(), objective, this)
} else {
rows[objective]?.addVariable(it, -equation.priority.value.toDouble(), objective, this)
}
}
if (rows[marker] == null) {
columns[marker]?.let { column ->
var leaving: Symbol? = null
var minRatio = 0.0
column.forEach {
if (it.isRestricted) {
rows[it]?.let { row ->
val coefficient = row.coefficientFor(marker)
if (coefficient < 0.0) {
val r = -row.constant / coefficient
if (leaving == null || r < minRatio) {
minRatio = coefficient
leaving = it
}
}
}
}
}
if (leaving == null) {
column.forEach {
if (it.isRestricted) {
rows[it]?.let { row ->
val coefficient = row.coefficientFor(marker)
val r = row.constant / coefficient
if (leaving == null || r < minRatio) {
minRatio = coefficient
leaving = it
}
}
}
}
}
if (leaving == null) {
if (column.size == 0) {
removeColumn(marker)
} else {
leaving = column.first()
}
}
leaving?.let { pivot(marker, it) }
}
}
}
private fun tryAddingDirectly(row: Row): Boolean {
val subject = chooseSubject(row) ?: return false
row.newSubject(subject)
if (columns.containsKey(subject)) {
substituteOut(subject, row)
}
addRow(subject, row)
return true
}
private fun chooseSubject(row: Row): Symbol? {
row.symbols.keys.firstOrNull { !it.isRestricted }?.let { return it }
row.symbols.forEach { (symbol, value) ->
if (symbol.type != Symbol.Type.dummy && value < 0.0 && columns[symbol] == null) {
return symbol
}
}
var subject: Symbol? = null
var coefficient = 0.0
row.symbols.forEach { (symbol, value) ->
if (symbol.type != Symbol.Type.dummy) {
return null
} else if (!columns.containsKey(symbol)) {
subject = symbol
coefficient = value
}
}
if (!row.constant.isAlmostZero) {
throw InternalSolverError()
}
if (coefficient > 0.0) {
row.multiplyBy(-1.0)
}
return subject
}
private fun addWithArtificialVariable(row: Row) {
val artificialVariable = Symbol(Symbol.Type.slack)
val objectiveVariable = Symbol(Symbol.Type.objective)
addRow(objectiveVariable, Row(row))
addRow(artificialVariable, row)
optimize(objectiveVariable)
if (rows[objectiveVariable]?.constant?.isAlmostZero != true) {
removeRow(objectiveVariable)
removeColumn(artificialVariable)
throw InternalSolverError()
}
rows[artificialVariable]?.let { artificialRow ->
val entering = artificialRow.symbols.keys.first { it.type == Symbol.Type.slack }
pivot(entering, artificialVariable)
}
removeColumn(artificialVariable)
removeRow(objectiveVariable)
}
private fun optimize(symbol: Symbol) {
val row = rows[symbol] ?: return
while (true) {
val entering = getEnteringSymbol(row) ?: return
val leaving = getLeavingSymbol(entering) ?: return
pivot(entering, leaving)
}
}
private fun getEnteringSymbol(row: Row): Symbol? {
row.symbols.forEach { (symbol, value) ->
if (symbol.type == Symbol.Type.slack && value < 0) {
return symbol
}
}
return null
}
private fun getLeavingSymbol(entering: Symbol): Symbol? {
var minRatio = java.lang.Double.MAX_VALUE
var symbol: Symbol? = null
columns[entering]?.forEach {
if (it.type == Symbol.Type.slack) {
rows[it]?.let { row ->
val coefficient = row.coefficientFor(entering)
if (coefficient < 0.0) {
val ratio = -row.constant / coefficient
if (ratio < minRatio) {
minRatio = ratio
symbol = it
}
}
}
}
}
return symbol
}
private fun pivot(entrySymbol: Symbol, exitSymbol: Symbol) {
removeRow(exitSymbol)?.let {
it.changeSubject(exitSymbol, entrySymbol)
substituteOut(entrySymbol, it)
addRow(entrySymbol, it)
}
}
private fun insertErrorSymbol(equation: Equation, symbol: Symbol) {
var symbols = errorSymbols[equation]
if (symbols == null) {
symbols = HashSet()
errorSymbols[equation] = symbols
}
symbols.add(symbol)
}
internal fun onSymbolRemoved(symbol: Symbol, subject: Symbol) {
columns[symbol]?.remove(subject)
}
internal fun onSymbolAdded(symbol: Symbol, subject: Symbol) {
insertColumnVariable(symbol, subject)
}
private fun insertColumnVariable(columnVariable: Symbol, rowVariable: Symbol) {
var rows = columns[columnVariable]
if (rows == null) {
rows = HashSet()
columns[columnVariable] = rows
}
rows.add(rowVariable)
}
private fun addRow(symbol: Symbol, row: Row) {
rows[symbol] = row
row.symbols.keys.forEach { insertColumnVariable(it, symbol) }
}
private fun removeColumn(symbol: Symbol) {
columns.remove(symbol)?.forEach { rows[it]?.symbols?.remove(symbol) }
}
private fun removeRow(symbol: Symbol): Row? {
val row = rows.remove(symbol)
row?.symbols?.keys?.forEach { columns[it]?.remove(symbol) }
return row
}
private fun substituteOut(oldSymbol: Symbol, row: Row) {
columns.remove(oldSymbol)?.forEach {
rows[it]?.substituteOut(oldSymbol, row, it, this)
}
}
private fun getSymbolForVariable(variable: ConstraintVariable): Symbol {
var symbol = symbolForVariable[variable]
if (symbol == null) {
symbol = Symbol(Symbol.Type.external)
symbolForVariable[variable] = symbol
}
return symbol
}
private val Symbol.isRestricted: Boolean
get() = type == Symbol.Type.slack || type == Symbol.Type.dummy
}
| mit | fc43de890ed74d4de8159c87a3366459 | 32.736695 | 105 | 0.541597 | 5.037223 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/itemliquefier/ItemLiquefierEntity.kt | 1 | 9823 | package net.ndrei.teslapoweredthingies.machines.itemliquefier
import net.minecraft.init.Items
import net.minecraft.inventory.Slot
import net.minecraft.item.EnumDyeColor
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraftforge.fluids.Fluid
import net.minecraftforge.fluids.FluidRegistry
import net.minecraftforge.fluids.FluidUtil
import net.minecraftforge.fluids.IFluidTank
import net.minecraftforge.fluids.capability.CapabilityFluidHandler
import net.minecraftforge.items.ItemStackHandler
import net.ndrei.teslacorelib.compatibility.ItemStackUtil
import net.ndrei.teslacorelib.containers.BasicTeslaContainer
import net.ndrei.teslacorelib.containers.FilteredSlot
import net.ndrei.teslacorelib.gui.BasicRenderedGuiPiece
import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer
import net.ndrei.teslacorelib.gui.FluidTankPiece
import net.ndrei.teslacorelib.gui.IGuiContainerPiece
import net.ndrei.teslacorelib.inventory.BoundingRectangle
import net.ndrei.teslacorelib.inventory.ColoredItemHandler
import net.ndrei.teslacorelib.inventory.FluidStorage
import net.ndrei.teslapoweredthingies.client.ThingiesTexture
import net.ndrei.teslapoweredthingies.common.gui.IWorkItemProvider
import net.ndrei.teslapoweredthingies.common.gui.ItemStackPiece
import net.ndrei.teslapoweredthingies.machines.BaseThingyMachine
/**
* Created by CF on 2017-06-30.
*/
class ItemLiquefierEntity : BaseThingyMachine(ItemLiquefierEntity::class.java.name.hashCode()), IWorkItemProvider {
private var lavaTank: IFluidTank? = null
private var inputs: ItemStackHandler? = null
private var fluidOutputs: ItemStackHandler? = null
private var currentRecipe: ItemLiquefierRecipe? = null
//region Inventory and GUI stuff
override fun initializeInventories() {
super.initializeInventories()
super.ensureFluidItems()
this.lavaTank = super.addFluidTank(FluidRegistry.LAVA, 5000, EnumDyeColor.RED, "Fluid Tank",
BoundingRectangle(133, 25, FluidTankPiece.WIDTH, FluidTankPiece.HEIGHT))
this.inputs = object : ItemStackHandler(3) {
override fun onContentsChanged(slot: Int) {
[email protected]()
}
}
super.addInventory(object : ColoredItemHandler(this.inputs!!, EnumDyeColor.GREEN, "Input Items", BoundingRectangle(61, 25, 18, 54)) {
override fun canInsertItem(slot: Int, stack: ItemStack): Boolean {
return !stack.isEmpty && ItemLiquefierRegistry.getRecipe(stack) != null
}
override fun canExtractItem(slot: Int): Boolean {
return false
}
})
super.addInventoryToStorage(this.inputs!!, "inv_inputs")
val box = BoundingRectangle(151, 25, FluidTankPiece.WIDTH, FluidTankPiece.HEIGHT)
this.fluidOutputs = object : ItemStackHandler(2) {
override fun getSlotLimit(slot: Int): Int {
return if (slot == 0) 1 else super.getSlotLimit(slot)
}
override fun onContentsChanged(slot: Int) {
[email protected]()
}
}
super.addInventory(object : ColoredItemHandler(this.fluidOutputs!!, EnumDyeColor.SILVER, "Fluid Output", box) {
override fun canInsertItem(slot: Int, stack: ItemStack): Boolean {
return slot == 0 && [email protected](stack)
}
override fun canExtractItem(slot: Int): Boolean {
return slot != 0
}
override fun getSlots(container: BasicTeslaContainer<*>): MutableList<Slot> {
val slots = mutableListOf<Slot>()
val box = this.boundingBox
slots.add(FilteredSlot(this.itemHandlerForContainer, 0, box.left + 1, box.top + 1))
slots.add(FilteredSlot(this.itemHandlerForContainer, 1, box.left + 1, box.top + 1 + 36))
return slots
}
override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>): MutableList<IGuiContainerPiece> {
val pieces = mutableListOf<IGuiContainerPiece>()
val box = this.boundingBox
pieces.add(BasicRenderedGuiPiece(box.left, box.top, box.width, box.height,
ThingiesTexture.MACHINES_TEXTURES.resource, 98, 36))
return pieces
}
})
super.addInventoryToStorage(this.fluidOutputs!!, "inv_fluid_outputs")
}
private fun isValidFluidContainer(stack: ItemStack): Boolean {
if (!stack.isEmpty) {
val item = stack.item
if (item === Items.GLASS_BOTTLE || item === Items.BUCKET) {
return true
}
if (stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) {
val handler = stack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)
if (handler != null) {
val tanks = handler.tankProperties
if (tanks != null && tanks.size > 0) {
for (tank in tanks) {
if (tank.canFill()) {
val content = tank.contents
if (content == null || content.amount < tank.capacity && content.fluid === FluidRegistry.LAVA) {
return true
}
}
}
}
}
}
}
return false
}
override fun shouldAddFluidItemsInventory(): Boolean {
return false
}
override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>): MutableList<IGuiContainerPiece> {
val pieces = super.getGuiContainerPieces(container)
pieces.add(BasicRenderedGuiPiece(79, 41, 54, 22,
ThingiesTexture.MACHINES_TEXTURES.resource, 24, 4))
pieces.add(BasicRenderedGuiPiece(99, 64, 14, 14,
ThingiesTexture.MACHINES_TEXTURES.resource, 44, 27))
pieces.add(ItemStackPiece(96, 42, 20, 20, this))
return pieces
}
//endregion
//region serialization
override fun readFromNBT(compound: NBTTagCompound) {
super.readFromNBT(compound)
if (compound.hasKey("currentRecipe")) {
this.currentRecipe = ItemLiquefierRecipe.deserializeNBT(compound.getCompoundTag("currentRecipe"))
} else {
this.currentRecipe = null
}
}
override fun writeToNBT(compound: NBTTagCompound): NBTTagCompound {
var compound = compound
compound = super.writeToNBT(compound)
if (this.currentRecipe != null) {
compound.setTag("currentRecipe", this.currentRecipe!!.serializeNBT())
}
return compound
}
//endregion
override val workItem: ItemStack
get() {
if (this.currentRecipe != null) {
return this.currentRecipe!!.input.copy() // ItemStack(this.currentRecipe!!.input, this.currentRecipe!!.inputStackSize)
}
return ItemStack.EMPTY
}
override val energyForWork: Int
get() = 6000
override fun performWork(): Float {
var result = 0.0f
if (this.currentRecipe != null) {
val fluid = this.currentRecipe!!.output.copy() // FluidStack(this.currentRecipe!!.output, this.currentRecipe!!.outputQuantity)
if (this.lavaTank!!.fill(fluid, false) == fluid.amount) { // this.currentRecipe!!.outputQuantity) {
this.lavaTank!!.fill(fluid, true)
this.currentRecipe = null
result = 1.0f
}
}
return result
}
override fun processImmediateInventories() {
super.processImmediateInventories()
var stack = this.fluidOutputs!!.getStackInSlot(0)
val maxDrain = this.lavaTank!!.fluidAmount
if (!stack.isEmpty && maxDrain > 0) {
if (stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) {
val toFill = Math.max(maxDrain, Fluid.BUCKET_VOLUME)
val dummy = FluidStorage()
dummy.addTank(this.lavaTank!!)
val result = FluidUtil.tryFillContainer(stack, dummy, toFill, null, true)
if (result.isSuccess) {
stack = result.getResult()
this.fluidOutputs!!.setStackInSlot(0, stack)
}
if (!stack.isEmpty && !this.isEmptyFluidContainer(stack)) {
this.fluidOutputs!!.setStackInSlot(0, this.fluidOutputs!!.insertItem(1, stack, false))
}
}
}
if (this.currentRecipe == null) {
for (input in ItemStackUtil.getCombinedInventory(this.inputs!!)) {
val recipe = ItemLiquefierRegistry.getRecipe(input/*.item*/)
if (recipe != null) { // && recipe.inputStackSize <= input.count) {
val fluid = recipe.output.copy() // FluidStack(recipe.output, recipe.outputQuantity)
if (this.lavaTank!!.fill(fluid, false) == fluid.amount) { // recipe.outputQuantity) {
ItemStackUtil.extractFromCombinedInventory(this.inputs!!, input, recipe.input.count) // inputStackSize)
this.currentRecipe = recipe
break
}
}
}
}
}
private fun isEmptyFluidContainer(stack: ItemStack): Boolean {
val fluid = FluidUtil.getFluidContained(stack)
return fluid == null || fluid.amount == 0
}
}
| mit | 18eecd0299ffeabafab0d30cbb3b20e8 | 39.258197 | 141 | 0.621602 | 5.037436 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/views/viewer/SeekController.kt | 1 | 874 | package com.pr0gramm.app.ui.views.viewer
import androidx.collection.LruCache
import com.google.android.exoplayer2.SimpleExoPlayer
object SeekController {
private val seekToCache = LruCache<Long, ExpiringTimestamp>(16)
fun store(id: Long, exo: SimpleExoPlayer) {
seekToCache.put(id, ExpiringTimestamp(exo.currentPosition))
}
fun restore(id: Long, exo: SimpleExoPlayer) {
// restore seek position if known
val seekTo = seekToCache.get(id)
if (seekTo != null && seekTo.valid) {
exo.seekTo(seekTo.timestamp)
}
}
/**
* This timestamp value is only valid for 60 seconds.
*/
private class ExpiringTimestamp(val timestamp: Long) {
private val created: Long = System.currentTimeMillis()
val valid: Boolean get() = (System.currentTimeMillis() - created) < 60 * 1000
}
} | mit | 9d4aca10ba7d2ac49f69664160c50120 | 30.25 | 85 | 0.668192 | 4.222222 | false | false | false | false |
FHannes/intellij-community | platform/analysis-impl/src/com/intellij/profile/codeInspection/ProjectInspectionProfileManager.kt | 5 | 12847 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.profile.codeInspection
import com.intellij.codeInspection.InspectionProfile
import com.intellij.codeInspection.ex.InspectionProfileImpl
import com.intellij.codeInspection.ex.InspectionToolRegistrar
import com.intellij.configurationStore.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.packageDependencies.DependencyValidationManager
import com.intellij.profile.ProfileChangeAdapter
import com.intellij.project.isDirectoryBased
import com.intellij.psi.search.scope.packageSet.NamedScopeManager
import com.intellij.psi.search.scope.packageSet.NamedScopesHolder
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.loadElement
import com.intellij.util.xmlb.Accessor
import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters
import com.intellij.util.xmlb.XmlSerializer
import com.intellij.util.xmlb.annotations.OptionTag
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.resolvedPromise
import org.jetbrains.concurrency.runAsync
import java.util.*
import java.util.function.Function
private const val VERSION = "1.0"
private const val SCOPE = "scope"
private const val NAME = "name"
private const val PROJECT_DEFAULT_PROFILE_NAME = "Project Default"
private val defaultSchemeDigest = loadElement("""<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
</profile>
</component>""").digest()
@State(name = "InspectionProjectProfileManager", storages = arrayOf(Storage(value = "inspectionProfiles/profiles_settings.xml", exclusive = true)))
class ProjectInspectionProfileManager(val project: Project,
private val applicationProfileManager: InspectionProfileManager,
private val scopeManager: DependencyValidationManager,
private val localScopesHolder: NamedScopeManager,
schemeManagerFactory: SchemeManagerFactory) : BaseInspectionProfileManager(project.messageBus), PersistentStateComponent<Element> {
companion object {
@JvmStatic
fun getInstance(project: Project): ProjectInspectionProfileManager {
return project.getComponent(ProjectInspectionProfileManager::class.java)
}
}
private val profileListeners: MutableList<ProfileChangeAdapter> = ContainerUtil.createLockFreeCopyOnWriteList<ProfileChangeAdapter>()
private var scopeListener: NamedScopesHolder.ScopeListener? = null
private var state = State()
private val initialLoadSchemesFuture: Promise<Any?>
private val skipDefaultsSerializationFilter = object : SkipDefaultValuesSerializationFilters(State()) {
override fun accepts(accessor: Accessor, bean: Any, beanValue: Any?): Boolean {
if (beanValue == null && accessor.name == "projectProfile") {
return false
}
return super.accepts(accessor, bean, beanValue)
}
}
private val schemeManagerIprProvider = if (project.isDirectoryBased) null else SchemeManagerIprProvider("profile")
override val schemeManager = schemeManagerFactory.create("inspectionProfiles", object : InspectionProfileProcessor() {
override fun createScheme(dataHolder: SchemeDataHolder<InspectionProfileImpl>,
name: String,
attributeProvider: Function<String, String?>,
isBundled: Boolean): InspectionProfileImpl {
val profile = InspectionProfileImpl(name, InspectionToolRegistrar.getInstance(), this@ProjectInspectionProfileManager, dataHolder)
profile.isProjectLevel = true
return profile
}
override fun isSchemeFile(name: CharSequence) = !StringUtil.equals(name, "profiles_settings.xml")
override fun isSchemeDefault(scheme: InspectionProfileImpl, digest: ByteArray): Boolean {
return scheme.name == PROJECT_DEFAULT_PROFILE_NAME && Arrays.equals(digest, defaultSchemeDigest)
}
override fun onSchemeDeleted(scheme: InspectionProfileImpl) {
schemeRemoved(scheme)
}
override fun onSchemeAdded(scheme: InspectionProfileImpl) {
if (scheme.wasInitialized()) {
fireProfileChanged(scheme)
}
}
override fun onCurrentSchemeSwitched(oldScheme: InspectionProfileImpl?, newScheme: InspectionProfileImpl?) {
for (adapter in profileListeners) {
adapter.profileActivated(oldScheme, newScheme)
}
}
}, isUseOldFileNameSanitize = true, streamProvider = schemeManagerIprProvider)
private data class State(@field:OptionTag("PROJECT_PROFILE") var projectProfile: String? = PROJECT_DEFAULT_PROFILE_NAME,
@field:OptionTag("USE_PROJECT_PROFILE") var useProjectProfile: Boolean = true)
init {
val app = ApplicationManager.getApplication()
if (!project.isDirectoryBased || app.isUnitTestMode) {
initialLoadSchemesFuture = resolvedPromise()
}
else {
initialLoadSchemesFuture = runAsync { schemeManager.loadSchemes() }
}
project.messageBus.connect().subscribe(ProjectManager.TOPIC, object: ProjectManagerListener {
override fun projectClosed(project: Project) {
val cleanupInspectionProfilesRunnable = {
cleanupSchemes(project)
(InspectionProfileManager.getInstance() as BaseInspectionProfileManager).cleanupSchemes(project)
fireProfilesShutdown()
}
if (app.isUnitTestMode || app.isHeadlessEnvironment) {
cleanupInspectionProfilesRunnable.invoke()
}
else {
app.executeOnPooledThread(cleanupInspectionProfilesRunnable)
}
}
})
}
@TestOnly
fun forceLoadSchemes() {
LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode)
schemeManager.loadSchemes()
}
fun isCurrentProfileInitialized() = currentProfile.wasInitialized()
override fun schemeRemoved(scheme: InspectionProfileImpl) {
scheme.cleanup(project)
}
@Suppress("unused")
private class ProjectInspectionProfileStartUpActivity : StartupActivity {
override fun runActivity(project: Project) {
getInstance(project).apply {
initialLoadSchemesFuture.done {
if (!project.isDisposed) {
currentProfile.initInspectionTools(project)
fireProfilesInitialized()
}
}
scopeListener = NamedScopesHolder.ScopeListener {
for (profile in schemeManager.allSchemes) {
profile.scopesChanged()
}
}
scopeManager.addScopeListener(scopeListener!!)
localScopesHolder.addScopeListener(scopeListener!!)
Disposer.register(project, Disposable {
scopeManager.removeScopeListener(scopeListener!!)
localScopesHolder.removeScopeListener(scopeListener!!)
(initialLoadSchemesFuture as? AsyncPromise<*>)?.cancel()
})
}
}
}
@Synchronized override fun getState(): Element? {
val result = Element("settings")
schemeManagerIprProvider?.writeState(result)
val state = this.state
if (state.useProjectProfile) {
state.projectProfile = schemeManager.currentSchemeName
}
XmlSerializer.serializeInto(state, result, skipDefaultsSerializationFilter)
if (!result.children.isEmpty()) {
result.addContent(Element("version").setAttribute("value", VERSION))
}
severityRegistrar.writeExternal(result)
return wrapState(result, project)
}
@Synchronized override fun loadState(state: Element) {
val data = unwrapState(state, project, schemeManagerIprProvider, schemeManager)
val newState = State()
data?.let {
try {
severityRegistrar.readExternal(it)
}
catch (e: Throwable) {
LOG.error(e)
}
XmlSerializer.deserializeInto(newState, it)
}
this.state = newState
if (data != null && data.getChild("version")?.getAttributeValue("value") != VERSION) {
for (o in data.getChildren("option")) {
if (o.getAttributeValue("name") == "USE_PROJECT_LEVEL_SETTINGS") {
if (o.getAttributeValue("value").toBoolean()) {
if (newState.projectProfile != null) {
currentProfile.convert(data, project)
}
}
break
}
}
}
if (newState.useProjectProfile) {
schemeManager.currentSchemeName = newState.projectProfile
}
}
override fun getScopesManager() = scopeManager
@Synchronized override fun getProfiles(): Collection<InspectionProfileImpl> {
currentProfile
return schemeManager.allSchemes
}
@Synchronized fun getAvailableProfileNames(): Array<String> = schemeManager.allSchemeNames.toTypedArray()
val projectProfile: String?
get() = schemeManager.currentSchemeName
@Synchronized override fun setRootProfile(name: String?) {
if (name != schemeManager.currentSchemeName) {
schemeManager.currentSchemeName = name
state.useProjectProfile = name != null
}
}
@Synchronized fun useApplicationProfile(name: String) {
schemeManager.currentSchemeName = null
state.useProjectProfile = false
// yes, we reuse the same field - useProjectProfile field will be used to distinguish - is it app or project level
// to avoid data format change
state.projectProfile = name
}
@Synchronized fun setCurrentProfile(profile: InspectionProfileImpl?) {
schemeManager.setCurrent(profile)
state.useProjectProfile = profile != null
}
@Synchronized override fun getCurrentProfile(): InspectionProfileImpl {
if (!state.useProjectProfile) {
return (state.projectProfile?.let {
applicationProfileManager.getProfile(it, false)
} ?: applicationProfileManager.currentProfile)
}
var currentScheme = schemeManager.currentScheme
if (currentScheme == null) {
currentScheme = schemeManager.allSchemes.firstOrNull()
if (currentScheme == null) {
currentScheme = InspectionProfileImpl(PROJECT_DEFAULT_PROFILE_NAME, InspectionToolRegistrar.getInstance(), this)
currentScheme.copyFrom(applicationProfileManager.currentProfile)
currentScheme.isProjectLevel = true
currentScheme.name = PROJECT_DEFAULT_PROFILE_NAME
schemeManager.addScheme(currentScheme)
}
schemeManager.setCurrent(currentScheme, false)
}
return currentScheme
}
private fun fireProfilesInitialized() {
for (listener in profileListeners) {
listener.profilesInitialized()
}
}
private fun fireProfilesShutdown() {
for (profileChangeAdapter in profileListeners) {
profileChangeAdapter.profilesShutdown()
}
}
@Synchronized override fun getProfile(name: String, returnRootProfileIfNamedIsAbsent: Boolean): InspectionProfileImpl? {
val profile = schemeManager.findSchemeByName(name)
return profile ?: applicationProfileManager.getProfile(name, returnRootProfileIfNamedIsAbsent)
}
fun fireProfileChanged() {
fireProfileChanged(currentProfile)
}
fun addProfileChangeListener(listener: ProfileChangeAdapter, parentDisposable: Disposable) {
ContainerUtil.add(listener, profileListeners, parentDisposable)
}
fun fireProfileChanged(oldProfile: InspectionProfile?, profile: InspectionProfile) {
for (adapter in profileListeners) {
adapter.profileActivated(oldProfile, profile)
}
}
override fun fireProfileChanged(profile: InspectionProfileImpl) {
profile.profileChanged()
for (adapter in profileListeners) {
adapter.profileChanged(profile)
}
}
} | apache-2.0 | 8e2a93212dd8fd781a31ceb5ef462fa6 | 36.025937 | 169 | 0.729898 | 5.418389 | false | false | false | false |
FHannes/intellij-community | platform/vcs-tests/testSrc/com/intellij/vcs/test/utils.kt | 6 | 3320 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.test
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.testFramework.UsefulTestCase.assertOrderedEquals
import org.junit.Assert.assertEquals
import org.picocontainer.MutablePicoContainer
inline fun <reified Int : Any, reified Impl : Int> overrideService(project: Project): Impl {
val key = Int::class.java.name
val picoContainer = project.picoContainer as MutablePicoContainer
picoContainer.unregisterComponent(key)
picoContainer.registerComponentImplementation(key, Impl::class.java)
return project.service<Int>() as Impl
}
inline fun <reified Int : Any, reified Impl : Int> overrideService(): Impl {
val key = Int::class.java.name
val picoContainer = ApplicationManager.getApplication().picoContainer as MutablePicoContainer
picoContainer.unregisterComponent(key)
picoContainer.registerComponentImplementation(key, Impl::class.java)
return service<Int>() as Impl
}
fun assertNotification(type: NotificationType, title: String, content: String, actions: List<String>, actual: Notification): Notification {
assertEquals("Incorrect notification type: " + tos(actual), type, actual.type)
assertEquals("Incorrect notification title: " + tos(actual), title, actual.title)
assertEquals("Incorrect notification content: " + tos(actual), cleanupForAssertion(content), cleanupForAssertion(actual.content))
assertOrderedEquals("Incorrect notification actions", actions, actual.actions.map { it.templatePresentation.text })
return actual
}
fun assertNotification(type: NotificationType, title: String, content: String, actual: Notification) =
assertNotification(type, title, content, listOf(), actual)
fun assertSuccessfulNotification(title: String, content: String, actual: Notification) =
assertNotification(NotificationType.INFORMATION, title, content, actual)
fun assertSuccessfulNotification(title: String, content: String, actions: List<String>, actual: Notification) =
assertNotification(NotificationType.INFORMATION, title, content, actions, actual)
fun cleanupForAssertion(content: String): String {
val nobr = content.replace("<br/>", "\n").replace("<br>", "\n").replace("<hr/>", "\n")
.replace(" ", " ").replace(" {2,}".toRegex(), " ")
return nobr.lines()
.map { line -> line.replace(" href='[^']*'".toRegex(), "").trim({ it <= ' ' }) }
.filter { line -> !line.isEmpty() }
.joinToString(" ")
}
private fun tos(notification: Notification): String {
return "${notification.title}|${notification.content}"
}
| apache-2.0 | af1bcd55c831e9e866def3b6355f04d1 | 45.760563 | 139 | 0.761747 | 4.403183 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/muteparticipants/MuteParticipantsViewModel.kt | 1 | 4945 | package com.quickblox.sample.conference.kotlin.presentation.screens.muteparticipants
import android.os.Bundle
import com.quickblox.chat.model.QBChatDialog
import com.quickblox.conference.ConferenceSession
import com.quickblox.sample.conference.kotlin.domain.DomainCallback
import com.quickblox.sample.conference.kotlin.domain.call.CallListener
import com.quickblox.sample.conference.kotlin.domain.call.CallManager
import com.quickblox.sample.conference.kotlin.domain.call.entities.CallEntity
import com.quickblox.sample.conference.kotlin.domain.chat.ChatManager
import com.quickblox.sample.conference.kotlin.domain.repositories.db.DBRepository
import com.quickblox.sample.conference.kotlin.domain.user.UserManager
import com.quickblox.sample.conference.kotlin.presentation.LiveData
import com.quickblox.sample.conference.kotlin.presentation.screens.base.BaseViewModel
import com.quickblox.users.model.QBUser
import com.quickblox.videochat.webrtc.BaseSession
import dagger.hilt.android.lifecycle.HiltViewModel
import java.util.*
import javax.inject.Inject
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
@HiltViewModel
class MuteParticipantsViewModel @Inject constructor(private val dbRepository: DBRepository, private val userManager: UserManager,
private val callManager: CallManager, private val chatManager: ChatManager) : BaseViewModel() {
private val TAG: String = MuteParticipantsViewModel::class.java.simpleName
val liveData = LiveData<Pair<Int, Any?>>()
private val callListener = CallListenerImpl(TAG)
var callEntities: SortedSet<CallEntity>
private set
var currentDialog: QBChatDialog? = null
private set
var currentUser: QBUser? = null
private set
init {
callEntities = callManager.getCallEntities() as SortedSet<CallEntity>
currentDialog = callManager.getCurrentDialog()
currentUser = userManager.getCurrentUser()
}
override fun onStartView() {
if (!chatManager.isLoggedInChat()) {
loginToChat()
}
}
override fun onStopApp() {
chatManager.destroyChat()
}
private fun loginToChat() {
currentUser?.let {
chatManager.loginToChat(it, object : DomainCallback<Unit, Exception> {
override fun onSuccess(result: Unit, bundle: Bundle?) {
// empty
}
override fun onError(error: Exception) {
// empty
}
})
} ?: run {
liveData.setValue(Pair(ViewState.SHOW_LOGIN_SCREEN, null))
}
}
fun getCurrentUserId(): Int? {
return dbRepository.getCurrentUser()?.id
}
fun getCountParticipants(): Int {
return callEntities.size
}
override fun onResumeView() {
callManager.subscribeCallListener(callListener)
}
override fun onPauseView() {
callManager.unsubscribeCallListener(callListener)
}
private inner class CallListenerImpl(val tag: String) : CallListener {
override fun receivedLocalVideoTrack(userId: Int) {
// empty
}
override fun leftPublisher(userId: Int) {
liveData.setValue(Pair(ViewState.UPDATE_LIST, null))
}
override fun receivedRemoteVideoTrack(userId: Int) {
userManager.loadUserById(userId, object : DomainCallback<QBUser, Exception> {
override fun onSuccess(result: QBUser, bundle: Bundle?) {
val callEntity = callEntities.find { it.getUserId() == result.id }
callEntity?.setUserName(result.fullName)
liveData.setValue(Pair(ViewState.UPDATE_LIST, null))
}
override fun onError(error: Exception) {
liveData.setValue(Pair(com.quickblox.sample.conference.kotlin.presentation.screens.call.ViewState.ERROR, error.message))
}
})
}
override fun onStateChanged(session: ConferenceSession?, state: BaseSession.QBRTCSessionState) {
// empty
}
override fun onError(exception: Exception) {
liveData.setValue(Pair(ViewState.ERROR, exception.message))
}
override fun releaseSession(exception: Exception?) {
// empty
}
override fun setOnlineParticipants(count: Int) {
// empty
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return if (other is CallListenerImpl) {
tag == other.tag
} else {
false
}
}
override fun hashCode(): Int {
var hash = 1
hash = 31 * hash + tag.hashCode()
return hash
}
}
} | bsd-3-clause | 6a2373d4ce2320be6b2ef7a180d53e5a | 33.58042 | 147 | 0.64199 | 5.034623 | false | false | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/h5_help/H5Kit.kt | 1 | 1060 | package com.didichuxing.doraemonkit.kit.h5_help
import android.app.Activity
import android.content.Context
import com.didichuxing.doraemonkit.DoKit
import com.didichuxing.doraemonkit.R
import com.didichuxing.doraemonkit.kit.AbstractKit
import com.google.auto.service.AutoService
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/8/24-20:41
* 描 述:
* 修订历史:
* ================================================
*/
@AutoService(AbstractKit::class)
class H5Kit : AbstractKit() {
override val name: Int
get() = R.string.dk_kit_h5_help
override val icon: Int
get() = R.mipmap.dk_icon_h5help
override val isInnerKit: Boolean
get() = true
override fun onClickWithReturn(activity: Activity): Boolean {
DoKit.launchFloating(H5DoKitView::class)
return true
}
override fun onAppInit(context: Context?) {
}
override fun innerKitId(): String {
return "dokit_sdk_comm_ck_h5kit"
}
}
| apache-2.0 | 8071e465fa54e0952598a348a6d00855 | 23.731707 | 65 | 0.610454 | 3.783582 | false | false | false | false |
dafi/photoshelf | birthday/src/main/java/com/ternaryop/photoshelf/birthday/util/BirthdayUtils.kt | 1 | 3978 | package com.ternaryop.photoshelf.birthday.util
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import com.ternaryop.photoshelf.api.ApiManager
import com.ternaryop.photoshelf.api.birthday.Birthday
import com.ternaryop.photoshelf.api.birthday.FindParams
import com.ternaryop.photoshelf.api.birthday.getClosestPhotoByWidth
import com.ternaryop.photoshelf.birthday.R
import com.ternaryop.photoshelf.birthday.publisher.activity.BirthdayPublisherActivity
import com.ternaryop.photoshelf.birthday.util.notification.BirthdayNotificationBroadcastReceiver
import com.ternaryop.photoshelf.birthday.util.notification.notifyTodayBirthdays
import com.ternaryop.photoshelf.util.notification.notify
import com.ternaryop.tumblr.Tumblr
import com.ternaryop.tumblr.TumblrAltSize
import com.ternaryop.tumblr.draftPhotoPost
import com.ternaryop.tumblr.publishPhotoPost
import com.ternaryop.utils.bitmap.readBitmap
import com.ternaryop.utils.bitmap.savePng
import com.ternaryop.utils.date.dayOfMonth
import com.ternaryop.utils.date.month
import com.ternaryop.utils.date.year
import com.ternaryop.utils.date.yearsBetweenDates
import java.io.File
import java.net.URL
import java.util.Calendar
import java.util.Locale
private const val CAKE_IMAGE_SEPARATOR_HEIGHT = 10
suspend fun notifyBirthday(context: Context, blogName: String? = null) {
try {
val now = Calendar.getInstance(Locale.US)
val birthdayResult = ApiManager.birthdayService().findByDate(
FindParams(month = now.month + 1, dayOfMonth = now.dayOfMonth, blogName = blogName).toQueryMap()
).response
birthdayResult.birthdays?.notifyTodayBirthdays(context, now.year, BirthdayPublisherActivity::class.java)
} catch (t: Throwable) {
t.notify(context, "Error")
}
}
fun createBirthdayImageFile(cakeImage: Bitmap, birthday: Birthday, cacheDir: File): File {
return File(cacheDir, "birth-${birthday.name}.png").also { file ->
val imageUrl = checkNotNull(birthday.getClosestPhotoByWidth(TumblrAltSize.IMAGE_WIDTH_400)).url
file.savePng(createBirthdayBitmap(cakeImage, URL(imageUrl).readBitmap()))
}
}
fun Tumblr.createBirthdayPost(file: File, birthday: Birthday, blogName: String, publishAsDraft: Boolean) {
try {
if (publishAsDraft) {
draftPhotoPost(blogName, file.toURI(), getBirthdayCaption(birthday), "Birthday, ${birthday.name}")
} else {
publishPhotoPost(blogName, file.toURI(), getBirthdayCaption(birthday), "Birthday, ${birthday.name}")
}
} finally {
file.delete()
}
}
private fun createBirthdayBitmap(cake: Bitmap, celebrity: Bitmap): Bitmap {
val canvasWidth = celebrity.width
val canvasHeight = cake.height + CAKE_IMAGE_SEPARATOR_HEIGHT + celebrity.height
val config = celebrity.config ?: Bitmap.Config.ARGB_8888
val destBmp = Bitmap.createBitmap(canvasWidth, canvasHeight, config)
val canvas = Canvas(destBmp)
canvas.drawBitmap(cake, ((celebrity.width - cake.width) / 2).toFloat(), 0f, null)
canvas.drawBitmap(celebrity, 0f, (cake.height + CAKE_IMAGE_SEPARATOR_HEIGHT).toFloat(), null)
return destBmp
}
private fun getBirthdayCaption(birthday: Birthday): String {
val birthdate = birthday.birthdate ?: return "Unknown date for ${birthday.name}"
val age = birthdate.yearsBetweenDates()
// caption must not be localized
return "Happy ${age}th Birthday, ${birthday.name}!!"
}
suspend fun addBirthdate(context: Context, name: String) {
try {
val nameResult = ApiManager.birthdayService().getByName(name, true).response
if (nameResult.isNew) {
nameResult.birthday.birthdate?.let { birthdate ->
BirthdayNotificationBroadcastReceiver.notifyBirthdayAdded(context, name, birthdate)
}
}
} catch (t: Throwable) {
t.notify(context, name, context.resources.getString(R.string.birthday_add_error_ticker))
}
}
| mit | 772275efa63cb45c6923094187fb7071 | 40.873684 | 112 | 0.747109 | 4.105263 | false | false | false | false |
ken-kentan/student-portal-plus | app/src/main/java/jp/kentan/studentportalplus/ui/lectureinfo/detail/LectureInfoDetailActivity.kt | 1 | 3633 | package jp.kentan.studentportalplus.ui.lectureinfo.detail
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.text.parseAsHtml
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.snackbar.Snackbar
import dagger.android.AndroidInjection
import jp.kentan.studentportalplus.R
import jp.kentan.studentportalplus.databinding.ActivityLectureInfoDetailBinding
import jp.kentan.studentportalplus.ui.ViewModelFactory
import javax.inject.Inject
class LectureInfoDetailActivity : AppCompatActivity() {
companion object {
private const val EXTRA_ID = "ID"
fun createIntent(context: Context, id: Long) =
Intent(context, LectureInfoDetailActivity::class.java).apply {
putExtra(EXTRA_ID, id)
}
}
@Inject
lateinit var viewModelFactory: ViewModelFactory
private val viewModel by lazy(LazyThreadSafetyMode.NONE) {
ViewModelProvider(this, viewModelFactory).get(LectureInfoDetailViewModel::class.java)
}
private lateinit var binding: ActivityLectureInfoDetailBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_lecture_info_detail)
AndroidInjection.inject(this)
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.setLifecycleOwner(this)
binding.viewModel = viewModel
viewModel.subscribe()
viewModel.onActivityCreated(intent.getLongExtra(EXTRA_ID, -1))
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.share, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_share -> viewModel.onShareClick()
android.R.id.home -> finish()
}
return super.onOptionsItemSelected(item)
}
private fun LectureInfoDetailViewModel.subscribe() {
val activity = this@LectureInfoDetailActivity
showAttendNotDialog.observe(activity, Observer { subject ->
AlertDialog.Builder(activity)
.setTitle(R.string.title_confirm)
.setMessage(getString(R.string.text_unregister_confirm, subject).parseAsHtml())
.setPositiveButton(R.string.action_yes) { _, _ ->
viewModel.onAttendNotClick(subject)
}
.setNegativeButton(R.string.action_no, null)
.show()
})
snackbar.observe(activity, Observer { resId ->
Snackbar.make(binding.root, resId, Snackbar.LENGTH_SHORT)
.show()
})
indefiniteSnackbar.observe(activity, Observer { resId ->
val snackbar = Snackbar.make(binding.root, resId, Snackbar.LENGTH_INDEFINITE)
snackbar.setAction(R.string.action_close) { snackbar.dismiss() }
.show()
})
share.observe(activity, Observer { startActivity(it) })
errorNotFound.observe(activity, Observer {
Toast.makeText(activity, R.string.error_not_found, Toast.LENGTH_LONG).show()
finish()
})
}
}
| gpl-3.0 | 2985172a0df7d67867011cd346a5ffaf | 33.932692 | 99 | 0.679053 | 4.997249 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/AlphaColorParameter.kt | 1 | 2890 | /*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.parameters
import javafx.scene.paint.Color
import javafx.util.StringConverter
import uk.co.nickthecoder.paratask.ParameterException
import uk.co.nickthecoder.paratask.util.uncamel
class AlphaColorParameter(
name: String,
label: String = name.uncamel(),
description: String = "",
value: Color = Color.WHITE)
: CompoundParameter<Color>(name = name,
label = label,
description = description) {
val rgbP = ColorParameter(name + "_rgb", label = "", value = value)
val alphaP = DoubleParameter(name + "_alpha", label = "Alpha", value = value.opacity, minValue = 0.0, maxValue = 1.0)
.asSlider(DoubleParameter.SliderInfo(blockIncrement = 0.1, majorTickUnit = 0.5, minorTickCount = 5, snapToTicks = false))
override var value: Color
get() {
val rgb = rgbP.value
return Color(rgb.red, rgb.green, rgb.blue, alphaP.value ?: 1.0)
}
set(v) {
rgbP.value = v
alphaP.value = v.opacity
}
override val converter = object : StringConverter<Color>() {
override fun fromString(str: String): Color {
val trimmed = str.trim()
try {
val rgb = trimmed.substring(0, 7)
val alpha = trimmed.substring(7, 9)
return Color.web(rgb, Integer.parseInt(alpha, 16) / 255.0)
} catch (e: Exception) {
throw ParameterException(this@AlphaColorParameter, "Not a Color")
}
}
override fun toString(obj: Color): String {
val r = Math.round(obj.red * 255.0).toInt();
val g = Math.round(obj.green * 255.0).toInt()
val b = Math.round(obj.blue * 255.0).toInt()
val a = Math.round(obj.opacity * 255.0).toInt()
return String.format("#%02x%02x%02x%02x", r, g, b, a)
}
}
init {
addParameters(rgbP, alphaP)
asHorizontal(labelPosition = LabelPosition.TOP)
}
override fun toString() = "AlphaColor" + super.toString()
override fun copy() = AlphaColorParameter(name = name, label = label, description = description, value = value)
}
| gpl-3.0 | d2ee17a2b3173e441618330326e7ac2b | 33.819277 | 133 | 0.63737 | 4.053296 | false | false | false | false |
soniccat/android-taskmanager | storagemanager/src/main/java/com/example/alexeyglushkov/cachemanager/disk/serializer/DiskMetadataWriter.kt | 1 | 2040 | package com.example.alexeyglushkov.cachemanager.disk.serializer
import com.example.alexeyglushkov.cachemanager.disk.DiskStorageMetadata
import com.example.alexeyglushkov.streamlib.data_readers_and_writers.OutputStreamDataWriter
import com.example.alexeyglushkov.streamlib.progress.ProgressUpdater
import com.example.alexeyglushkov.tools.ExceptionTools
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.core.JsonGenerator
import java.io.IOException
import java.io.OutputStream
/**
* Created by alexeyglushkov on 11.09.16.
*/
class DiskMetadataWriter : OutputStreamDataWriter<DiskStorageMetadata?> {
private var stream: OutputStream? = null
override fun beginWrite(stream: OutputStream) {
ExceptionTools.throwIfNull(stream, "DiskMetadataReader.beginWrite: stream is null")
this.stream = stream
}
@Throws(IOException::class)
override fun closeWrite() {
ExceptionTools.throwIfNull(stream, "DiskMetadataReader.close: stream is null")
stream!!.close()
}
@Throws(IOException::class)
override fun write(metadata: DiskStorageMetadata) {
ExceptionTools.throwIfNull(stream, "DiskMetadataReader.write: stream is null")
val f = JsonFactory()
var g: JsonGenerator? = null
try {
g = f.createGenerator(stream)
g.writeStartObject()
g.writeNumberField("contentSize", metadata.contentSize)
g.writeNumberField("createTime", metadata.createTime)
g.writeNumberField("expireTime", metadata.expireTime)
val entryClass = metadata.entryClass
if (entryClass != null) {
g.writeStringField("entryClass", entryClass.name)
}
} finally {
if (g != null) {
try {
g.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
override fun setProgressUpdater(progressUpdater: ProgressUpdater) {}
} | mit | 12977ad9bc320b8e2aa36e037196530c | 36.109091 | 91 | 0.670098 | 5.049505 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/common/AbstractValueUsageTransformer.kt | 1 | 9361 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.common
import org.jetbrains.kotlin.backend.konan.ir.KonanSymbols
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.symbols.*
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.util.defaultType
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
/**
* Transforms expressions depending on the context they are used in.
*
* The transformations are defined with `IrExpression.use*` methods in this class,
* the most common are [useAs], [useAsStatement], [useInTypeOperator].
*
* TODO: the implementation is originally based on [org.jetbrains.kotlin.psi2ir.transformations.InsertImplicitCasts]
* and should probably be used as its base.
*
* TODO: consider making this visitor non-recursive to make it more general.
*/
internal abstract class AbstractValueUsageTransformer(
val builtIns: KotlinBuiltIns,
val symbols: KonanSymbols,
val irBuiltIns: IrBuiltIns
): IrElementTransformerVoid() {
protected open fun IrExpression.useAs(type: IrType): IrExpression = this
protected open fun IrExpression.useAsStatement(): IrExpression = this
protected open fun IrExpression.useInTypeOperator(operator: IrTypeOperator, typeOperand: IrType): IrExpression =
this
protected open fun IrExpression.useAsValue(value: IrValueDeclaration): IrExpression = this.useAs(value.type)
protected open fun IrExpression.useAsArgument(parameter: IrValueParameter): IrExpression =
this.useAsValue(parameter)
protected open fun IrExpression.useAsDispatchReceiver(expression: IrFunctionAccessExpression): IrExpression =
this.useAsArgument(expression.symbol.owner.dispatchReceiverParameter!!)
protected open fun IrExpression.useAsExtensionReceiver(expression: IrFunctionAccessExpression): IrExpression =
this.useAsArgument(expression.symbol.owner.extensionReceiverParameter!!)
protected open fun IrExpression.useAsValueArgument(expression: IrFunctionAccessExpression,
parameter: IrValueParameter
): IrExpression =
this.useAsArgument(parameter)
private fun IrExpression.useForVariable(variable: IrVariable): IrExpression =
this.useAsValue(variable)
private fun IrExpression.useForField(field: IrField): IrExpression =
this.useAs(field.type)
protected open fun IrExpression.useAsReturnValue(returnTarget: IrReturnTargetSymbol): IrExpression =
when (returnTarget) {
is IrSimpleFunctionSymbol -> this.useAs(returnTarget.owner.returnType)
is IrConstructorSymbol -> this.useAs(irBuiltIns.unitType)
is IrReturnableBlockSymbol -> this.useAs(returnTarget.owner.type)
else -> error(returnTarget)
}
protected open fun IrExpression.useAsResult(enclosing: IrExpression): IrExpression =
this.useAs(enclosing.type)
override fun visitPropertyReference(expression: IrPropertyReference): IrExpression {
TODO()
}
override fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference): IrExpression {
TODO()
}
override fun visitFunctionReference(expression: IrFunctionReference): IrExpression {
TODO()
}
override fun visitFunctionAccess(expression: IrFunctionAccessExpression): IrExpression {
expression.transformChildrenVoid(this)
with(expression) {
dispatchReceiver = dispatchReceiver?.useAsDispatchReceiver(expression)
extensionReceiver = extensionReceiver?.useAsExtensionReceiver(expression)
for (index in symbol.owner.valueParameters.indices) {
val argument = getValueArgument(index) ?: continue
val parameter = symbol.owner.valueParameters[index]
putValueArgument(index, argument.useAsValueArgument(expression, parameter))
}
}
return expression
}
override fun visitBlockBody(body: IrBlockBody): IrBody {
body.transformChildrenVoid(this)
body.statements.forEachIndexed { i, irStatement ->
if (irStatement is IrExpression) {
body.statements[i] = irStatement.useAsStatement()
}
}
return body
}
override fun visitContainerExpression(expression: IrContainerExpression): IrExpression {
expression.transformChildrenVoid(this)
if (expression.statements.isEmpty()) {
return expression
}
val lastIndex = expression.statements.lastIndex
expression.statements.forEachIndexed { i, irStatement ->
if (irStatement is IrExpression) {
expression.statements[i] =
if (i == lastIndex)
irStatement.useAsResult(expression)
else
irStatement.useAsStatement()
}
}
return expression
}
override fun visitReturn(expression: IrReturn): IrExpression {
expression.transformChildrenVoid(this)
expression.value = expression.value.useAsReturnValue(expression.returnTargetSymbol)
return expression
}
override fun visitSetVariable(expression: IrSetVariable): IrExpression {
expression.transformChildrenVoid(this)
expression.value = expression.value.useForVariable(expression.symbol.owner)
return expression
}
override fun visitSetField(expression: IrSetField): IrExpression {
expression.transformChildrenVoid(this)
expression.value = expression.value.useForField(expression.symbol.owner)
return expression
}
override fun visitField(declaration: IrField): IrStatement {
declaration.transformChildrenVoid(this)
declaration.initializer?.let {
it.expression = it.expression.useForField(declaration)
}
return declaration
}
override fun visitVariable(declaration: IrVariable): IrVariable {
declaration.transformChildrenVoid(this)
declaration.initializer = declaration.initializer?.useForVariable(declaration)
return declaration
}
override fun visitWhen(expression: IrWhen): IrExpression {
expression.transformChildrenVoid(this)
for (irBranch in expression.branches) {
irBranch.condition = irBranch.condition.useAs(irBuiltIns.booleanType)
irBranch.result = irBranch.result.useAsResult(expression)
}
return expression
}
override fun visitLoop(loop: IrLoop): IrExpression {
loop.transformChildrenVoid(this)
loop.condition = loop.condition.useAs(irBuiltIns.booleanType)
loop.body = loop.body?.useAsStatement()
return loop
}
override fun visitThrow(expression: IrThrow): IrExpression {
expression.transformChildrenVoid(this)
expression.value = expression.value.useAs(symbols.throwable.owner.defaultType)
return expression
}
override fun visitTry(aTry: IrTry): IrExpression {
aTry.transformChildrenVoid(this)
aTry.tryResult = aTry.tryResult.useAsResult(aTry)
for (aCatch in aTry.catches) {
aCatch.result = aCatch.result.useAsResult(aTry)
}
aTry.finallyExpression = aTry.finallyExpression?.useAsStatement()
return aTry
}
override fun visitVararg(expression: IrVararg): IrExpression {
expression.transformChildrenVoid(this)
expression.elements.forEachIndexed { i, element ->
when (element) {
is IrSpreadElement ->
element.expression = element.expression.useAs(expression.type)
is IrExpression ->
expression.putElement(i, element.useAs(expression.varargElementType))
}
}
return expression
}
override fun visitTypeOperator(expression: IrTypeOperatorCall): IrExpression {
expression.transformChildrenVoid(this)
expression.argument = expression.argument.useInTypeOperator(expression.operator, expression.typeOperand)
return expression
}
override fun visitFunction(declaration: IrFunction): IrStatement {
declaration.transformChildrenVoid(this)
declaration.valueParameters.forEach { parameter ->
val defaultValue = parameter.defaultValue
if (defaultValue is IrExpressionBody) {
defaultValue.expression = defaultValue.expression.useAsArgument(parameter)
}
}
declaration.body?.let {
if (it is IrExpressionBody) {
it.expression = it.expression.useAsReturnValue(declaration.symbol)
}
}
return declaration
}
// TODO: IrStringConcatenation, IrEnumEntry?
}
| apache-2.0 | 83116334aac577dd1de09e0573a6520a | 33.799257 | 116 | 0.690204 | 5.548903 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-github/src/test/java/net/nemerosa/ontrack/extension/github/app/GitHubAppRateLimitMetricsTest.kt | 1 | 2639 | package net.nemerosa.ontrack.extension.github.app
import io.micrometer.core.instrument.MeterRegistry
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import net.nemerosa.ontrack.extension.github.GitHubConfigurationProperties
import net.nemerosa.ontrack.extension.github.client.OntrackGitHubClientFactory
import net.nemerosa.ontrack.extension.github.model.GitHubEngineConfiguration
import net.nemerosa.ontrack.extension.github.service.GitHubConfigurationService
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class GitHubAppRateLimitMetricsTest {
private lateinit var gitHubConfigurationProperties: GitHubConfigurationProperties
private lateinit var gitHubConfigurationService: GitHubConfigurationService
private lateinit var gitHubClientFactory: OntrackGitHubClientFactory
private lateinit var meterRegistry: MeterRegistry
private lateinit var metrics: GitHubAppRateLimitMetrics
@BeforeEach
fun init() {
gitHubConfigurationProperties = GitHubConfigurationProperties()
gitHubConfigurationService = mockk(relaxed = true)
gitHubClientFactory = mockk()
meterRegistry = mockk(relaxed = true)
metrics = GitHubAppRateLimitMetrics(
gitHubConfigurationProperties,
gitHubConfigurationService,
gitHubClientFactory,
meterRegistry,
)
}
@Test
fun `Registration at startup by default`() {
withConfiguration {
metrics.start()
}
verify {
gitHubConfigurationService.addConfigurationServiceListener(metrics)
}
}
@Test
fun `Registration at startup with explicit flag`() {
gitHubConfigurationProperties.metrics.enabled = true
withConfiguration {
metrics.start()
}
verify {
gitHubConfigurationService.addConfigurationServiceListener(metrics)
}
}
@Test
fun `No registration at startup`() {
gitHubConfigurationProperties.metrics.enabled = false
withConfiguration {
metrics.start()
}
verify(exactly = 0) {
gitHubConfigurationService.addConfigurationServiceListener(metrics)
}
}
private fun withConfiguration(
code: () -> Unit,
) {
val configuration = GitHubEngineConfiguration(
name = "test",
url = null,
oauth2Token = "xxx"
)
every {
gitHubConfigurationService.configurations
} returns listOf(
configuration
)
code()
}
} | mit | dffd72e1bd86de43b14a89c5d34264bf | 29 | 85 | 0.685866 | 5.812775 | false | true | false | false |
Plastix/Kotlin-Android-Boilerplate | app/src/main/kotlin/io/github/plastix/kotlinboilerplate/extensions/ViewExtensions.kt | 1 | 1758 | package io.github.plastix.kotlinboilerplate.extensions
import android.content.Context
import android.support.annotation.ColorInt
import android.support.annotation.StringRes
import android.support.design.widget.Snackbar
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.squareup.picasso.Picasso
var View.isVisible: Boolean
get() = visibility == View.VISIBLE
set(value) {
visibility = if(value) View.VISIBLE else View.GONE
}
fun Context.inflateLayout(layoutResId: Int): View {
return inflateView(this, layoutResId, null, false)
}
fun Context.inflateLayout(layoutResId: Int, parent: ViewGroup): View {
return inflateLayout(layoutResId, parent, true)
}
fun Context.inflateLayout(layoutResId: Int, parent: ViewGroup, attachToRoot: Boolean): View {
return inflateView(this, layoutResId, parent, attachToRoot)
}
private fun inflateView(context: Context, layoutResId: Int, parent: ViewGroup?, attachToRoot: Boolean): View {
return LayoutInflater.from(context).inflate(layoutResId, parent, attachToRoot)
}
fun ImageView.loadImage(url: String) {
Picasso.with(context).load(url).into(this)
}
fun View.showSnackbar(message: String, length: Int = Snackbar.LENGTH_LONG, f: (Snackbar.() -> Unit) = {}) {
val snack = Snackbar.make(this, message, length)
snack.f()
snack.show()
}
fun View.showSnackbar(@StringRes message: Int, length: Int = Snackbar.LENGTH_LONG, f: (Snackbar.() -> Unit) = {}) {
showSnackbar(resources.getString(message), length, f)
}
fun Snackbar.action(action: String, @ColorInt color: Int? = null, listener: (View) -> Unit) {
setAction(action, listener)
color?.let { setActionTextColor(color) }
}
| mit | 3f0b0aa2d5a3545670a9494c80c9ae1e | 32.169811 | 115 | 0.745165 | 3.977376 | false | false | false | false |
goodwinnk/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/migLayout/MigLayoutRow.kt | 1 | 10254 | // 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.migLayout
import com.intellij.CommonBundle
import com.intellij.icons.AllIcons
import com.intellij.ide.ui.laf.VisualPaddingsProvider
import com.intellij.openapi.ui.OnePixelDivider
import com.intellij.openapi.ui.panel.ComponentPanelBuilder
import com.intellij.ui.SeparatorComponent
import com.intellij.ui.components.Label
import com.intellij.ui.layout.*
import com.intellij.util.SmartList
import net.miginfocom.layout.CC
import java.awt.Component
import javax.swing.*
import javax.swing.border.LineBorder
internal class MigLayoutRow(private val parent: MigLayoutRow?,
private val componentConstraints: MutableMap<Component, CC>,
override val builder: MigLayoutBuilder,
val labeled: Boolean = false,
val noGrid: Boolean = false,
private val buttonGroup: ButtonGroup? = null,
private val indent: Int /* level number (nested rows) */) : Row() {
val components = SmartList<JComponent>()
var rightIndex = Int.MAX_VALUE
private var lastComponentConstraintsWithSplit: CC? = null
private var columnIndex = -1
internal var subRows: MutableList<MigLayoutRow>? = null
private set
var gapAfter: String? = null
private set
private var componentIndexWhenCellModeWasEnabled = -1
private val spacing: SpacingConfiguration
get() = builder.spacing
override var enabled: Boolean = true
set(value) {
if (field == value) {
return
}
field = value
for (c in components) {
c.isEnabled = value
}
}
override var visible: Boolean = true
set(value) {
if (field == value) {
return
}
field = value
for (c in components) {
c.isVisible = value
}
}
override var subRowsEnabled: Boolean = true
set(value) {
if (field == value) {
return
}
field = value
subRows?.forEach { it.enabled = value }
}
override var subRowsVisible: Boolean = true
set(value) {
if (field == value) {
return
}
field = value
subRows?.forEach { it.visible = value }
}
internal val isLabeledIncludingSubRows: Boolean
get() = labeled || (subRows?.any { it.isLabeledIncludingSubRows } ?: false)
internal val columnIndexIncludingSubRows: Int
get() = Math.max(columnIndex, subRows?.maxBy { it.columnIndex }?.columnIndex ?: 0)
fun createChildRow(label: JLabel? = null, buttonGroup: ButtonGroup? = null, separated: Boolean = false, noGrid: Boolean = false): MigLayoutRow {
if (subRows == null) {
subRows = SmartList()
}
val subRows = subRows!!
if (separated) {
val row = MigLayoutRow(this, componentConstraints, builder, indent = indent, noGrid = true)
subRows.add(row)
row.apply {
val separatorComponent = SeparatorComponent(0, OnePixelDivider.BACKGROUND, null)
val cc = CC()
cc.vertical.gapBefore = gapToBoundSize(spacing.largeVerticalGap, false)
cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap * 2, false)
componentConstraints.put(separatorComponent, cc)
addComponent(separatorComponent, lazyOf(cc))
}
}
val row = MigLayoutRow(this, componentConstraints, builder,
labeled = label != null,
noGrid = noGrid,
indent = indent + computeChildRowIndent(),
buttonGroup = buttonGroup)
subRows.add(row)
if (label != null) {
row.addComponent(label)
}
return row
}
// cell mode not tested with "gear" button, wait first user request
override fun setCellMode(value: Boolean, isVerticalFlow: Boolean) {
if (value) {
assert(componentIndexWhenCellModeWasEnabled == -1)
componentIndexWhenCellModeWasEnabled = components.size
}
else {
val firstComponentIndex = componentIndexWhenCellModeWasEnabled
componentIndexWhenCellModeWasEnabled = -1
// do not add split if cell empty or contains the only component
if ((components.size - firstComponentIndex) > 1) {
val component = components.get(firstComponentIndex)
val cc = componentConstraints.getOrPut(component) { CC() }
cc.split(components.size - firstComponentIndex)
if (isVerticalFlow) {
cc.flowY()
// because when vertical buttons placed near scroll pane, it wil be centered by baseline (and baseline not applicable for grow elements, so, will be centered)
cc.alignY("top")
}
}
}
}
private fun computeChildRowIndent(): Int {
val firstComponent = components.firstOrNull() ?: return 0
if (firstComponent is JRadioButton || firstComponent is JCheckBox) {
return getCommentLeftInset(firstComponent)
}
else {
return spacing.horizontalGap * 3
}
}
private fun getCommentLeftInset(component: JComponent): Int {
if (component is JTextField) {
// 1px border, better to indent comment text
return 1
}
// as soon as ComponentPanelBuilder will also compensate visual paddings (instead of compensating on LaF level),
// this logic will be moved into computeCommentInsets
val componentBorderVisualLeftPadding = when {
spacing.isCompensateVisualPaddings -> {
val border = component.border
if (border is VisualPaddingsProvider) {
border.getVisualPaddings(component)?.left ?: 0
}
else {
0
}
}
else -> 0
}
val insets = ComponentPanelBuilder.computeCommentInsets(component, true)
return insets.left - componentBorderVisualLeftPadding
}
override operator fun JComponent.invoke(vararg constraints: CCFlags, gapLeft: Int, growPolicy: GrowPolicy?, comment: String?) {
addComponent(this, constraints.create()?.let { lazyOf(it) } ?: lazy { CC() }, gapLeft, growPolicy, comment)
}
// separate method to avoid JComponent as a receiver
private fun addComponent(component: JComponent, cc: Lazy<CC> = lazy { CC() }, gapLeft: Int = 0, growPolicy: GrowPolicy? = null, comment: String? = null) {
components.add(component)
if (!shareCellWithPreviousComponentIfNeed(component, cc)) {
// increase column index if cell mode not enabled or it is a first component of cell
if (componentIndexWhenCellModeWasEnabled == -1 || componentIndexWhenCellModeWasEnabled == (components.size - 1)) {
columnIndex++
}
}
if (labeled && components.size == 2 && component.border is LineBorder) {
componentConstraints.get(components.first())?.vertical?.gapBefore = builder.defaultComponentConstraintCreator.vertical1pxGap
}
if (comment != null && comment.isNotEmpty()) {
gapAfter = "${spacing.commentVerticalTopGap}px!"
val isParentRowLabeled = labeled
// create comment in a new sibling row (developer is still able to create sub rows because rows is not stored in a flat list)
parent!!.createChildRow().apply {
val commentComponent = ComponentPanelBuilder.createCommentComponent(comment, true)
val commentComponentCC = CC()
addComponent(commentComponent, lazyOf(commentComponentCC))
commentComponentCC.horizontal.gapBefore = gapToBoundSize(getCommentLeftInset(component), true)
if (isParentRowLabeled) {
commentComponentCC.skip()
}
componentConstraints.put(commentComponent, commentComponentCC)
}
}
if (buttonGroup != null && component is JToggleButton) {
buttonGroup.add(component)
}
builder.defaultComponentConstraintCreator.createComponentConstraints(cc, component, gapLeft = gapLeft, growPolicy = growPolicy)
if (!noGrid && indent > 0 && components.size == 1) {
cc.value.horizontal.gapBefore = gapToBoundSize(indent, true)
}
// if this row is not labeled and previous row is labeled and component is a "Remember" checkbox, skip one column (since this row doesn't have a label)
if (!labeled && components.size == 1 && component is JCheckBox) {
val siblings = parent!!.subRows
if (siblings != null && siblings.size > 1 && siblings.get(siblings.size - 2).labeled && component.text == CommonBundle.message("checkbox.remember.password")) {
cc.value.skip(1)
}
}
// MigLayout doesn't check baseline if component has grow
if (labeled && component is JScrollPane && component.viewport.view is JTextArea) {
val labelCC = componentConstraints.getOrPut(components.get(0)) { CC() }
labelCC.alignY("top")
val labelTop = component.border?.getBorderInsets(component)?.top ?: 0
if (labelTop != 0) {
labelCC.vertical.gapBefore = gapToBoundSize(labelTop, false)
}
}
if (cc.isInitialized()) {
componentConstraints.put(component, cc.value)
}
}
private fun shareCellWithPreviousComponentIfNeed(component: JComponent, componentCC: Lazy<CC>): Boolean {
if (components.size > 1 && component is JLabel && component.icon === AllIcons.General.GearPlain) {
componentCC.value.horizontal.gapBefore = builder.defaultComponentConstraintCreator.horizontalUnitSizeGap
if (lastComponentConstraintsWithSplit == null) {
val prevComponent = components.get(components.size - 2)!!
var cc = componentConstraints.get(prevComponent)
if (cc == null) {
cc = CC()
componentConstraints.set(prevComponent, cc)
}
cc.split++
lastComponentConstraintsWithSplit = cc
}
else {
lastComponentConstraintsWithSplit!!.split++
}
return true
}
else {
lastComponentConstraintsWithSplit = null
return false
}
}
override fun alignRight() {
if (rightIndex != Int.MAX_VALUE) {
throw IllegalStateException("right allowed only once")
}
rightIndex = components.size
}
override fun createRow(label: String?): Row {
return createChildRow(label = label?.let { Label(it) })
}
} | apache-2.0 | 730b6ca8b42574b4d1e7a02ca0d9c109 | 34.484429 | 168 | 0.664424 | 4.859716 | false | false | false | false |
hummatli/MAHAds | app-cross-promoter/src/main/java/com/mobapphome/appcrosspromoter/tools/Updater.kt | 2 | 5300 | package com.mobapphome.appcrosspromoter.tools
import android.os.AsyncTask
import android.support.v4.app.FragmentActivity
import android.util.Log
import com.mobapphome.appcrosspromoter.ACPController
import com.mobapphome.appcrosspromoter.ACPDlgExit
import com.mobapphome.appcrosspromoter.ACPDlgPrograms
import java.io.IOException
object Updater {
private var loading = false
fun updateProgramList(activity: FragmentActivity, urls: Urls) {
Log.i(Constants.LOG_TAG_MAH_ADS, "Update info called , loading = " + loading)
if (loading) {
Log.i(Constants.LOG_TAG_MAH_ADS, "Accept_3")
Log.i(Constants.LOG_TAG_MAH_ADS, "Loading")
return
}
val fragDlgPrograms = activity.supportFragmentManager
.findFragmentByTag(Constants.TAG_MAH_ADS_DLG_PROGRAMS) as ACPDlgPrograms?
if (fragDlgPrograms != null
&& fragDlgPrograms.isVisible
&& !fragDlgPrograms.isRemoving) {
fragDlgPrograms.startLoading()
}
object : AsyncTask<String, Void, MAHRequestResult>() {
override fun doInBackground(vararg args: String): MAHRequestResult {
Log.i(Constants.LOG_TAG_MAH_ADS, "inside of doInBackground , loading = " + loading)
//Setting loading to true
loading = true
//Read from cache
var requestResult = HttpUtils.jsonToProgramList(readStringFromCache(activity))
//Here we filter and set ACPController for first time from cache
filterMAHRequestResult(activity, requestResult)
ACPController.mahRequestResult = requestResult
try {
val myVersion = getVersionFromLocal(activity)
val currVersion = HttpUtils.requestProgramsVersion(activity, args[0])
Log.i(Constants.LOG_TAG_MAH_ADS, "Version from base $myVersion Version from web = $currVersion")
Log.i(Constants.LOG_TAG_MAH_ADS, "program list url = " + args[1])
//Ceck version to see are there any new verion in the web
if (myVersion == currVersion) {
//Read from cache if the verion has not changed
//requestResult = HttpUtils.jsonToProgramList(Utils.readStringFromCache(activity));
if (requestResult.programsTotal.size == 0
|| requestResult.resultState == MAHRequestResult.ResultState.ERR_JSON_IS_NULL_OR_EMPTY
|| requestResult.resultState == MAHRequestResult.ResultState.ERR_JSON_HAS_TOTAL_ERROR) {
//Read again from the web if upper errors has apears
requestResult = HttpUtils.requestPrograms(activity, args[1])
Log.i(Constants.LOG_TAG_MAH_ADS, "Programs red from web, In reattemt case")
}
Log.i(Constants.LOG_TAG_MAH_ADS, "Programs red from local, In version equal case")
} else {
//Read from the web if versions are different
requestResult = HttpUtils.requestPrograms(activity, args[1])
Log.i(Constants.LOG_TAG_MAH_ADS, "Programs red from web, In version different case")
}
//In this place we filter mahrequest from web
filterMAHRequestResult(activity, requestResult)
} catch (e: IOException) {
Log.i(Constants.LOG_TAG_MAH_ADS, "Accept_6")
Log.i(Constants.LOG_TAG_MAH_ADS, " " + e.message)
Log.i(Constants.LOG_TAG_MAH_ADS, "Programs red from local, In exception case")
}
Log.i(Constants.LOG_TAG_MAH_ADS, "Programs count = " + requestResult.programsTotal.size)
Log.i(Constants.LOG_TAG_MAH_ADS, "Request Result state" + requestResult.resultState)
return requestResult
}
override fun onPostExecute(mahRequestResult: MAHRequestResult?) {
super.onPostExecute(mahRequestResult)
Log.i(Constants.LOG_TAG_MAH_ADS, "MAHRequestResult isReadFromWeb = " + mahRequestResult!!.isReadFromWeb)
//It calls twise. Needs to solve. I can not use this "mahRequestResult.isReadFromWeb".
// Cause in first time needs to show retry button. if I check it does not show
fragDlgPrograms?.setUI(mahRequestResult, false)
val fragDlgExit = activity.supportFragmentManager.findFragmentByTag(Constants.TAG_MAH_ADS_DLG_EXIT) as ACPDlgExit?
if (fragDlgExit != null && mahRequestResult.isReadFromWeb ) {
fragDlgExit.setUi(mahRequestResult)
}
//In this place we set ACPController's mahrequest from web
ACPController.mahRequestResult = mahRequestResult
//Setting loading to false
loading = false
Log.i(Constants.LOG_TAG_MAH_ADS, "Set loading to = " + loading)
}
}.execute(urls.urlForProgramVersion, urls.urlForProgramList)
}
}
| apache-2.0 | ed79d9c7db8804f6d64a1aeb868f1a47 | 48.074074 | 130 | 0.598679 | 4.907407 | false | false | false | false |
material-components/material-components-android-motion-codelab | app/src/main/java/com/materialstudies/reply/ui/home/ReboundingSwipeActionCallback.kt | 1 | 5654 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.ui.home
import android.graphics.Canvas
import android.view.View
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs
import kotlin.math.ln
// The intensity at which dX of a swipe should be decreased as we approach the swipe
// threshold.
private const val swipeReboundingElasticity = 0.8F
// The 'true' percentage of total swipe distance needed to consider a view as 'swiped'. This
// is used in favor of getSwipeThreshold since that has been overridden to return an impossible
// to reach value.
private const val trueSwipeThreshold = 0.4F
class ReboundingSwipeActionCallback : ItemTouchHelper.SimpleCallback(
0,
ItemTouchHelper.RIGHT
) {
interface ReboundableViewHolder {
/**
* A view from the view holder which should be translated for swipe events.
*/
val reboundableView: View
/**
* Called as a view holder is actively being swiped/rebounded.
*
* @param currentSwipePercentage The total percentage the view has been swiped.
* @param swipeThreshold The percentage needed to consider a swipe as "rebounded"
* or "swiped"
* @param currentTargetHasMetThresholdOnce Whether or not during a contiguous interaction
* with a single view holder, the swipe percentage has ever been greater than the swipe
* threshold.
*/
fun onReboundOffsetChanged(
currentSwipePercentage: Float,
swipeThreshold: Float,
currentTargetHasMetThresholdOnce: Boolean
)
/**
* Called once all interaction (user initiated swiping and animations) has ended and this
* view holder has been swiped passed the swipe threshold.
*/
fun onRebounded()
}
// Track the view holder currently being swiped.
private var currentTargetPosition: Int = -1
private var currentTargetHasMetThresholdOnce: Boolean = false
// Never dismiss.
override fun getSwipeThreshold(viewHolder: RecyclerView.ViewHolder): Float = Float.MAX_VALUE
// Never dismiss.
override fun getSwipeVelocityThreshold(defaultValue: Float): Float {
return Float.MAX_VALUE
}
// Never dismiss.
override fun getSwipeEscapeVelocity(defaultValue: Float): Float {
return Float.MAX_VALUE
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean = false
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
// After animations to replace view have run, notify viewHolders that they have
// been swiped. This waits for animations to finish so RecyclerView's DefaultItemAnimator
// doesn't try to run updating animations while swipe animations are still running.
if (currentTargetHasMetThresholdOnce && viewHolder is ReboundableViewHolder){
currentTargetHasMetThresholdOnce = false
viewHolder.onRebounded()
}
super.clearView(recyclerView, viewHolder)
}
override fun onChildDraw(
c: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean
) {
if (viewHolder !is ReboundableViewHolder) return
if (currentTargetPosition != viewHolder.adapterPosition) {
currentTargetPosition = viewHolder.adapterPosition
currentTargetHasMetThresholdOnce = false
}
val itemView = viewHolder.itemView
val currentSwipePercentage = abs(dX) / itemView.width
viewHolder.onReboundOffsetChanged(
currentSwipePercentage,
trueSwipeThreshold,
currentTargetHasMetThresholdOnce
)
translateReboundingView(itemView, viewHolder, dX)
if (currentSwipePercentage >= trueSwipeThreshold &&
!currentTargetHasMetThresholdOnce) {
currentTargetHasMetThresholdOnce = true
}
}
private fun translateReboundingView(
itemView: View,
viewHolder: ReboundableViewHolder,
dX: Float
) {
// Progressively decrease the amount by which the view is translated to give a 'spring'
// affect to the item.
val swipeDismissDistanceHorizontal = itemView.width * trueSwipeThreshold
val dragFraction = ln(
(1 + (dX / swipeDismissDistanceHorizontal)).toDouble()) / ln(3.toDouble()
)
val dragTo = dragFraction * swipeDismissDistanceHorizontal *
swipeReboundingElasticity
viewHolder.reboundableView.translationX = dragTo.toFloat()
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// Do nothing. Overriding getSwipeThreshold to an impossible number means this will
// never be called.
}
} | apache-2.0 | 43272f39ff0b23d2f1a8f61c0076bebe | 35.483871 | 97 | 0.689777 | 5.298969 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge3d/internal/InternalExt.kt | 1 | 2284 | package com.soywiz.korge3d.internal
import com.soywiz.kds.*
import com.soywiz.kmem.*
import com.soywiz.korma.geom.*
import kotlin.native.concurrent.*
internal fun <T : Any> Map<String, T>.toFast() = FastStringMap<T>().apply {
@Suppress("MapGetWithNotNullAssertionOperator")
for (k in [email protected]) {
this[k] = this@toFast[k]!!
}
}
internal operator fun Vector3D.get(char: Char): Float = when (char) {
'x', 'r' -> this[0]
'y', 'g' -> this[1]
'z', 'b' -> this[2]
'w', 'a' -> this[3]
'0' -> 0f
'1' -> 1f
else -> Float.NaN
}
internal fun Vector3D.swizzle(name: String, input: Vector3D = this): Vector3D {
val x = name.getOrElse(0) { '0' }
val y = name.getOrElse(1) { '0' }
val z = name.getOrElse(2) { '0' }
val w = name.getOrElse(3) { '1' }
return this.setTo(input[x], input[y], input[z], input[w])
}
internal operator fun Vector3D.get(name: String): Vector3D = Vector3D().copyFrom(this).swizzle(name)
@ThreadLocal
internal val vector3DTemps = Vector3DTemps()
internal class Vector3DTemps {
@PublishedApi
internal var pos = 0
@PublishedApi
internal val items = arrayListOf<Vector3D>(Vector3D(), Vector3D(), Vector3D())
fun alloc(): Vector3D {
val npos = pos++
return if (npos < items.size) {
items[npos]
} else {
val item = Vector3D()
items.add(item)
item
}
}
inline operator fun <T> invoke(callback: Vector3DTemps.() -> T): T {
val oldPos = pos
try {
return callback()
} finally {
pos = oldPos
}
}
operator fun Vector3D.plus(that: Vector3D) = alloc().setToFunc { this[it] + that[it] }
operator fun Vector3D.minus(that: Vector3D) = alloc().setToFunc { this[it] - that[it] }
}
internal fun FloatArrayList.toFBuffer(): FBuffer = toFloatArray().toFBuffer()
internal fun FloatArray.toFBuffer(): FBuffer =
FBuffer.alloc(this.size * 4).also { it.setAlignedArrayFloat32(0, this, 0, this.size) }
internal fun IntArrayList.toFBuffer(): FBuffer = toIntArray().toFBuffer()
internal fun IntArray.toFBuffer():FBuffer =
FBuffer.alloc(this.size * 4).also { it.setAlignedArrayInt32(0, this, 0, this.size) }
internal fun ShortArrayList.toFBuffer(): FBuffer = toShortArray().toFBuffer()
internal fun ShortArray.toFBuffer():FBuffer =
FBuffer.alloc(this.size * 2).also { it.setAlignedArrayInt16(0, this, 0, this.size) }
| apache-2.0 | 4ba9c2e35b0cab74a600e7875b83f94d | 27.911392 | 100 | 0.680385 | 2.883838 | false | false | false | false |
jitsi/jicofo | jicofo/src/test/kotlin/org/jitsi/jicofo/conference/source/SourceSignalingTest.kt | 1 | 11534 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jicofo.conference.source
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.collections.shouldBeEmpty
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import org.jitsi.jicofo.conference.AddOrRemove.Add
import org.jitsi.jicofo.conference.AddOrRemove.Remove
import org.jitsi.jicofo.conference.SourceSignaling
import org.jitsi.utils.MediaType
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
class SourceSignalingTest : ShouldSpec() {
override fun isolationMode() = IsolationMode.InstancePerLeaf
init {
val e1 = "endpoint1"
val e1a = Source(1, MediaType.AUDIO)
val e1v = Source(11, MediaType.VIDEO)
val s1 = ConferenceSourceMap(e1 to EndpointSourceSet(setOf(e1a, e1v))).unmodifiable
val e2 = "endpoint2"
val e2a = Source(2, MediaType.AUDIO)
val e2v = Source(22, MediaType.VIDEO)
val s2 = ConferenceSourceMap(e2 to EndpointSourceSet(setOf(e2a, e2v))).unmodifiable
val e2a2 = Source(222, MediaType.AUDIO)
val e2v2 = Source(2222, MediaType.VIDEO)
val s2new = ConferenceSourceMap(e2 to EndpointSourceSet(setOf(e2a2, e2v2))).unmodifiable
val e3 = "endpoint3"
val e3a = Source(3, MediaType.AUDIO)
val s3 = ConferenceSourceMap(e3 to EndpointSourceSet(e3a)).unmodifiable
val e4 = "endpoint4"
val e4a1 = Source(4, MediaType.AUDIO)
val e4v1a = Source(43, MediaType.VIDEO, name = "e4-v1")
val e4v1b = Source(44, MediaType.VIDEO, name = "e4-v1")
val e4v1c = Source(45, MediaType.VIDEO, name = "e4-v1")
val e4v1a_r = Source(53, MediaType.VIDEO, name = "e4-v1")
val e4v1b_r = Source(54, MediaType.VIDEO, name = "e4-v1")
val e4v1c_r = Source(55, MediaType.VIDEO, name = "e4-v1")
val e4vgroups = setOf(
SsrcGroup(SsrcGroupSemantics.Sim, listOf(43, 44, 45)),
SsrcGroup(SsrcGroupSemantics.Fid, listOf(43, 53)),
SsrcGroup(SsrcGroupSemantics.Fid, listOf(44, 54)),
SsrcGroup(SsrcGroupSemantics.Fid, listOf(45, 55))
)
val e4ss1a = Source(46, MediaType.VIDEO, name = "e4-ss1", videoType = VideoType.Desktop)
val e4ss1b = Source(47, MediaType.VIDEO, name = "e4-ss1", videoType = VideoType.Desktop)
val e4ss1c = Source(48, MediaType.VIDEO, name = "e4-ss1", videoType = VideoType.Desktop)
val s4audio = ConferenceSourceMap(e4 to EndpointSourceSet(e4a1))
val s4video = ConferenceSourceMap(
e4 to EndpointSourceSet(
setOf(e4v1a, e4v1b, e4v1c, e4v1a_r, e4v1b_r, e4v1c_r),
e4vgroups
)
)
val s4ss = ConferenceSourceMap(
e4 to EndpointSourceSet(
setOf(e4ss1a, e4ss1b, e4ss1c),
setOf()
)
)
val e4sources = setOf(e4a1, e4v1a, e4v1b, e4v1c, e4ss1a, e4ss1b, e4ss1c)
val e4groups = setOf(
SsrcGroup(SsrcGroupSemantics.Sim, listOf(43, 44, 45), MediaType.VIDEO),
SsrcGroup(SsrcGroupSemantics.Sim, listOf(46, 47, 48), MediaType.VIDEO)
)
val s4 = ConferenceSourceMap(e4 to EndpointSourceSet(e4sources, e4groups))
context("Queueing remote sources") {
val sourceSignaling = SourceSignaling()
sourceSignaling.update().shouldBeEmpty()
context("Resetting") {
sourceSignaling.addSources(s1)
sourceSignaling.reset(ConferenceSourceMap())
sourceSignaling.update().shouldBeEmpty()
sourceSignaling.addSources(s1)
sourceSignaling.reset(s2)
sourceSignaling.update().shouldBeEmpty()
}
context("Adding a single source") {
sourceSignaling.addSources(s1)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources.toMap() shouldBe s1.toMap()
}
}
context("Adding multiple sources") {
// Consecutive source-adds should be merged.
sourceSignaling.addSources(s1)
sourceSignaling.addSources(s2)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources.toMap() shouldBe (s1 + s2).toMap()
}
}
context("Adding multiple sources in multiple API calls") {
// Consecutive source-adds should be merged.
sourceSignaling.addSources(s1)
sourceSignaling.addSources(s2)
sourceSignaling.addSources(s2new)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources.toMap() shouldBe (s1 + s2 + s2new).toMap()
}
}
context("Adding and removing sources") {
// A source-remove after a series of source-adds should be a new entry.
sourceSignaling.addSources(s1)
sourceSignaling.addSources(s2)
sourceSignaling.addSources(s2new)
sourceSignaling.removeSources(s2new)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources.toMap() shouldBe (s1 + s2).toMap()
}
}
context("Adding, removing, then adding again") {
// A source-add following source-remove should be a new entry.
sourceSignaling.addSources(s1)
sourceSignaling.addSources(s2)
sourceSignaling.addSources(s2new)
sourceSignaling.removeSources(s2new)
sourceSignaling.addSources(s3)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources.toMap() shouldBe (s1 + s2 + s3).toMap()
}
}
context("Adding and removing the same source") {
sourceSignaling.addSources(s1)
sourceSignaling.removeSources(s1)
sourceSignaling.update().shouldBeEmpty()
}
sourceSignaling.debugState.shouldBeValidJson()
}
listOf(true, false).forEach { supportsReceivingMultipleStreams ->
context("Filtering (supportsReceivingMultipleStreams=$supportsReceivingMultipleStreams)") {
val sourceSignaling = SourceSignaling(audio = true, video = false, stripSimulcast = true)
sourceSignaling.reset(s1 + s2).shouldBe(
ConferenceSourceMap(
e1 to EndpointSourceSet(e1a),
e2 to EndpointSourceSet(e2a)
)
)
sourceSignaling.addSources(s2new)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources shouldBe ConferenceSourceMap(e2 to EndpointSourceSet(e2a2))
}
sourceSignaling.removeSources(s1)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Remove
it[0].sources shouldBe ConferenceSourceMap(e1 to EndpointSourceSet(e1a))
}
sourceSignaling.addSources(s1)
sourceSignaling.removeSources(s1)
sourceSignaling.update().shouldBeEmpty()
sourceSignaling.removeSources(s2)
sourceSignaling.addSources(s2)
sourceSignaling.update().shouldBeEmpty()
}
}
context("Filtering with no support for multiple streams") {
val sourceSignaling = SourceSignaling(
audio = true,
video = true,
stripSimulcast = true,
supportsReceivingMultipleStreams = false
)
sourceSignaling.addSources(s1)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources shouldBe s1
}
// When camera and SS are added together, it should only add SS
sourceSignaling.addSources(s4audio + s4video + s4ss)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources shouldBe (s4audio + s4ss).stripSimulcast()
}
// It should only remove the sources that were added (SS)
sourceSignaling.removeSources(s4audio + s4video + s4ss)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Remove
it[0].sources shouldBe (s4audio + s4ss).stripSimulcast()
}
sourceSignaling.addSources(s4audio + s4ss)
sourceSignaling.update().let {
it.size shouldBe 1
it[0].action shouldBe Add
it[0].sources shouldBe (s4audio + s4ss).stripSimulcast()
}
// SS exists, camera should not be added.
sourceSignaling.addSources(s4video)
sourceSignaling.update().shouldBeEmpty()
// When SS is removed and only camera is left, camera should be added
sourceSignaling.removeSources(s4ss)
sourceSignaling.update().let { sourceUpdates ->
sourceUpdates.size shouldBe 2
val remove = sourceUpdates.find { it.action == Remove }
remove shouldNotBe null
remove!!.sources shouldBe s4ss.stripSimulcast()
val add = sourceUpdates.find { it.action == Add }
add shouldNotBe null
add!!.sources shouldBe s4video.stripSimulcast()
}
// When SS is added and camera exists, it should be replaced.
sourceSignaling.addSources(s4ss)
sourceSignaling.update().let { sourceUpdates ->
sourceUpdates.size shouldBe 2
val remove = sourceUpdates.find { it.action == Remove }
remove shouldNotBe null
remove!!.sources shouldBe s4video.stripSimulcast()
val add = sourceUpdates.find { it.action == Add }
add shouldNotBe null
add!!.sources shouldBe s4ss.stripSimulcast()
}
}
}
}
fun JSONObject.shouldBeValidJson() = JSONParser().parse(this.toJSONString())
| apache-2.0 | 29beaf44ae8c648842f29e9b3c9273e7 | 40.638989 | 105 | 0.580111 | 4.694343 | false | false | false | false |
myeonginwoo/KotlinWithAndroid | app/src/main/kotlin/com/lazysoul/kotlinwithandroid/ui/main/TodoAdapter.kt | 1 | 1850 | package com.lazysoul.kotlinwithandroid.ui.main
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.lazysoul.kotlinwithandroid.R
import com.lazysoul.kotlinwithandroid.datas.Todo
import kotlinx.android.synthetic.main.item_todo.view.*
import java.util.ArrayList
/**
* Created by Lazysoul on 2017. 7. 12..
*/
class TodoAdapter(val todoListener: TodoListener)
: RecyclerView.Adapter<TodoAdapter.TodoHolder>() {
private val todoList = ArrayList<Todo>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoHolder =
TodoHolder(parent)
override fun onBindViewHolder(holder: TodoHolder, position: Int) {
holder.draw(todoList[position])
}
override fun getItemCount(): Int = todoList.size
fun addItems(list: List<Todo>) {
todoList.addAll(list)
notifyDataSetChanged()
}
fun update(todoId: Int) {
val position = todoList.indexOfFirst { todoId == it.id }
notifyItemChanged(position)
}
fun addItem(todo: Todo) {
todoList.add(todo)
notifyItemInserted(todoList.size - 1)
}
fun clear() {
todoList.clear()
notifyDataSetChanged()
}
inner class TodoHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_todo, parent, false)) {
fun draw(todo: Todo) {
with(itemView) {
cb_item.isChecked = todo.isChecked
cb_item.setOnCheckedChangeListener { _, isChecked ->
todoListener.onChecked(todo.id, isChecked)
}
cv_item_todo.setOnClickListener { todoListener.onClicked(todo.id) }
tv_item_todo_body.text = todo.body
}
}
}
}
| mit | 6dafc5293f07ef42144bd407151d068f | 28.365079 | 93 | 0.652432 | 4.352941 | false | false | false | false |
MrBIMC/RunInBackgroundPermissionSetter | app/src/main/java/com/pavelsikun/runinbackgroundpermissionsetter/MainActivity.kt | 1 | 6759 | package com.pavelsikun.runinbackgroundpermissionsetter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.content.pm.PackageManager
import android.content.Intent
import android.net.Uri
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
import org.jetbrains.anko.coroutines.experimental.bg
import com.yarolegovich.lovelydialog.LovelyStandardDialog
import com.yarolegovich.lovelydialog.LovelyProgressDialog
import kotlinx.android.synthetic.main.search_view.*
import android.view.ViewAnimationUtils
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.Activity
import android.support.design.widget.Snackbar
import android.view.inputmethod.InputMethodManager
import com.pavelsikun.runinbackgroundpermissionsetter.AppListAdapter.SortMethod
class MainActivity : AppCompatActivity() {
val adapter by lazy {
AppListAdapter { (_, appName, appPackage, isEnabled) ->
setRunInBackgroundPermission(appPackage, isEnabled) { isSuccess ->
val status = if (isEnabled) getString(R.string.message_allow) else getString(R.string.message_ignore)
val msgSuccess = "$appName RUN_IN_BACKGROUND ${getString(R.string.message_was_set_to)} '$status'"
val msgError = "${getString(R.string.message_there_was_error)} $appName RUN_IN_BACKGROUND ${getString(R.string.message_to)} '$status'"
runOnUiThread {
val msg = if (isSuccess) msgSuccess else msgError
Snackbar.make(coordinator, msg, Snackbar.LENGTH_SHORT).show()
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
recycler.layoutManager = LinearLayoutManager(this)
recycler.adapter = adapter
swipeRefreshLayout.setOnRefreshListener {
adapter.clear()
loadApps()
}
loadApps()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_search -> showSearchBar()
R.id.action_info -> showInfoDialog()
R.id.action_sort_name -> adapter.sort(SortMethod.NAME)
R.id.action_sort_package -> adapter.sort(SortMethod.PACKAGE)
R.id.action_sort_disabled_first -> adapter.sort(SortMethod.STATE)
}
return super.onOptionsItemSelected(item)
}
fun loadApps() {
swipeRefreshLayout.isRefreshing = false
val ad = LovelyProgressDialog(this)
.setTopColorRes(R.color.accent)
.setTopTitle(getString(R.string.loading_dialog_title))
.setTopTitleColor(getColor(android.R.color.white))
.setIcon(R.drawable.clock_alert)
.setMessage(getString(R.string.loading_dialog_message)).show()
async(UI) {
val intent = Intent(Intent.ACTION_MAIN, null)
intent.addCategory(Intent.CATEGORY_LAUNCHER)
val apps = packageManager.queryIntentActivities(intent, PackageManager.GET_META_DATA)
apps.map {
val data = bg {
AppItem(it.loadIcon(packageManager),
it.loadLabel(packageManager).toString(),
it.activityInfo.packageName,
checkRunInBackgroundPermission(it.activityInfo.packageName).get())
}
adapter.addItem(data.await())
if (adapter.itemCount == apps.size) {
adapter.sort()
ad.dismiss()
}
}
}
}
fun openGithub() {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/MrBIMC/RunInBackgroundPermissionSetter")))
}
fun showSearchBar() {
val viewWidth = searchOverlay.measuredWidth.toFloat()
val x = (searchOverlay.measuredWidth * 0.95).toInt()
val y = searchOverlay.measuredHeight / 2
val enterAnim = ViewAnimationUtils.createCircularReveal(searchOverlay, x, y, 0f, viewWidth)
val exitAnim = ViewAnimationUtils.createCircularReveal(searchOverlay, x, y, viewWidth, 0f)
val inputManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
enterAnim.addListener(object: AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
searchBox.requestFocus()
inputManager.showSoftInput(searchBox, InputMethodManager.SHOW_IMPLICIT)
}
})
exitAnim.addListener(object: AnimatorListenerAdapter() {
override fun onAnimationEnd(animator: Animator) {
searchOverlay.visibility = View.INVISIBLE
}
})
buttonClear.setOnClickListener {
searchBox.text.clear()
}
buttonBack.setOnClickListener {
inputManager.hideSoftInputFromWindow(currentFocus.windowToken, 0)
exitAnim.start()
}
searchBox.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) { /*IGNORE*/ }
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { /*IGNORE*/ }
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
adapter.filter(searchBox.text.toString().toLowerCase())
}
})
searchOverlay.visibility = View.VISIBLE
enterAnim.start()
}
fun showInfoDialog() {
LovelyStandardDialog(this)
.setTopColorRes(R.color.accent)
.setTopTitle(getString(R.string.button_open_information))
.setTopTitleColor(getColor(android.R.color.white))
.setButtonsColorRes(R.color.primary)
.setIcon(R.drawable.information)
.setMessage(R.string.info_dialog_message)
.setNegativeButton(getString(R.string.button_close_dialog), null)
.setPositiveButton(getString(R.string.button_open_github)) {
openGithub()
}
.show()
}
}
| gpl-3.0 | 6386c539ef316603011480879bd0799a | 37.622857 | 150 | 0.645066 | 4.855603 | false | false | false | false |
mayank408/susi_android | app/src/main/java/org/fossasia/susi/ai/chat/ChatPresenter.kt | 1 | 18937 | package org.fossasia.susi.ai.chat
import android.os.Handler
import io.realm.RealmResults
import org.fossasia.susi.ai.MainApplication
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.data.db.DatabaseRepository
import org.fossasia.susi.ai.data.db.contract.IDatabaseRepository
import org.fossasia.susi.ai.chat.contract.IChatPresenter
import org.fossasia.susi.ai.chat.contract.IChatView
import org.fossasia.susi.ai.data.ChatModel
import org.fossasia.susi.ai.data.UtilModel
import org.fossasia.susi.ai.data.contract.IChatModel
import org.fossasia.susi.ai.data.model.ChatMessage
import org.fossasia.susi.ai.helper.*
import org.fossasia.susi.ai.rest.clients.BaseUrl
import org.fossasia.susi.ai.rest.responses.others.LocationResponse
import org.fossasia.susi.ai.rest.responses.susi.MemoryResponse
import org.fossasia.susi.ai.rest.responses.susi.SusiResponse
import retrofit2.Response
import java.util.*
/**
* Presentation Layer for Chat View.
*
* The P in MVP
* Created by chiragw15 on 9/7/17.
*/
class ChatPresenter(chatActivity: ChatActivity): IChatPresenter, IChatModel.OnRetrievingMessagesFinishedListener,
IChatModel.OnLocationFromIPReceivedListener, IChatModel.OnMessageFromSusiReceivedListener,
IDatabaseRepository.onDatabaseUpdateListener{
var chatView: IChatView?= null
var chatModel: IChatModel = ChatModel()
var utilModel: UtilModel = UtilModel(chatActivity)
var databaseRepository: IDatabaseRepository = DatabaseRepository()
lateinit var locationHelper: LocationHelper
val nonDeliveredMessages = LinkedList<Pair<String, Long>>()
lateinit var results: RealmResults<ChatMessage>
var newMessageIndex: Long = 0
var micCheck = false
var latitude: Double = 0.0
var longitude: Double = 0.0
var source = Constant.IP
var isDetectionOn = false
var check = false
var offset = 1
var isEnabled = true
var atHome = true
var backPressedOnce = false
override fun onAttach(chatView: IChatView) {
this.chatView = chatView
}
override fun setUp() {
//set theme
chatView?.setTheme(PrefManager.getString(Constant.THEME, Constant.LIGHT) == Constant.DARK)
//find total number of messages and find new message index
newMessageIndex = databaseRepository.getMessageCount() + 1
PrefManager.putLong(Constant.MESSAGE_COUNT, newMessageIndex)
micCheck = utilModel.checkMicInput()
chatView?.setupAdapter(databaseRepository.getAllMessages())
getPermissions()
}
override fun checkPreferences() {
micCheck = utilModel.getBooleanPref(Constant.MIC_INPUT, true)
chatView?.checkMicPref(utilModel.getBooleanPref(Constant.MIC_INPUT, true))
chatView?.checkEnterKeyPref(utilModel.getBooleanPref(Constant.ENTER_SEND, false))
}
override fun onMenuCreated() {
chatView?.enableLoginInMenu(utilModel.getAnonymity())
}
override fun micCheck(): Boolean {
return micCheck
}
override fun check(boolean: Boolean) {
check = boolean
}
//Change Background Methods
override fun setUpBackground() {
val previouslyChatImage = PrefManager.getString(Constant.IMAGE_DATA, "")
if (previouslyChatImage.equals(utilModel.getString(R.string.background_no_wall), ignoreCase = true)) {
chatView?.setChatBackground(null)
} else if (!previouslyChatImage.equals("", ignoreCase = true)) {
chatView?.setChatBackground(utilModel.decodeImage(previouslyChatImage))
} else {
chatView?.setChatBackground(null)
}
}
override fun openSelectBackgroundDialog(which: Int) {
when (which) {
0 -> {
chatView?.openImagePickerActivity()
}
1 -> {
PrefManager.putString(Constant.IMAGE_DATA, utilModel.getString(R.string.background_no_wall))
setUpBackground()
}
}
}
override fun cropPicture(encodedImage: String) {
PrefManager.putString(Constant.IMAGE_DATA, encodedImage)
setUpBackground()
}
//initiates hotword detection
override fun initiateHotwordDetection() {
if (chatView!!.checkPermission(utilModel.permissionsToGet()[2]) &&
chatView!!.checkPermission(utilModel.permissionsToGet()[1])) {
if ( utilModel.isArmDevice() && utilModel.checkMicInput()) {
utilModel.copyAssetstoSD()
chatView?.initHotword()
startHotwordDetection()
}
else {
chatView?.showToast(utilModel.getString(R.string.error_hotword))
utilModel.putBooleanPref(Constant.HOTWORD_DETECTION, false)
}
}
}
override fun hotwordDetected() {
chatView?.displayVoiceInput()
chatView?.promptSpeechInput()
}
override fun startHotwordDetection() {
if (!isDetectionOn && utilModel.getBooleanPref(Constant.HOTWORD_DETECTION, false)) {
chatView?.stopRecording()
isDetectionOn = true
}
}
override fun stopHotwordDetection() {
if (isDetectionOn) {
chatView?.stopRecording()
isDetectionOn = false
}
}
override fun startSpeechInput() {
check = true
chatView?.displayVoiceInput()
chatView?.promptSpeechInput()
}
override fun disableMicInput(boolean: Boolean) {
if(boolean) {
micCheck = false
PrefManager.putBoolean(Constant.MIC_INPUT, false)
} else {
micCheck = utilModel.checkMicInput()
PrefManager.putBoolean(Constant.MIC_INPUT, utilModel.checkMicInput())
chatView?.checkMicPref(micCheck)
}
}
//Retrieves old Messages
override fun retrieveOldMessages(firstRun: Boolean) {
if(firstRun and NetworkUtils.isNetworkConnected()) {
chatView?.showRetrieveOldMessageProgress()
val thread = object : Thread() {
override fun run() {
chatModel.retrieveOldMessages(this@ChatPresenter)
}
}
thread.start()
}
}
override fun onRetrieveSuccess(response: Response<MemoryResponse>?) {
if (response != null && response.isSuccessful && response.body() != null) {
val allMessages = response.body().cognitions
if (allMessages.isEmpty()) {
chatView?.showToast("No messages found")
} else {
var c: Long
for (i in allMessages.size - 1 downTo 0) {
val query = allMessages[i].query
val queryDate = allMessages[i].query_date
val answerDate = allMessages[i].answer_date
val urlList = ParseSusiResponseHelper.extractUrls(query)
val isHavingLink = !urlList.isEmpty()
newMessageIndex = PrefManager.getLong(Constant.MESSAGE_COUNT, 0)
if (newMessageIndex == 0L) {
databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.getDate(queryDate),
DateTimeHelper.getTime(queryDate), false, "", null, false, null, "", 0, this)
} else {
val prevDate = DateTimeHelper.getDate(allMessages[i + 1].query_date)
if (DateTimeHelper.getDate(queryDate) != prevDate) {
databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.getDate(queryDate),
DateTimeHelper.getTime(queryDate), false, "", null, false, null, "", 0, this)
}
}
c = newMessageIndex
databaseRepository.updateDatabase(newMessageIndex, query, false, DateTimeHelper.getDate(queryDate),
DateTimeHelper.getTime(queryDate), true, "", null, isHavingLink, null, "", 0, this)
val actionSize = allMessages[i].answers[0].actions.size
for (j in 0..actionSize - 1) {
val psh = ParseSusiResponseHelper()
psh.parseSusiResponse(allMessages[i], j, utilModel.getString(R.string.error_occurred_try_again))
databaseRepository.updateDatabase(c, psh.answer, false, DateTimeHelper.getDate(answerDate),
DateTimeHelper.getTime(answerDate), false, psh.actionType, psh.mapData, psh.isHavingLink,
psh.datumList, psh.webSearch, psh.count, this)
}
}
}
}
chatView?.hideRetrieveOldMessageProgress()
}
override fun updateMessageCount() {
newMessageIndex++
PrefManager.putLong(Constant.MESSAGE_COUNT, newMessageIndex)
}
override fun onRetrieveFailure() {
chatView?.hideRetrieveOldMessageProgress()
}
//Gets Location of user using his IP Address
override fun getLocationFromIP() {
chatModel.getLocationFromIP(this)
}
override fun onLocationSuccess(response: Response<LocationResponse>) {
if (response.isSuccessful && response.body() != null) {
try {
val loc = response.body().loc
val s = loc.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
latitude = s[0].toDouble()
longitude = s[1].toDouble()
source = Constant.IP
} catch (e: Exception) {
e.printStackTrace()
}
}
}
//Gets Location of user using gps and network
override fun getLocationFromLocationService() {
locationHelper = LocationHelper(MainApplication.getInstance().applicationContext)
getLocation()
}
fun getLocation() {
locationHelper.getLocation()
if (locationHelper.canGetLocation()) {
latitude = locationHelper.latitude
longitude = locationHelper.longitude
source = locationHelper.source
}
}
//get undelivered messages from database
override fun getUndeliveredMessages() {
nonDeliveredMessages.clear()
val nonDelivered = databaseRepository.getUndeliveredMessages()
nonDelivered.mapTo(nonDeliveredMessages) { Pair(it.content, it.id) }
}
//sends message to susi
override fun sendMessage(query: String, actual: String) {
val urlList = ParseSusiResponseHelper.extractUrls(query)
val isHavingLink = !urlList.isEmpty()
newMessageIndex = PrefManager.getLong(Constant.MESSAGE_COUNT, 0)
if (newMessageIndex == 0L) {
databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.date,
DateTimeHelper.currentTime, false, "", null, false, null, "", 0, this)
} else {
val s = databaseRepository.getAMessage(newMessageIndex-1).date
if (DateTimeHelper.date != s) {
databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.date,
DateTimeHelper.currentTime, false, "", null, false, null, "", 0, this)
}
}
nonDeliveredMessages.add(Pair(query, newMessageIndex))
databaseRepository.updateDatabase(newMessageIndex, actual, false, DateTimeHelper.date,
DateTimeHelper.currentTime, true, "", null, isHavingLink, null, "", 0, this)
getLocationFromLocationService()
computeThread().start()
}
override fun startComputingThread() {
computeThread().start()
}
private inner class computeThread : Thread() {
override fun run() {
computeOtherMessage()
}
}
@Synchronized
fun computeOtherMessage() {
if (!nonDeliveredMessages.isEmpty()) {
if (NetworkUtils.isNetworkConnected()) {
chatView?.showWaitingDots()
val tz = TimeZone.getDefault()
val now = Date()
val timezoneOffset = -1 * (tz.getOffset(now.time) / 60000)
val query = nonDeliveredMessages.first.first
chatModel.getSusiMessage(timezoneOffset, longitude, latitude, source, Locale.getDefault().language, query, this)
} else run {
chatView?.hideWaitingDots()
chatView?.displaySnackbar(utilModel.getString(R.string.no_internet_connection))
}
}
}
override fun onSusiMessageReceivedFailure(t: Throwable) {
chatView?.hideWaitingDots()
val id = nonDeliveredMessages.first.second
val query = nonDeliveredMessages.first.first
nonDeliveredMessages.pop()
if (!NetworkUtils.isNetworkConnected()) {
nonDeliveredMessages.addFirst(Pair(query, id))
chatView?.displaySnackbar(utilModel.getString(R.string.no_internet_connection))
} else {
databaseRepository.updateDatabase(id, utilModel.getString(R.string.error_internet_connectivity),
false, DateTimeHelper.date, DateTimeHelper.currentTime, false, Constant.ANSWER,
null, false, null, "", -1, this)
}
BaseUrl.updateBaseUrl(t)
computeOtherMessage()
}
override fun onSusiMessageReceivedSuccess(response: Response<SusiResponse>?) {
val id = nonDeliveredMessages.first.second
val query = nonDeliveredMessages.first.first
nonDeliveredMessages.pop()
if (response != null && response.isSuccessful && response.body() != null) {
val susiResponse = response.body()
val actionSize = response.body().answers[0].actions.size
val date = response.body().answer_date
for (i in 0..actionSize - 1) {
val delay = response.body().answers[0].actions[i].delay
val actionNo = i
val handler = Handler()
handler.postDelayed({
val psh = ParseSusiResponseHelper()
psh.parseSusiResponse(susiResponse, actionNo, utilModel.getString(R.string.error_occurred_try_again))
val setMessage = psh.answer
if (psh.actionType == Constant.ANSWER && (PrefManager.checkSpeechOutputPref() && check || PrefManager.checkSpeechAlwaysPref())){
var speechReply = setMessage
if (psh.isHavingLink) {
speechReply = setMessage.substring(0, setMessage.indexOf("http"))
}
chatView?.voiceReply(speechReply)
}
databaseRepository.updateDatabase(id, setMessage, false, DateTimeHelper.getDate(date),
DateTimeHelper.getTime(date), false, psh.actionType, psh.mapData, psh.isHavingLink,
psh.datumList, psh.webSearch, psh.count, this)
}, delay)
}
chatView?.hideWaitingDots()
} else {
if (!NetworkUtils.isNetworkConnected()) {
nonDeliveredMessages.addFirst(Pair(query, id))
chatView?.displaySnackbar(utilModel.getString(R.string.no_internet_connection))
} else {
databaseRepository.updateDatabase(id, utilModel.getString(R.string.error_internet_connectivity),
false, DateTimeHelper.date, DateTimeHelper.currentTime, false,
Constant.ANSWER, null, false, null, "", -1, this)
}
chatView?.hideWaitingDots()
}
if (!NetworkUtils.isNetworkConnected())
computeOtherMessage()
}
override fun onDatabaseUpdateSuccess() {
chatView?.databaseUpdated()
}
//Search methods. Used when search is enabled
override fun startSearch() {
chatView?.displaySearchElements(true)
isEnabled = false
}
override fun stopSearch() {
chatView?.modifyMenu(false)
offset = 1
chatView?.displaySearchElements(false)
}
override fun onSearchQuerySearched(query: String) {
chatView?.displaySearchElements(true)
results = databaseRepository.getSearchResults(query)
offset = 1
if (results.size > 0) {
chatView?.modifyMenu(true)
chatView?.searchMovement(results[results.size - offset].id.toInt())
} else {
chatView?.showToast(utilModel.getString(R.string.not_found))
}
}
override fun searchUP() {
offset++
if (results.size - offset > -1) {
chatView?.searchMovement(results[results.size - offset].id.toInt())
} else {
chatView?.showToast(utilModel.getString(R.string.nothing_up_matches_your_query))
offset--
}
}
override fun searchDown() {
offset--
if (results.size - offset < results.size) {
chatView?.searchMovement(results[results.size - offset].id.toInt())
} else {
chatView?.showToast(utilModel.getString(R.string.nothing_down_matches_your_query))
offset++
}
}
//Asks for permissions from user
fun getPermissions() {
val permissionsRequired = utilModel.permissionsToGet()
val permissionsGranted = arrayOfNulls<String>(3)
var c = 0
for(permission in permissionsRequired) {
if(!(chatView?.checkPermission(permission) as Boolean)) {
permissionsGranted[c] = permission
c++
}
}
if(c > 0) {
chatView?.askForPermission(permissionsGranted)
}
if(!(chatView?.checkPermission(permissionsRequired[1]) as Boolean)) {
PrefManager.putBoolean(Constant.MIC_INPUT, utilModel.checkMicInput())
}
}
override fun logout() {
utilModel.clearToken()
databaseRepository.deleteAllMessages()
chatView?.startLoginActivity()
}
override fun login() {
utilModel.clearToken()
utilModel.saveAnonymity(false)
databaseRepository.deleteAllMessages()
chatView?.startLoginActivity()
}
override fun exitChatActivity() {
if (atHome) {
if (backPressedOnce) {
chatView?.finishActivity()
return
}
backPressedOnce = true
chatView?.showToast(utilModel.getString(R.string.exit))
Handler().postDelayed({ backPressedOnce = false }, 2000)
} else if (!atHome) {
atHome = true
}
}
override fun onDetach() {
locationHelper.removeListener()
databaseRepository.closeDatabase()
chatView = null
}
} | apache-2.0 | f957c48afa76d6fff9e46ccea923a6a9 | 36.353057 | 148 | 0.611818 | 5.075583 | false | false | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solverGenerator/solution/SolveDerivation.kt | 1 | 2256 | package de.sudoq.model.solverGenerator.solution
import de.sudoq.model.actionTree.Action
import de.sudoq.model.solvingAssistant.HintTypes
import de.sudoq.model.sudoku.Sudoku
import java.util.*
/**
* A Derivation on the way to a solution of a Cell.
*
* @property type the technique that led to this derivation
*/
open class SolveDerivation constructor(var type: HintTypes?) {
/**
* A textual illustration of this solution step
*/
private var description: String? = null
/**
* A list of [DerivationCell]s, that are relevant fo this step
*/
private val cells: MutableList<DerivationCell> = ArrayList()
/**
* A list of [DerivationBlock]s that are relevant for this step
*/
private val blocks: MutableList<DerivationBlock> = ArrayList()
protected var hasActionListCapability =
false //maybe cleaner to have classes implement interface ActionList
constructor() : this(null)
/**
* Accepts a string description of what this derivation does
* @param descrip String that describes the derivation
*/
fun setDescription(description: String) {
this.description = description
}
/**
* Adds a DerivationCell
*
* @param cell [DerivationCell] to add
*/
fun addDerivationCell(cell: DerivationCell) {
cells.add(cell)
}
/**
* Adds a DerivationBlock
*
* @param cell [DerivationBlock] to add
*/
fun addDerivationBlock(block: DerivationBlock) {
blocks.add(block)
}
/**
* Iterator over [DerivationCell]s
*
* @return Iterator over [DerivationCell]s
*/
val cellIterator: Iterator<DerivationCell>
get() = cells.iterator()
/**
* Iterator over [DerivationBlock]s
*
* @return Iterator over [DerivationBlock]s
*/
val blockIterator: Iterator<DerivationBlock>
get() = blocks.iterator()
val derivationBlocks: List<DerivationBlock>
get() = blocks
fun hasActionListCapability(): Boolean {
return hasActionListCapability
}
open fun getActionList(sudoku: Sudoku): List<Action> {
return ArrayList()
}
override fun toString(): String {
return description!!
}
} | gpl-3.0 | 6ce20d77d75df7b8b9de2369f2c84804 | 23.532609 | 76 | 0.650709 | 4.680498 | false | false | false | false |
AndroidX/androidx | metrics/integration-tests/janktest/src/main/java/androidx/metrics/performance/janktest/JankStatsAggregator.kt | 3 | 4400 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.metrics.performance.janktest
import android.view.Window
import androidx.metrics.performance.FrameData
import androidx.metrics.performance.JankStats
/**
* This utility class can be used to provide a simple data aggregation mechanism for JankStats.
* Instead of receiving a callback on every frame and caching that data, JankStats users can
* create JankStats indirectly through this Aggregator class, which will compile the data
* and issue it upon request.
*
* @param window The Window for which stats will be tracked. A JankStatsAggregator
* instance is specific to each window in an application, since the timing metrics are
* tracked on a per-window basis internally.
* @throws IllegalStateException This function will throw an exception if `window` has
* a null DecorView.
*/
class JankStatsAggregator(window: Window, private val onJankReportListener: OnJankReportListener) {
private val listener = object : JankStats.OnFrameListener {
override fun onFrame(volatileFrameData: FrameData) {
++numFrames
if (volatileFrameData.isJank) {
// Store copy of frameData because it will be reused by JankStats before any report
// is issued
jankReport.add(volatileFrameData.copy())
if (jankReport.size >= REPORT_BUFFER_LIMIT) {
issueJankReport("Max buffer size reached")
}
}
}
}
val jankStats = JankStats.createAndTrack(window, listener)
private var jankReport = ArrayList<FrameData>()
private var numFrames: Int = 0
/**
* Issue a report on current jank data. The data includes FrameData for every frame
* experiencing jank since the listener was set, or since the last time a report
* was issued for this JankStats object. Calling this function will cause the jankData
* to be reset and cleared. Note that this function may be called externally, from application
* code, but it may also be called internally for various reasons (to reduce memory size
* by clearing the buffer, or because there was an important lifecycle event). The
* [reason] parameter explains why the report was issued if it was not called externally.
*
* @param reason An optional parameter specifying the reason that the report was issued.
* This parameter may be used if JankStats issues a report for some internal reason.
*/
fun issueJankReport(reason: String = "") {
val jankReportCopy = jankReport
val numFramesCopy = numFrames
onJankReportListener.onJankReport(reason, numFramesCopy, jankReportCopy)
jankReport = ArrayList()
numFrames = 0
}
/**
* This listener is called whenever there is a call to [issueJankReport].
*/
fun interface OnJankReportListener {
/**
* The implementation of this method will be called whenever there is a call
* to [issueJankReport].
*
* @param reason Optional reason that this report was issued
* @param totalFrames The total number of frames (jank and not) since collection
* began (or since the last time the report was issued and reset)
* @param jankFrameData The FrameData for every frame experiencing jank during
* the collection period
*/
fun onJankReport(reason: String, totalFrames: Int, jankFrameData: List<FrameData>)
}
companion object {
/**
* The number of frames for which data can be accumulated is limited to avoid
* memory problems. When the limit is reached, a report is automatically issued
* and the buffer is cleared.
*/
private const val REPORT_BUFFER_LIMIT = 1000
}
} | apache-2.0 | e160b0a19696a123f68b3e946d87bfd5 | 42.147059 | 99 | 0.696591 | 4.96614 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/barcodescanner/ExpoBarCodeScanner.kt | 2 | 4692 | package abi44_0_0.expo.modules.barcodescanner
import android.hardware.Camera
import android.hardware.Camera.CameraInfo
import android.util.Log
import android.view.Surface
class ExpoBarCodeScanner(
private var mActualDeviceOrientation: Int
) {
private val cameraInfo: HashMap<Int, CameraInfoWrapper?> = HashMap()
private val cameraTypeToIndex: HashMap<Int, Int> = HashMap()
private val cameras: MutableSet<Number> = HashSet()
init {
// map camera types to camera indexes and collect cameras properties
repeat(Camera.getNumberOfCameras()) {
val info = CameraInfo()
Camera.getCameraInfo(it, info)
if (info.facing == CameraInfo.CAMERA_FACING_FRONT && cameraInfo[CAMERA_TYPE_FRONT] == null) {
cameraInfo[CAMERA_TYPE_FRONT] = CameraInfoWrapper(info)
cameraTypeToIndex[CAMERA_TYPE_FRONT] = it
cameras.add(CAMERA_TYPE_FRONT)
} else if (info.facing == CameraInfo.CAMERA_FACING_BACK && cameraInfo[CAMERA_TYPE_BACK] == null) {
cameraInfo[CAMERA_TYPE_BACK] = CameraInfoWrapper(info)
cameraTypeToIndex[CAMERA_TYPE_BACK] = it
cameras.add(CAMERA_TYPE_BACK)
}
}
}
private var camera: Camera? = null
private var cameraType = 0
var rotation = 0
private set
fun acquireCameraInstance(type: Int): Camera? {
if (camera == null && cameras.contains(type) && null != cameraTypeToIndex[type]) {
try {
cameraTypeToIndex[type]?.let {
camera = Camera.open(it)
}
cameraType = type
adjustPreviewLayout(type)
} catch (e: Exception) {
Log.e("ExpoBarCodeScanner", "acquireCameraInstance failed", e)
}
}
return camera
}
fun releaseCameraInstance() {
camera?.run {
release()
}
camera = null
}
fun getPreviewWidth(type: Int): Int {
return cameraInfo[type]?.previewWidth ?: 0
}
fun getPreviewHeight(type: Int): Int {
return cameraInfo[type]?.previewHeight ?: 0
}
fun getBestSize(supportedSizes: List<Camera.Size>, maxWidth: Int, maxHeight: Int) =
supportedSizes
.filter { it.width <= maxWidth && it.height <= maxHeight }
.reduce { acc, size ->
val resultArea = acc.width * acc.height
val newArea = size.width * size.height
if (newArea > resultArea) {
size
} else {
acc
}
}
var actualDeviceOrientation: Int
get() = mActualDeviceOrientation
set(actualDeviceOrientation) {
mActualDeviceOrientation = actualDeviceOrientation
adjustPreviewLayout(cameraType)
}
fun adjustPreviewLayout(type: Int) {
camera?.run {
val tmpCameraInfo = cameraInfo[type] ?: return
// https://www.captechconsulting.com/blogs/android-camera-orientation-made-simple
val degrees =
when (mActualDeviceOrientation) {
Surface.ROTATION_0 -> 0
Surface.ROTATION_90 -> 90
Surface.ROTATION_180 -> 180
Surface.ROTATION_270 -> 270
else -> 0
}
if (tmpCameraInfo.info.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (tmpCameraInfo.info.orientation + degrees) % 360
rotation = (360 - rotation) % 360
} else {
rotation = (tmpCameraInfo.info.orientation - degrees + 360) % 360
}
setDisplayOrientation(rotation)
val temporaryParameters = parameters
temporaryParameters.setRotation(rotation)
// set preview size
// Limit preview size to 1920x1920 in order to allow scanning codes on low dpi computer screens
val optimalPreviewSize = getBestSize(temporaryParameters.supportedPreviewSizes, 1920, 1920)
val width = optimalPreviewSize.width
val height = optimalPreviewSize.height
temporaryParameters.setPreviewSize(width, height)
try {
parameters = temporaryParameters
} catch (e: Exception) {
e.printStackTrace()
}
tmpCameraInfo.previewHeight = height
tmpCameraInfo.previewWidth = width
if (rotation == 90 || rotation == 270) {
tmpCameraInfo.previewHeight = width
tmpCameraInfo.previewWidth = height
}
}
}
private inner class CameraInfoWrapper(val info: CameraInfo) {
var rotation = 0
var previewWidth = -1
var previewHeight = -1
}
companion object {
const val CAMERA_TYPE_FRONT = 1
const val CAMERA_TYPE_BACK = 2
private var innerInstance: ExpoBarCodeScanner? = null
val instance: ExpoBarCodeScanner
get() = requireNotNull(innerInstance) { "Bar code scanner needs to be initialized" }
fun createInstance(deviceOrientation: Int) {
innerInstance = ExpoBarCodeScanner(deviceOrientation)
}
}
}
| bsd-3-clause | 347546874b968508b168059d2a2673dd | 30.702703 | 104 | 0.660912 | 4.481375 | false | false | false | false |
androidx/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/layoutanimation/ScaleEnterExitDemo.kt | 3 | 6193 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.layoutanimation
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.expandIn
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement.Absolute.SpaceEvenly
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Checkbox
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Preview
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun ScaleEnterExitDemo() {
Column {
var showRed by remember { mutableStateOf(true) }
var showYellow by remember { mutableStateOf(true) }
var showGreen by remember { mutableStateOf(true) }
var showBlue by remember { mutableStateOf(true) }
AnimatedVisibility(
visible = showRed,
// Scale up from the TopLeft by setting TransformOrigin to (0f, 0f), while expanding the
// layout size from Top start and fading. This will create a coherent look as if the
// scale is impacting the size.
enter = scaleIn(transformOrigin = TransformOrigin(0f, 0f)) + fadeIn() +
expandIn(expandFrom = Alignment.TopStart),
// Scale down from the TopLeft by setting TransformOrigin to (0f, 0f), while shrinking
// the layout towards Top start and fading. This will create a coherent look as if the
// scale is impacting the layout size.
exit = scaleOut(transformOrigin = TransformOrigin(0f, 0f)) + fadeOut() +
shrinkOut(shrinkTowards = Alignment.TopStart)
) {
Box(Modifier.size(100.dp).background(Color.Red, shape = RoundedCornerShape(20.dp)))
}
AnimatedVisibility(
visible = showYellow,
enter = scaleIn(transformOrigin = TransformOrigin(0f, 0f)),
exit = scaleOut(transformOrigin = TransformOrigin(1f, 1f))
) {
Box(Modifier.size(100.dp).background(Color.Yellow, shape = RoundedCornerShape(20.dp)))
}
AnimatedVisibility(
visible = showGreen,
// By Default, `scaleIn` uses the center as the pivot point. When used with a vertical
// expansion from the vertical center, the content will be growing from the center of
// the vertically expanding layout.
enter = scaleIn() + expandVertically(expandFrom = Alignment.CenterVertically),
// By Default, `scaleOut` uses the center as the pivot point. When used with an
// ExitTransition that shrinks towards the center, the content will be shrinking both in
// terms of scale and layout size towards the center.
exit = scaleOut() + shrinkVertically(shrinkTowards = Alignment.CenterVertically)
) {
Box(Modifier.size(100.dp).background(Color.Green, shape = RoundedCornerShape(20.dp)))
}
AnimatedVisibility(
visible = showBlue,
enter = scaleIn(initialScale = 1.2f) +
slideInHorizontally(initialOffsetX = { (-it * 1.2f).toInt() }),
exit = scaleOut(targetScale = 2f) +
slideOutHorizontally(targetOffsetX = { -2 * it })
) {
Box(Modifier.size(100.dp).background(Color.Blue, shape = RoundedCornerShape(20.dp)))
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = SpaceEvenly) {
Column(Modifier.clickable { showRed = !showRed }.padding(5.dp)) {
Checkbox(showRed, { showRed = !showRed })
Text("Red\n (Scale \n + Expand/Shrink \n TopStart)")
}
Column(Modifier.clickable { showYellow = !showYellow }.padding(5.dp)) {
Checkbox(showYellow, { showYellow = !showYellow })
Text("Yellow\n (Scale)")
}
Column(Modifier.clickable { showGreen = !showGreen }.padding(5.dp)) {
Checkbox(showGreen, { showGreen = !showGreen })
Text("Green\n (Scale \n + Expand/Shrink \n CenterVertical)")
}
Column(Modifier.clickable { showBlue = !showBlue }.padding(5.dp)) {
Checkbox(showBlue, { showBlue = !showBlue })
Text("Blue\n (Scale \n + Slide)")
}
}
}
} | apache-2.0 | 1efe5d01090828d9c39b3992928b4c37 | 47.015504 | 100 | 0.691426 | 4.573855 | false | false | false | false |
bsmr-java/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/Constants.kt | 1 | 6112 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import java.io.PrintWriter
import java.util.*
import kotlin.reflect.KClass
// Extension properties for numeric literals.
val Int.b: Byte get() = this.toByte()
val Int.s: Short get() = this.toShort()
val Long.i: Int get() = this.toInt()
open class ConstantType<T : Any>(
val javaType: String,
val print: (T) -> String
) {
constructor(
type: KClass<T>,
print: (T) -> String
) : this(type.java.simpleName, print)
}
val ByteConstant = ConstantType(Byte::class) {
val i = it.toInt() and 0xFF
"0x%X".format(i).let {
if ( i < 0x80 ) it else "(byte)$it"
}
}
val CharConstant = ConstantType(Char::class) { "'$it'" }
val ShortConstant = ConstantType(Short::class) {
val i = it.toInt() and 0xFFFF
"0x%X".format(i).let {
if ( i < 0x8000 ) it else "(short)$it"
}
}
val IntConstant = ConstantType(Int::class) { "0x%X".format(it) }
val LongConstant = ConstantType(Long::class) { "0x%XL".format(it) }
val FloatConstant = ConstantType(Float::class) { "%sf".format(it) }
val StringConstant = ConstantType(String::class) { "\"$it\"" }
open class EnumValue(
val documentation: (() -> String?) = { null },
val value: Int? = null
)
class EnumValueExpression(
documentation: () -> String?,
val expression: String
) : EnumValue(documentation, null)
val EnumConstant = ConstantType(EnumValue::class, { "0x%X".format(it) })
open class Constant<out T : Any>(val name: String, val value: T?)
internal class ConstantExpression<out T : Any>(
name: String,
val expression: String,
// Used for StringConstants only, false: wrap in quotes, true: print as is
val unwrapped: Boolean
) : Constant<T>(name, null)
class ConstantBlock<T : Any>(
val nativeClass: NativeClass,
var access: Access,
val constantType: ConstantType<T>,
val documentation: () -> String?,
vararg val constants: Constant<T>
) {
private var noPrefix = false
fun noPrefix() {
noPrefix = true
}
private fun getConstantName(name: String) = if ( noPrefix ) name else "${nativeClass.prefixConstant}$name"
private val Constant<Int>.enumValue: Int get() = this.value.let {
it ?: try {
Integer.parseInt((this as ConstantExpression).expression)
} catch(e: Exception) {
Integer.MAX_VALUE
}
}
internal fun generate(writer: PrintWriter) {
if ( constantType === EnumConstant ) {
// Increment/update the current enum value while iterating the enum constants.
// Constants without documentation are added to the root block.
// Constants with documentation go to their own block.
val rootBlock = ArrayList<Constant<Int>>()
val enumBlocks = ArrayList<ConstantBlock<Int>>()
var value = 0
var formatType = 1 // 0: hex, 1: decimal
for (c in constants) {
if ( c is ConstantExpression ) {
@Suppress("UNCHECKED_CAST")
rootBlock.add(c as ConstantExpression<Int>)
continue
}
val ev = c.value as EnumValue
(
when {
ev is EnumValueExpression -> {
try {
value = Integer.parseInt(ev.expression) + 1 // decimal
formatType = 1 // next values will be decimal
} catch(e: NumberFormatException) {
try {
value = Integer.parseInt(ev.expression, 16) + 1 // hex
} catch(e: Exception) {
// ignore
}
formatType = 0 // next values will be hex
}
ConstantExpression(c.name, ev.expression, false)
}
ev.value != null -> {
value = ev.value + 1
formatType = 0
Constant(c.name, ev.value)
}
else -> {
if ( formatType == 1 )
ConstantExpression(c.name, Integer.toString(value++), false)
else
Constant(c.name, value++)
}
}
).let {
val doc = ev.documentation()
if ( doc == null )
rootBlock.add(it)
else
ConstantBlock(nativeClass, access, IntConstant, { doc }, it).let {
it.noPrefix = noPrefix
enumBlocks.add(it)
}
}
}
fun rootBlockBefore() =
enumBlocks.isEmpty() || Math.abs(rootBlock[0].enumValue) <= Math.abs(enumBlocks[0].constants[0].enumValue)
fun PrintWriter.generateRootBlock(rootBlock: ArrayList<Constant<Int>>) =
ConstantBlock(nativeClass, access, IntConstant, [email protected], *rootBlock.toArray(emptyArray())).let {
it.noPrefix = noPrefix
it.generate(this)
}
if ( rootBlock.isNotEmpty() && rootBlockBefore())
writer.generateRootBlock(rootBlock)
for (b in enumBlocks)
b.generate(writer)
if ( rootBlock.isNotEmpty() && !rootBlockBefore())
writer.generateRootBlock(rootBlock)
} else
writer.generateBlock()
}
private fun PrintWriter.generateBlock() {
println()
val doc = documentation()
if ( doc != null )
println(doc)
print("\t${access.modifier}static final ${constantType.javaType}")
val indent: String
if ( constants.size == 1 ) {
indent = " "
} else {
print('\n')
indent = "\t\t"
}
// Find maximum constant name length
val alignment = constants.map {
it.name.length
}.fold(0) { left, right ->
Math.max(left, right)
}
constants.forEachWithMore { it, more ->
if ( more )
println(',')
printConstant(it, indent, alignment)
}
println(";")
}
private fun PrintWriter.printConstant(constant: Constant<T>, indent: String, alignment: Int) {
print("$indent${getConstantName(constant.name)}")
for (i in 0..(alignment - constant.name.length - 1))
print(' ')
print(" = ")
if ( constant is ConstantExpression ) {
print(if ( constantType !== StringConstant || constant.unwrapped )
constant.expression
else
constantType.print(constant.expression)
)
} else
print(constantType.print(constant.value!!))
}
val javaDocLinks: String get() = javaDocLinks { true }
val javaDocLinksSkipCount: String get() = javaDocLinks { !it.name.endsWith("_COUNT") }
fun javaDocLinks(predicate: (Constant<T>) -> Boolean) = constants.asSequence()
.filter { predicate(it) }
.map { "${nativeClass.className}#${it.name}" }
.joinToString(" ")
} | bsd-3-clause | 87c8bcd2a9c3c7a551240fad286e7d3e | 26.290179 | 125 | 0.648887 | 3.474702 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/types/Ty.kt | 1 | 12855 | package org.elm.lang.core.types
/**
* A type in the inference system.
*
* The name "Ty" is used to differentiate it from the PsiElements with "Type" in their name.
*/
sealed class Ty {
/**
* The type of the alias that this ty was referenced through, if there is one.
*
* If the type was inferred from a literal or referenced directly, this will be null. Types that
* cannot be aliased like [TyVar] will always return null.
*/
abstract val alias: AliasInfo?
/** Make a copy of this ty with the given [alias] as its alias */
abstract fun withAlias(alias: AliasInfo): Ty
}
// vars are not a data class because they need to be compared by identity
/**
* A type variable, either rigid or flexible.
*
* e.g. Given the following declaration:
*
* ```
* foo : a -> ()
* foo x =
* ...
* ```
*
* While inferring the body of the declaration, the value `x` is a rigid variable (meaning it can't
* be assigned to anything expecting a concrete type, so an expression like `x + 1` is invalid).
* When calling `foo`, the parameter is a flexible variable (meaning any type can be passed as an
* argument).
*/
class TyVar(val name: String, val rigid: Boolean = false) : Ty() {
override val alias: AliasInfo? get() = null
override fun withAlias(alias: AliasInfo): TyVar = this
override fun toString(): String {
return "<${if (rigid) "!" else ""}$name@${(System.identityHashCode(this)).toString(16).take(3)}>"
}
}
/** A tuple type like `(Int, String)` */
data class TyTuple(val types: List<Ty>, override val alias: AliasInfo? = null) : Ty() {
init {
require(types.isNotEmpty()) { "can't create a tuple with no types. Use TyUnit." }
}
override fun withAlias(alias: AliasInfo): TyTuple = copy(alias = alias)
}
/**
* A record type like `{x: Int, y: Float}` or `{a | x: Int}`
*
* @property fields map of field name to ty
* @property baseTy The type of the base record identifier, if there is one. Non-null for field
* accessors, record with base identifiers etc. that match a subset of record fields
* @property alias The alias for this record, if there is one. Used for rendering and tracking record constructors
* @property fieldReferences A map of field name to the psi element that defines them; used for
* reference resolve, only the frozen status affects equality
*/
data class TyRecord(
val fields: Map<String, Ty>,
val baseTy: Ty? = null,
override val alias: AliasInfo? = null,
val fieldReferences: RecordFieldReferenceTable = RecordFieldReferenceTable()
) : Ty() {
companion object {
// Empty records occur in code like `foo : BaseRecord {}`, where they create a type from an
// extension record with no extra fields.
val emptyRecord = TyRecord(emptyMap(), null, null, RecordFieldReferenceTable().apply { freeze() })
}
/** true if this record has a base name, and will match a subset of a record's fields */
val isSubset: Boolean get() = baseTy != null
override fun withAlias(alias: AliasInfo): TyRecord = copy(alias = alias)
override fun toString(): String {
val f = fields.toString().let { it.substring(1, it.lastIndex) }
return alias?.let {
val prefix = if (fieldReferences.isEmpty()) "" else "+"
val params = if (it.parameters.isEmpty()) "" else " ${it.parameters.joinToString(" ")}"
"{$prefix${it.name}$params}"
} ?: baseTy?.let { "{$baseTy | $f}" } ?: "{$f}"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TyRecord) return false
if (fields != other.fields) return false
if (baseTy != other.baseTy) return false
if (alias != other.alias) return false
if (fieldReferences.frozen != other.fieldReferences.frozen) return false
return true
}
override fun hashCode(): Int {
var result = fields.hashCode()
result = 31 * result + (baseTy?.hashCode() ?: 0)
result = 31 * result + (alias?.hashCode() ?: 0)
result = 31 * result + fieldReferences.frozen.hashCode()
return result
}
}
/**
* A [TyRecord] with mutable fields, only used internally by type inference. These are never cached.
*
* This is used to track multiple constraints on record types. Only records can have more than one
* constraint, so other types don't need a mutable version.
*/
data class MutableTyRecord(
val fields: MutableMap<String, Ty>,
val baseTy: Ty? = null,
val fieldReferences: RecordFieldReferenceTable = RecordFieldReferenceTable()
) : Ty() {
fun toRecord() = TyRecord(fields.toMap(), baseTy, alias, fieldReferences)
override val alias: AliasInfo? get() = null
override fun withAlias(alias: AliasInfo) = error("MutableTyRecord cannot have aliases")
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is MutableTyRecord) return false
if (fields != other.fields) return false
if (baseTy != other.baseTy) return false
if (alias != other.alias) return false
if (fieldReferences.frozen != other.fieldReferences.frozen) return false
return true
}
override fun hashCode(): Int {
var result = fields.hashCode()
result = 31 * result + (baseTy?.hashCode() ?: 0)
result = 31 * result + (alias?.hashCode() ?: 0)
result = 31 * result + fieldReferences.frozen.hashCode()
return result
}
override fun toString() = "{~${toRecord().toString().drop(1)}"
}
/** A type like `String` or `Maybe a` */
data class TyUnion(
val module: String,
val name: String,
val parameters: List<Ty>,
override val alias: AliasInfo? = null
) : Ty() {
override fun withAlias(alias: AliasInfo): TyUnion = copy(alias = alias)
override fun toString(): String {
return "[${(listOf("$module.$name") + parameters).joinToString(" ")}]"
}
}
val TyInt = TyUnion("Basics", "Int", emptyList())
val TyFloat = TyUnion("Basics", "Float", emptyList())
val TyBool = TyUnion("Basics", "Bool", emptyList())
val TyString = TyUnion("String", "String", emptyList())
val TyChar = TyUnion("Char", "Char", emptyList())
/** WebGL GLSL shader */
// The actual type is `Shader attributes uniforms varyings`, but we would have to parse the
// GLSL code to infer the type variables, so we just don't report diagnostics on shader types.
val TyShader = TyUnion("WebGL", "Shader", listOf(TyUnknown(), TyUnknown(), TyUnknown()))
@Suppress("FunctionName")
fun TyList(elementTy: Ty) = TyUnion("List", "List", listOf(elementTy))
val TyUnion.isTyList: Boolean get() = module == "List" && name == "List"
val TyUnion.isTyInt: Boolean get() = module == TyInt.module && name == TyInt.name
val TyUnion.isTyFloat: Boolean get() = module == TyFloat.module && name == TyFloat.name
val TyUnion.isTyBool: Boolean get() = module == TyBool.module && name == TyBool.name
val TyUnion.isTyString: Boolean get() = module == TyString.module && name == TyString.name
val TyUnion.isTyChar: Boolean get() = module == TyChar.module && name == TyChar.name
data class TyFunction(
val parameters: List<Ty>,
val ret: Ty,
override val alias: AliasInfo? = null
) : Ty() {
init {
require(parameters.isNotEmpty()) { "can't create a function with no parameters" }
}
val allTys get() = parameters + ret
fun partiallyApply(count: Int): Ty = when {
count < parameters.size -> TyFunction(parameters.drop(count), ret)
else -> ret
}
fun uncurry(): TyFunction = when (ret) {
is TyFunction -> TyFunction(parameters + ret.parameters, ret.ret)
else -> this
}
override fun withAlias(alias: AliasInfo): TyFunction = copy(alias = alias)
override fun toString(): String {
return allTys.joinToString(" → ", prefix = "(", postfix = ")")
}
}
/** The [Ty] representing `()` */
data class TyUnit(override val alias: AliasInfo? = null) : Ty() {
override fun withAlias(alias: AliasInfo): TyUnit = copy(alias = alias)
override fun toString(): String = javaClass.simpleName
}
/**
* A [Ty] that can be assigned to and from any [Ty].
*
* Used for unimplemented functionality and in partial programs where it's not possible to infer a type.
*/
data class TyUnknown(override val alias: AliasInfo? = null) : Ty() {
override fun withAlias(alias: AliasInfo): TyUnknown = copy(alias = alias)
override fun toString(): String = javaClass.simpleName
}
/** Not a real ty, but used to diagnose cyclic values in parameter bindings */
object TyInProgressBinding : Ty() {
override val alias: AliasInfo? get() = null
override fun withAlias(alias: AliasInfo): TyInProgressBinding = this
override fun toString(): String = javaClass.simpleName
}
/** Information about a type alias. This is not a [Ty]. */
data class AliasInfo(val module: String, val name: String, val parameters: List<Ty>)
/** Return a list of all [TyVar]s in this ty, including itself */
fun Ty.allVars(): List<TyVar> = mutableListOf<TyVar>().also { allVars(it) }
private fun Ty.allVars(result: MutableList<TyVar>) {
when (this) {
is TyVar -> result.add(this)
is TyTuple -> types.forEach { it.allVars(result) }
is TyRecord -> {
fields.values.forEach { it.allVars(result) }
baseTy?.allVars(result)
}
is MutableTyRecord -> {
fields.values.forEach { it.allVars(result) }
baseTy?.allVars(result)
}
is TyUnion -> parameters.forEach { it.allVars(result) }
is TyFunction -> {
ret.allVars(result)
parameters.forEach { it.allVars(result) }
}
is TyUnit, is TyUnknown, TyInProgressBinding -> {
}
}
}
/** Return `true` if this [Ty] or any of its children match the [predicate] */
fun Ty.anyVar(predicate: (TyVar) -> Boolean): Boolean {
return when (this) {
is TyVar -> predicate(this)
is TyTuple -> types.any { it.anyVar(predicate) }
is TyRecord -> fields.values.any { it.anyVar(predicate) } || baseTy?.anyVar(predicate) == true
is MutableTyRecord -> fields.values.any { it.anyVar(predicate) } || baseTy?.anyVar(predicate) == true
is TyUnion -> parameters.any { it.anyVar(predicate) }
is TyFunction -> ret.anyVar(predicate) || parameters.any { it.anyVar(predicate) }
is TyUnit, is TyUnknown, TyInProgressBinding -> false
} || alias?.parameters?.any { it.anyVar(predicate) } == true
}
data class DeclarationInTy(val module: String, val name: String, val isUnion: Boolean)
/** Create a lazy sequence of all union and alias instances within a [Ty]. */
fun Ty.allDeclarations(
includeFunctions: Boolean = false,
includeUnionsWithAliases: Boolean = false
): Sequence<DeclarationInTy> = sequence {
when (this@allDeclarations) {
is TyVar -> {
}
is TyTuple -> types.forEach { yieldAll(it.allDeclarations(includeFunctions, includeUnionsWithAliases)) }
is TyRecord -> {
fields.values.forEach { yieldAll(it.allDeclarations(includeFunctions, includeUnionsWithAliases)) }
if (baseTy != null) yieldAll(baseTy.allDeclarations(includeFunctions, includeUnionsWithAliases))
}
is MutableTyRecord -> {
fields.values.forEach { yieldAll(it.allDeclarations(includeFunctions, includeUnionsWithAliases)) }
if (baseTy != null) yieldAll(baseTy.allDeclarations(includeFunctions, includeUnionsWithAliases))
}
is TyFunction -> {
if (includeFunctions) {
yieldAll(ret.allDeclarations(includeFunctions, includeUnionsWithAliases))
parameters.forEach { yieldAll(it.allDeclarations(includeFunctions, includeUnionsWithAliases)) }
}
}
is TyUnion -> {
if (includeUnionsWithAliases || alias == null) {
yield(DeclarationInTy(module, name, isUnion = true))
}
parameters.forEach { yieldAll(it.allDeclarations(includeFunctions, includeUnionsWithAliases)) }
}
is TyUnit, is TyUnknown, TyInProgressBinding -> {
}
}
alias?.let {
yield(DeclarationInTy(it.module, it.name, isUnion = false))
it.parameters.forEach { p -> yieldAll(p.allDeclarations()) }
}
}
/** Extract the typeclass for a var name if it is one, or null if it's a normal var */
fun TyVar.typeclassName(): String? = when {
name.length < 6 -> null // "number".length == 6
name.startsWith("number") -> "number"
name.startsWith("appendable") -> "appendable"
name.startsWith("comparable") -> "comparable"
name.startsWith("compappend") -> "compappend"
else -> null
}
| mit | 8e78af6b4f94860e898c980b335d3892 | 39.291536 | 114 | 0.646931 | 4.291486 | false | false | false | false |
evanchooly/kibble | src/test/kotlin/com/antwerkz/kibble/KibbleObjectTest.kt | 1 | 1621 | package com.antwerkz.kibble
import com.squareup.kotlinpoet.ANY
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.KModifier.OVERRIDE
import com.squareup.kotlinpoet.KModifier.PRIVATE
import org.testng.Assert
import org.testng.annotations.Test
class KibbleObjectTest {
@Test
fun objects() {
val file = Kibble.parse("src/test/resources/com/antwerkz/test/SampleKibbleObject.kt")
val objects = file.classes.first().objects.iterator()
val kibbleObject = objects.next()
Assert.assertTrue(kibbleObject.isCompanion)
Assert.assertTrue(kibbleObject.modifiers.contains(PRIVATE))
Assert.assertEquals(kibbleObject.superclass, ANY)
Assert.assertTrue(kibbleObject.superclassConstructorParameters.isEmpty())
Assert.assertNotNull(kibbleObject.superinterfaces.containsKey(ClassName("java.lang", "Runnable")))
val functions = kibbleObject.funSpecs.iterator()
var function = functions.next()
Assert.assertEquals(function.name, "run")
Assert.assertTrue(function.modifiers.contains(OVERRIDE))
function = functions.next()
Assert.assertEquals(function.name, "dummy")
}
@Test
fun functions() {
val obj = Kibble.parseSource(
"""
object temp {
fun something(): Junk {
println("something")
}
}""".trim()
).objects.first()
Assert.assertEquals(obj.name, "temp")
val function = obj.funSpecs.first()
Assert.assertEquals(function.name, "something")
Assert.assertEquals(function.returnType, ClassName("", "Junk"))
}
}
| apache-2.0 | 0c5e1ec2b47ca13bcd50f8b09fc56879 | 34.23913 | 106 | 0.693399 | 4.465565 | false | true | false | false |
commonsguy/cw-omnibus | Slices/Inspector/app/src/main/java/com/commonsware/android/slice/inspector/InspectorFragment.kt | 2 | 2967 | /*
Copyright (c) 2018 CommonsWare, 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.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.slice.inspector
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.slice.Slice
import androidx.slice.SliceItem
import androidx.slice.widget.SliceLiveData
import de.blox.treeview.BaseTreeAdapter
import de.blox.treeview.TreeNode
import de.blox.treeview.TreeView
class InspectorFragment : Fragment() {
private lateinit var tree: TreeView
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
tree = TreeView(activity).apply {
lineColor = ResourcesCompat.getColor(activity!!.resources, android.R.color.black, null)
levelSeparation = 60
}
SliceLiveData
.fromUri(activity!!, Uri.parse(BuildConfig.SLICE_URI))
.observe(this, Observer<Slice> { this.onSlice(it) })
return tree
}
private fun onSlice(slice: Slice) {
val adapter = SliceTreeAdapter(activity!!)
val root = buildTreeNode(null)
slice.items.forEach { root.addChild(buildTreeNode(it)) }
adapter.setRootNode(root)
tree.adapter = adapter
}
private fun buildTreeNode(sliceItem: SliceItem?): TreeNode {
val result = TreeNode(sliceItem)
if (android.app.slice.SliceItem.FORMAT_SLICE == sliceItem?.format) {
sliceItem.slice.items.forEach { result.addChild(buildTreeNode(it)) }
}
return result
}
internal class SliceTreeAdapter(context: Context) : BaseTreeAdapter<SliceItemViewHolder>(context, R.layout.tree_node) {
override fun onCreateViewHolder(view: View): SliceItemViewHolder = SliceItemViewHolder(view)
override fun onBindViewHolder(viewHolder: SliceItemViewHolder, data: Any?,
position: Int) {
viewHolder.bind(data as SliceItem?)
}
}
internal class SliceItemViewHolder(card: View) {
val title: TextView = card.findViewById(R.id.title)
fun bind(sliceItem: SliceItem?) {
title.text = sliceItem?.format ?: "slice"
}
}
}
| apache-2.0 | 816f861b64361967f020b6bcd47da8ce | 32.715909 | 121 | 0.734075 | 4.275216 | false | false | false | false |
HabitRPG/habitica-android | wearos/src/main/java/com/habitrpg/wearos/habitica/ui/views/TextActionChipView.kt | 1 | 1828 | package com.habitrpg.wearos.habitica.ui.views
import android.content.Context
import android.content.res.ColorStateList
import android.util.AttributeSet
import android.view.Gravity
import android.widget.RelativeLayout
import androidx.core.view.isVisible
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.TextActionChipBinding
import com.habitrpg.common.habitica.extensions.layoutInflater
open class TextActionChipView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
RelativeLayout(context, attrs) {
private val attributes = context.theme?.obtainStyledAttributes(
attrs,
R.styleable.TextActionChip,
0, 0
)
val binding = TextActionChipBinding.inflate(context.layoutInflater, this)
init {
binding.chipTextview.text = attributes?.getText(R.styleable.TextActionChip_chipText)
val icon = attributes?.getDrawable(R.styleable.TextActionChip_chipImage)
if (icon != null) {
binding.chipImageview.setImageDrawable(icon)
binding.chipTextview.gravity = Gravity.START
binding.chipImageview.isVisible = true
} else {
binding.chipImageview.setImageDrawable(icon)
binding.chipTextview.gravity = Gravity.START
binding.chipImageview.isVisible = false
}
attributes?.getColor(R.styleable.TextActionChip_chipColor, context.getColor(R.color.surface))?.let {
binding.wearChipButton.backgroundTintList = ColorStateList.valueOf(it)
}
attributes?.getColor(R.styleable.TextActionChip_chipTextColor, context.getColor(R.color.watch_white))?.let {
binding.chipTextview.setTextColor(it)
}
}
fun setChipText(text: String) {
binding.chipTextview.text = text
}
} | gpl-3.0 | b91553737be638b9d72533b13434ccf3 | 38.76087 | 116 | 0.723195 | 4.699229 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/BaseDialogFragment.kt | 1 | 3833 | package com.habitrpg.android.habitica.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.TutorialRepository
import com.habitrpg.android.habitica.helpers.AmplitudeManager
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.ui.activities.MainActivity
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.functions.Consumer
import java.util.concurrent.TimeUnit
import javax.inject.Inject
abstract class BaseDialogFragment<VB : ViewBinding> : BottomSheetDialogFragment() {
var isModal: Boolean = false
abstract var binding: VB?
@Inject
lateinit var tutorialRepository: TutorialRepository
var tutorialStepIdentifier: String? = null
protected var tutorialCanBeDeferred = true
var tutorialTexts: MutableList<String> = ArrayList()
protected var compositeSubscription: CompositeDisposable = CompositeDisposable()
open val displayedClassName: String?
get() = this.javaClass.simpleName
override fun onCreate(savedInstanceState: Bundle?) {
HabiticaBaseApplication.userComponent?.let {
injectFragment(it)
}
super.onCreate(savedInstanceState)
}
abstract fun createBinding(inflater: LayoutInflater, container: ViewGroup?): VB
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
compositeSubscription = CompositeDisposable()
val additionalData = HashMap<String, Any>()
additionalData["page"] = this.javaClass.simpleName
AmplitudeManager.sendEvent("navigate", AmplitudeManager.EVENT_CATEGORY_NAVIGATION, AmplitudeManager.EVENT_HITTYPE_PAGEVIEW, additionalData)
binding = createBinding(inflater, container)
return binding?.root
}
abstract fun injectFragment(component: UserComponent)
override fun onResume() {
super.onResume()
showTutorialIfNeeded()
}
private fun showTutorialIfNeeded() {
if (view != null) {
if (this.tutorialStepIdentifier != null) {
compositeSubscription.add(
tutorialRepository.getTutorialStep(this.tutorialStepIdentifier ?: "").firstElement()
.delay(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
Consumer { step ->
if (step.isValid && step.isManaged && step.shouldDisplay) {
val mainActivity = activity as? MainActivity ?: return@Consumer
mainActivity.displayTutorialStep(step, tutorialTexts, tutorialCanBeDeferred)
}
},
ExceptionHandler.rx()
)
)
}
}
}
override fun onDestroyView() {
binding = null
if (!compositeSubscription.isDisposed) {
compositeSubscription.dispose()
}
super.onDestroyView()
}
override fun onDestroy() {
try {
tutorialRepository.close()
} catch (exception: UninitializedPropertyAccessException) { /* no-on */ }
super.onDestroy()
}
open fun addToBackStack(): Boolean = true
}
| gpl-3.0 | 58902cae70d03a1b61e527745a87359b | 34.82243 | 147 | 0.665275 | 5.807576 | false | false | false | false |
luanalbineli/popularmovies | app/src/main/java/com/themovielist/intheaters/InTheatersFragment.kt | 1 | 3621 | package com.themovielist.intheaters
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.themovielist.R
import com.themovielist.base.BaseFragment
import com.themovielist.base.BasePresenter
import com.themovielist.injector.components.ApplicationComponent
import com.themovielist.injector.components.DaggerFragmentComponent
import com.themovielist.model.MovieWithGenreModel
import com.themovielist.model.response.ConfigurationImageResponseModel
import com.themovielist.model.view.MovieImageGenreViewModel
import com.themovielist.movielist.MovieListFragment
import com.themovielist.util.ApiUtil
import kotlinx.android.synthetic.main.movie_header_detail.*
import timber.log.Timber
import javax.inject.Inject
class InTheatersFragment : BaseFragment<InTheatersContract.View>(), InTheatersContract.View {
override val presenterImplementation: BasePresenter<InTheatersContract.View>
get() = mPresenter
override val viewImplementation: InTheatersContract.View
get() = this
@Inject
lateinit var mPresenter: InTheatersPresenter
override fun onInjectDependencies(applicationComponent: ApplicationComponent) {
DaggerFragmentComponent.builder()
.applicationComponent(applicationComponent)
.build()
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.in_theaters_fragment, container, false)
}
private lateinit var mMovieListFragment: MovieListFragment
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity.setTitle(R.string.cinema)
mMovieListFragment = fragmentManager.findFragmentById(R.id.fragmentMovieList) as? MovieListFragment ?:
childFragmentManager.findFragmentById(R.id.fragmentMovieList) as MovieListFragment
mMovieListFragment.useListLayout()
mPresenter.start()
}
override fun showMainMovieDetail(movieWithGenreModel: MovieWithGenreModel) {
val posterWidth = ApiUtil.getDefaultPosterSize(sdvMovieHeaderBackdrop.width)
if (movieWithGenreModel.movieModel.posterPath != null) {
val posterUrl = ApiUtil.buildPosterImageUrl(movieWithGenreModel.movieModel.posterPath!!, posterWidth)
sdvMovieHeaderBackdrop.setImageURI(posterUrl)
}
tvMovieHeaderReleaseDate.text = "1h 20m" // TODO: TEST
tvMovieHeaderMovieName.text = movieWithGenreModel.movieModel.title
tvMovieHeaderMovieGenres.text = movieWithGenreModel.genreList?.map { it.name }?.reduce { a, b -> "$a, $b"} ?: ""
}
override fun showMovieList(results: List<MovieImageGenreViewModel>, configurationResponseModel: ConfigurationImageResponseModel) {
mMovieListFragment.addMoviesToList(results, configurationResponseModel)
}
override fun showLoadingIndicator() {
mMovieListFragment.showLoadingIndicator()
}
override fun hideLoadingIndicator() {
mMovieListFragment.hideLoadingIndicator()
}
override fun showErrorLoadingMovies(error: Throwable) {
Timber.e(error, "An error occurred while tried to fetch the in theaters movies: ${error.message}")
mMovieListFragment.showErrorLoadingMovies()
}
override fun onStop() {
super.onStop()
mPresenter.onStop()
}
companion object {
fun getInstance(): InTheatersFragment = InTheatersFragment()
}
}
| apache-2.0 | 62162e02e4b629bd6ea5a78ac0a575b4 | 36.71875 | 134 | 0.752002 | 5.187679 | false | false | false | false |
jakubveverka/SportApp | app/src/main/java/com/example/jakubveverka/sportapp/Adapters/EventsRecyclerViewAdapter.kt | 1 | 2479 | package com.example.jakubveverka.sportapp.Adapters
import android.content.Context
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.jakubveverka.sportapp.Entities.Event
import com.example.jakubveverka.sportapp.R
import com.example.jakubveverka.sportapp.ViewModels.EventsAdapterViewModel
import java.util.*
class EventsRecyclerViewAdapter(val mContext: Context) : RecyclerView.Adapter<EventsRecyclerViewAdapter.ViewHolder>() {
var mValues: List<Event> = LinkedList()
val mViewModel: EventsAdapterViewModel by lazy {
EventsAdapterViewModel(mContext)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_events_list_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.mItem = mValues[position]
holder.mNameTextView.text = mValues[position].name
holder.mPlaceTextView.text = mValues[position].place
holder.mStartTimeTextView.text = mViewModel.formatDateInMillis(mValues[position].startTime)
holder.mEndTimeTextView.text = mViewModel.formatDateInMillis(mValues[position].endTime)
holder.mContainer.setCardBackgroundColor(mViewModel.getBackgroundColorForEvent(mValues[position]))
}
override fun getItemCount(): Int {
return mValues.size
}
inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) {
val mNameTextView: TextView
val mPlaceTextView: TextView
val mStartTimeTextView: TextView
val mEndTimeTextView: TextView
val mContainer: CardView
var mItem: Event? = null
init {
mNameTextView = mView.findViewById(R.id.tw_name) as TextView
mPlaceTextView = mView.findViewById(R.id.tw_place) as TextView
mStartTimeTextView = mView.findViewById(R.id.tw_start_time) as TextView
mEndTimeTextView = mView.findViewById(R.id.tw_end_time) as TextView
mContainer = mView.findViewById(R.id.events_list_item_container) as CardView
}
override fun toString(): String {
return super.toString() + " '" + mNameTextView.text + "'"
}
}
}
| mit | 4a88b3aa80fa89e22a62bb7276a3ebef | 38.983871 | 119 | 0.722469 | 4.450628 | false | false | false | false |
InsertKoinIO/koin | core/koin-core/src/commonMain/kotlin/org/koin/core/registry/ScopeRegistry.kt | 1 | 3282 | /*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.koin.core.registry
import org.koin.core.Koin
import org.koin.core.annotation.KoinInternalApi
import org.koin.core.error.NoScopeDefFoundException
import org.koin.core.error.ScopeAlreadyCreatedException
import org.koin.core.module.Module
import org.koin.core.qualifier.Qualifier
import org.koin.core.qualifier._q
import org.koin.core.scope.Scope
import org.koin.core.scope.ScopeID
import org.koin.mp.KoinPlatformTools.safeHashMap
/**
* Scope Registry
* create/find scopes for Koin
*
* @author Arnaud Giuliani
*/
@OptIn(KoinInternalApi::class)
class ScopeRegistry(private val _koin: Koin) {
private val _scopeDefinitions = HashSet<Qualifier>()
val scopeDefinitions: Set<Qualifier>
get() = _scopeDefinitions
private val _scopes = safeHashMap<ScopeID, Scope>()
@KoinInternalApi
val rootScope = Scope(rootScopeQualifier, ROOT_SCOPE_ID, isRoot = true, _koin = _koin)
init {
_scopeDefinitions.add(rootScope.scopeQualifier)
_scopes[rootScope.id] = rootScope
}
@PublishedApi
internal fun getScopeOrNull(scopeId: ScopeID): Scope? {
return _scopes[scopeId]
}
@PublishedApi
internal fun createScope(scopeId: ScopeID, qualifier: Qualifier, source: Any? = null): Scope {
if (!_scopeDefinitions.contains(qualifier)){
_koin.logger.info("Warning: Scope '$qualifier' not defined. Creating it")
_scopeDefinitions.add(qualifier)
}
if (_scopes.contains(scopeId)) {
throw ScopeAlreadyCreatedException("Scope with id '$scopeId' is already created")
}
val scope = Scope(qualifier,scopeId, _koin = _koin)
source?.let { scope._source = source }
scope.linkTo(rootScope)
_scopes[scopeId] = scope
return scope
}
internal fun deleteScope(scopeId: ScopeID) {
_scopes[scopeId]?.let { deleteScope(it) }
}
internal fun deleteScope(scope: Scope) {
_koin.instanceRegistry.dropScopeInstances(scope)
_scopes.remove(scope.id)
}
internal fun close() {
closeAllScopes()
_scopes.clear()
_scopeDefinitions.clear()
}
private fun closeAllScopes() {
_scopes.values.forEach { scope ->
scope.close()
}
}
fun loadScopes(modules: Set<Module>) {
modules.forEach {
loadModule(it)
}
}
private fun loadModule(module: Module) {
_scopeDefinitions.addAll(module.scopes)
}
companion object {
private const val ROOT_SCOPE_ID = "_root_"
@PublishedApi
internal val rootScopeQualifier = _q(ROOT_SCOPE_ID)
}
} | apache-2.0 | f2eddaa52f84a4a553d0a04a2767f9f2 | 29.119266 | 98 | 0.67337 | 4.245796 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsTrackingController.kt | 1 | 4162 | package eu.kanade.tachiyomi.ui.setting
import android.app.Activity
import android.content.Intent
import android.support.customtabs.CustomTabsIntent
import android.support.v7.preference.PreferenceScreen
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.anilist.AnilistApi
import eu.kanade.tachiyomi.data.track.shikimori.ShikimoriApi
import eu.kanade.tachiyomi.data.track.bangumi.BangumiApi
import eu.kanade.tachiyomi.util.getResourceColor
import eu.kanade.tachiyomi.widget.preference.LoginPreference
import eu.kanade.tachiyomi.widget.preference.TrackLoginDialog
import uy.kohesive.injekt.injectLazy
import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys
class SettingsTrackingController : SettingsController(),
TrackLoginDialog.Listener {
private val trackManager: TrackManager by injectLazy()
override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) {
titleRes = R.string.pref_category_tracking
switchPreference {
key = Keys.autoUpdateTrack
titleRes = R.string.pref_auto_update_manga_sync
defaultValue = true
}
preferenceCategory {
titleRes = R.string.services
trackPreference(trackManager.myAnimeList) {
onClick {
val dialog = TrackLoginDialog(trackManager.myAnimeList)
dialog.targetController = this@SettingsTrackingController
dialog.showDialog(router)
}
}
trackPreference(trackManager.aniList) {
onClick {
val tabsIntent = CustomTabsIntent.Builder()
.setToolbarColor(context.getResourceColor(R.attr.colorPrimary))
.build()
tabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
tabsIntent.launchUrl(activity, AnilistApi.authUrl())
}
}
trackPreference(trackManager.kitsu) {
onClick {
val dialog = TrackLoginDialog(trackManager.kitsu)
dialog.targetController = this@SettingsTrackingController
dialog.showDialog(router)
}
}
trackPreference(trackManager.shikimori) {
onClick {
val tabsIntent = CustomTabsIntent.Builder()
.setToolbarColor(context.getResourceColor(R.attr.colorPrimary))
.build()
tabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
tabsIntent.launchUrl(activity, ShikimoriApi.authUrl())
}
}
trackPreference(trackManager.bangumi) {
onClick {
val tabsIntent = CustomTabsIntent.Builder()
.setToolbarColor(context.getResourceColor(R.attr.colorPrimary))
.build()
tabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
tabsIntent.launchUrl(activity, BangumiApi.authUrl())
}
}
}
}
inline fun PreferenceScreen.trackPreference(
service: TrackService,
block: (@DSL LoginPreference).() -> Unit
): LoginPreference {
return initThenAdd(LoginPreference(context).apply {
key = Keys.trackUsername(service.id)
title = service.name
}, block)
}
override fun onActivityResumed(activity: Activity) {
super.onActivityResumed(activity)
// Manually refresh anilist holder
updatePreference(trackManager.aniList.id)
updatePreference(trackManager.shikimori.id)
}
private fun updatePreference(id: Int) {
val pref = findPreference(Keys.trackUsername(id)) as? LoginPreference
pref?.notifyChanged()
}
override fun trackDialogClosed(service: TrackService) {
updatePreference(service.id)
}
}
| apache-2.0 | ff20441e2ebad9ca4f951f1b904cc656 | 38.638095 | 91 | 0.625661 | 5.43342 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/search/SearchEngine.kt | 1 | 7440 | package exh.search
import exh.metadata.sql.tables.SearchMetadataTable
import exh.metadata.sql.tables.SearchTagTable
import exh.metadata.sql.tables.SearchTitleTable
class SearchEngine {
private val queryCache = mutableMapOf<String, List<QueryComponent>>()
fun textToSubQueries(namespace: String?,
component: Text?): Pair<String, List<String>>? {
val maybeLenientComponent = component?.let {
if (!it.exact)
it.asLenientTagQueries()
else
listOf(it.asQuery())
}
val componentTagQuery = maybeLenientComponent?.let {
val params = mutableListOf<String>()
it.map { q ->
params += q
"${SearchTagTable.TABLE}.${SearchTagTable.COL_NAME} LIKE ?"
}.joinToString(separator = " OR ", prefix = "(", postfix = ")") to params
}
return if(namespace != null) {
var query = """
(SELECT ${SearchTagTable.COL_MANGA_ID} AS $COL_MANGA_ID FROM ${SearchTagTable.TABLE}
WHERE ${SearchTagTable.COL_NAMESPACE} IS NOT NULL
AND ${SearchTagTable.COL_NAMESPACE} LIKE ?
""".trimIndent()
val params = mutableListOf(escapeLike(namespace))
if(componentTagQuery != null) {
query += "\n AND ${componentTagQuery.first}"
params += componentTagQuery.second
}
"$query)" to params
} else if(component != null) {
// Match title + tags
val tagQuery = """
SELECT ${SearchTagTable.COL_MANGA_ID} AS $COL_MANGA_ID FROM ${SearchTagTable.TABLE}
WHERE ${componentTagQuery!!.first}
""".trimIndent() to componentTagQuery.second
val titleQuery = """
SELECT ${SearchTitleTable.COL_MANGA_ID} AS $COL_MANGA_ID FROM ${SearchTitleTable.TABLE}
WHERE ${SearchTitleTable.COL_TITLE} LIKE ?
""".trimIndent() to listOf(component.asLenientTitleQuery())
"(${tagQuery.first} UNION ${titleQuery.first})".trimIndent() to
(tagQuery.second + titleQuery.second)
} else null
}
fun queryToSql(q: List<QueryComponent>): Pair<String, List<String>> {
val wheres = mutableListOf<String>()
val whereParams = mutableListOf<String>()
val include = mutableListOf<Pair<String, List<String>>>()
val exclude = mutableListOf<Pair<String, List<String>>>()
for(component in q) {
val query = if(component is Text) {
textToSubQueries(null, component)
} else if(component is Namespace) {
if(component.namespace == "uploader") {
wheres += "meta.${SearchMetadataTable.COL_UPLOADER} LIKE ?"
whereParams += component.tag!!.rawTextEscapedForLike()
null
} else {
if(component.tag!!.components.size > 0) {
//Match namespace + tags
textToSubQueries(component.namespace, component.tag)
} else {
//Perform namespace search
textToSubQueries(component.namespace, null)
}
}
} else error("Unknown query component!")
if(query != null) {
(if(component.excluded) exclude else include) += query
}
}
val completeParams = mutableListOf<String>()
var baseQuery = """
SELECT ${SearchMetadataTable.COL_MANGA_ID}
FROM ${SearchMetadataTable.TABLE} meta
""".trimIndent()
include.forEachIndexed { index, pair ->
baseQuery += "\n" + ("""
INNER JOIN ${pair.first} i$index
ON i$index.$COL_MANGA_ID = meta.${SearchMetadataTable.COL_MANGA_ID}
""".trimIndent())
completeParams += pair.second
}
exclude.forEach {
wheres += """
(meta.${SearchMetadataTable.COL_MANGA_ID} NOT IN ${it.first})
""".trimIndent()
whereParams += it.second
}
if(wheres.isNotEmpty()) {
completeParams += whereParams
baseQuery += "\nWHERE\n"
baseQuery += wheres.joinToString("\nAND\n")
}
baseQuery += "\nORDER BY ${SearchMetadataTable.COL_MANGA_ID}"
return baseQuery to completeParams
}
fun parseQuery(query: String, enableWildcard: Boolean = true) = queryCache.getOrPut(query) {
val res = mutableListOf<QueryComponent>()
var inQuotes = false
val queuedRawText = StringBuilder()
val queuedText = mutableListOf<TextComponent>()
var namespace: Namespace? = null
var nextIsExcluded = false
var nextIsExact = false
fun flushText() {
if(queuedRawText.isNotEmpty()) {
queuedText += StringTextComponent(queuedRawText.toString())
queuedRawText.setLength(0)
}
}
fun flushToText() = Text().apply {
components += queuedText
queuedText.clear()
}
fun flushAll() {
flushText()
if (queuedText.isNotEmpty() || namespace != null) {
val component = namespace?.apply {
tag = flushToText()
namespace = null
} ?: flushToText()
component.excluded = nextIsExcluded
component.exact = nextIsExact
res += component
}
}
for(char in query.toLowerCase()) {
if(char == '"') {
inQuotes = !inQuotes
} else if(enableWildcard && (char == '?' || char == '_')) {
flushText()
queuedText.add(SingleWildcard(char.toString()))
} else if(enableWildcard && (char == '*' || char == '%')) {
flushText()
queuedText.add(MultiWildcard(char.toString()))
} else if(char == '-') {
nextIsExcluded = true
} else if(char == '$') {
nextIsExact = true
} else if(char == ':') {
flushText()
var flushed = flushToText().rawTextOnly()
//Map tag aliases
flushed = when(flushed) {
"a" -> "artist"
"c", "char" -> "character"
"f" -> "female"
"g", "creator", "circle" -> "group"
"l", "lang" -> "language"
"m" -> "male"
"p", "series" -> "parody"
"r" -> "reclass"
else -> flushed
}
namespace = Namespace(flushed, null)
} else if(char == ' ' && !inQuotes) {
flushAll()
} else {
queuedRawText.append(char)
}
}
flushAll()
res
}
companion object {
private const val COL_MANGA_ID = "cmid"
fun escapeLike(string: String): String {
return string.replace("\\", "\\\\")
.replace("_", "\\_")
.replace("%", "\\%")
}
}
}
| apache-2.0 | 0427e3efc0747dbaee06df8a2eb1e87e | 35.650246 | 103 | 0.497984 | 5.181058 | false | false | false | false |
GKZX-HN/MyGithub | app/src/main/java/com/gkzxhn/mygithub/ui/adapter/ColumnCardsAdapter.kt | 1 | 4831 | package com.gkzxhn.mygithub.ui.adapter
import android.graphics.Bitmap
import android.graphics.Canvas
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.RelativeLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.gkzxhn.mygithub.R
import com.gkzxhn.mygithub.bean.info.ColumnCardsInfo
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
/**
* Created by 方 on 2017/10/24.
*/
class ColumnCardsAdapter(datas: List<ColumnCardsInfo>?) : BaseQuickAdapter<ColumnCardsInfo, BaseViewHolder>(R.layout.item_column_card, datas) {
private var dispose: Disposable? = null
private val PRESS_TIME = 500L //长按的临界时间
private var onActionListener: OnActionListener? = null
private var bitmapCard: Bitmap? = null
private var originalX = 0f
private var originalY = 0f
fun setOnActionListener(onActionListener: OnActionListener) {
this.onActionListener = onActionListener
}
override fun convert(helper: BaseViewHolder?, item: ColumnCardsInfo?) {
helper!!.setText(R.id.tv_note, item!!.note)
.setText(R.id.tv_login, item.creator.login)
.addOnClickListener(R.id.iv_edit)
val itemCard = helper.getView<RelativeLayout>(R.id.ll_item_card)
itemCard.setOnTouchListener { v, event ->
Log.i(javaClass.simpleName, "item_card event_action : ${event.action}")
when (event.action) {
MotionEvent.ACTION_DOWN -> {
val rawX = event.rawX
val rawY = event.rawY
dispose = Observable.just("long press")
.delay(PRESS_TIME, TimeUnit.MILLISECONDS)
.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe({
if (onActionListener != null) {
originalX = rawX
originalY = rawY
bitmapCard = view2bitmap(itemCard)
onActionListener!!.onActionLongClick(itemCard, item, rawX, rawY)
itemCard.parent.requestDisallowInterceptTouchEvent(true);
}
},{
Log.e(javaClass.simpleName, it.message)
})
return@setOnTouchListener true
}
MotionEvent.ACTION_MOVE -> {
if (bitmapCard != null) {
if (onActionListener != null) {
onActionListener!!.onActionMove(itemCard, item, event.rawX, event.rawY)
return@setOnTouchListener true
}
}
}
MotionEvent.ACTION_UP -> {
dispose!!.dispose()
if (bitmapCard != null) {
if (onActionListener != null) {
val rawX = event.rawX
val rawY = event.rawY
onActionListener!!.onActionUp(itemCard, item, rawX, rawY)
}
}
return@setOnTouchListener false
}
MotionEvent.ACTION_CANCEL -> {
dispose!!.dispose()
}
else -> {
}
}
return@setOnTouchListener false
}
}
interface OnActionListener {
fun onActionLongClick(view: View, item: ColumnCardsInfo?, rawX: Float, rawY: Float)
fun onActionMove(view: View, item: ColumnCardsInfo?, rawX: Float, rawY: Float)
fun onActionUp(view: View, item: ColumnCardsInfo?, rawX: Float, rawY: Float)
}
fun view2bitmap(view: View): Bitmap {
val width = view.measuredWidth
val height = view.measuredHeight
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
view.draw(Canvas(bitmap))
return bitmap
}
} | gpl-3.0 | ec0c79b64ca956b76bbe4ad73bd7236e | 42.387387 | 143 | 0.506542 | 5.780312 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/media/src/main/kotlin/app/ss/media/playback/model/PlaybackProgressState.kt | 1 | 624 | package app.ss.media.playback.model
import androidx.compose.runtime.Immutable
import app.ss.media.playback.extensions.millisToDuration
@Immutable
data class PlaybackProgressState(
val total: Long = 0L,
val position: Long = 0L,
val elapsed: Long = 0L,
val buffered: Long = 0L
) {
val progress get() = ((position.toFloat() + elapsed) / (total + 1).toFloat()).coerceIn(0f, 1f)
val bufferedProgress get() = ((buffered.toFloat()) / (total + 1).toFloat()).coerceIn(0f, 1f)
val currentDuration get() = (position + elapsed).millisToDuration()
val totalDuration get() = total.millisToDuration()
}
| mit | 67669ca870f0a03a869b4489a2f3c1a6 | 31.842105 | 98 | 0.697115 | 3.714286 | false | false | false | false |
Maccimo/intellij-community | platform/platform-api/src/com/intellij/ide/actions/CollapseAllAction.kt | 2 | 2407 | // 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.ide.actions
import com.intellij.ide.TreeExpander
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.IdeActions.ACTION_COLLAPSE_ALL
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys.TOOL_WINDOW
import com.intellij.openapi.actionSystem.PlatformDataKeys.TREE_EXPANDER
import com.intellij.openapi.actionSystem.ex.ActionUtil.copyFrom
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.ExperimentalUI
class CollapseAllAction : DumbAwareAction {
private val getTreeExpander: (AnActionEvent) -> TreeExpander?
constructor() : super() {
getTreeExpander = { TREE_EXPANDER.getData(it.dataContext) ?: findTreeExpander(it) }
}
constructor(getExpander: (AnActionEvent) -> TreeExpander?) : super() {
getTreeExpander = getExpander
copyFrom(this, ACTION_COLLAPSE_ALL)
}
override fun actionPerformed(event: AnActionEvent) {
val expander = getTreeExpander(event) ?: return
if (expander.canCollapse()) expander.collapseAll()
}
override fun update(event: AnActionEvent) {
val expander = getTreeExpander(event)
val hideIfMissing = event.getData(PlatformDataKeys.TREE_EXPANDER_HIDE_ACTIONS_IF_NO_EXPANDER) ?: false
event.presentation.isVisible = expander == null && !hideIfMissing ||
expander != null && expander.isCollapseAllVisible && expander.isVisible(event)
event.presentation.isEnabled = expander != null && expander.canCollapse()
if (ExperimentalUI.isNewUI() && ActionPlaces.isPopupPlace(event.place)) {
event.presentation.icon = null
}
}
companion object {
// find tree expander for a toolbar of a tool window
internal fun findTreeExpander(event: AnActionEvent): TreeExpander? {
if (!event.isFromActionToolbar) return null
val window = TOOL_WINDOW.getData(event.dataContext) ?: return null
val component = window.contentManagerIfCreated?.selectedContent?.component ?: return null
val provider = component as? DataProvider ?: return null
return TREE_EXPANDER.getData(provider)
}
}
}
| apache-2.0 | 075ad75f2e3eae43d7ceea46a0eacb76 | 43.574074 | 120 | 0.75779 | 4.664729 | false | false | false | false |
diffplug/durian-rx | src/main/java/com/diffplug/common/rx/RxBoxImp.kt | 1 | 1641 | /*
* Copyright 2020 DiffPlug
*
* 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.diffplug.common.rx
import com.diffplug.common.base.Converter
import java.util.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
internal open class RxBoxImp<T> private constructor(initial: T, subject: MutableStateFlow<T>) :
RxBox<T> {
private var value: T = initial
private val subject: MutableStateFlow<T> = subject
constructor(initial: T) : this(initial, MutableStateFlow(initial)) {}
override fun set(newValue: T) {
if (newValue != value) {
value = newValue
subject.value = newValue
}
}
override fun get(): T = value
override fun asObservable(): Flow<T> = subject
internal class Mapped<T, R>(delegate: RxBox<T>, converter: Converter<T, R>) :
MappedImp<T, R, RxBox<T>>(delegate, converter), RxBox<R> {
val observable: Flow<R> =
delegate.asObservable().map { a: T -> converter.convertNonNull(a) }.distinctUntilChanged()
override fun asObservable(): Flow<R> = observable
}
}
| apache-2.0 | f1d245a58d73058979583da84466c667 | 33.1875 | 95 | 0.737355 | 3.825175 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/instructionset/Op.kt | 1 | 1053 | package nl.jstege.adventofcode.aoc2018.days.instructionset
/**
*
* @author Jelle Stege
*/
enum class Op(val instr: (Int, Int, RegisterBank) -> Int) {
ADDR({ ra, rb, rs -> rs[ra] + rs[rb] }),
ADDI({ ra, vb, rs -> rs[ra] + vb }),
MULR({ ra, rb, rs -> rs[ra] * rs[rb] }),
MULI({ ra, vb, rs -> rs[ra] * vb }),
BANR({ ra, rb, rs -> rs[ra] and rs[rb] }),
BANI({ ra, vb, rs -> rs[ra] and vb }),
BORR({ ra, rb, rs -> rs[ra] or rs[rb] }),
BORI({ ra, vb, rs -> rs[ra] or vb }),
SETR({ ra, _, rs -> rs[ra] }),
SETI({ va, _, _ -> va }),
GTIR({ va, rb, rs -> if (va > rs[rb]) 1 else 0 }),
GTRI({ ra, vb, rs -> if (rs[ra] > vb) 1 else 0 }),
GTRR({ ra, rb, rs -> if (rs[ra] > rs[rb]) 1 else 0 }),
EQIR({ va, rb, rs -> if (va == rs[rb]) 1 else 0 }),
EQRI({ ra, vb, rs -> if (rs[ra] == vb) 1 else 0 }),
EQRR({ ra, rb, rs -> if (rs[ra] == rs[rb]) 1 else 0 });
operator fun invoke(op1: Int, op2: Int, op3: Int, rs: RegisterBank): RegisterBank =
rs.copyAndUpdate(op3, instr(op1, op2, rs))
}
| mit | 129488e8ad7abb76018f46fd806ebff8 | 36.607143 | 87 | 0.488129 | 2.543478 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/viewholders/MonthActivityAdapter.kt | 1 | 1668 | package org.wordpress.android.ui.stats.refresh.lists.sections.viewholders
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView.Adapter
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ActivityItem.Box
class MonthActivityAdapter : Adapter<DayViewHolder>() {
private var items: List<Box> = listOf()
fun update(newItems: List<Box>) {
val diffResult = DiffUtil.calculateDiff(BoxDiffCallback(items, newItems))
items = newItems
diffResult.dispatchUpdatesTo(this)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DayViewHolder {
return DayViewHolder(parent)
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: DayViewHolder, position: Int, payloads: List<Any>) {
val item = items[position]
holder.bind(item)
}
override fun onBindViewHolder(holder: DayViewHolder, position: Int) {
onBindViewHolder(holder, position, listOf())
}
private class BoxDiffCallback(
private val oldItems: List<Box>,
private val newItems: List<Box>
) : DiffUtil.Callback() {
override fun areItemsTheSame(oldPosition: Int, newPosition: Int): Boolean {
return oldItems[oldPosition] == newItems[newPosition]
}
override fun getOldListSize(): Int = oldItems.size
override fun getNewListSize(): Int = newItems.size
override fun areContentsTheSame(oldPosition: Int, newPosition: Int): Boolean {
return oldItems[oldPosition] == newItems[newPosition]
}
}
}
| gpl-2.0 | 930149a8359ddcffd61a3b869de47a0d | 33.75 | 94 | 0.703837 | 4.891496 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/sitecreation/theme/SiteDesignRecommendationProvider.kt | 1 | 4103 | package org.wordpress.android.ui.sitecreation.theme
import org.wordpress.android.R
import org.wordpress.android.fluxc.network.rest.wpcom.theme.StarterDesign
import org.wordpress.android.fluxc.network.rest.wpcom.theme.StarterDesignCategory
import org.wordpress.android.ui.layoutpicker.LayoutCategoryModel
import org.wordpress.android.ui.layoutpicker.LayoutModel
import org.wordpress.android.ui.layoutpicker.toLayoutCategories
import org.wordpress.android.ui.layoutpicker.toLayoutModels
import org.wordpress.android.viewmodel.ResourceProvider
import javax.inject.Inject
class SiteDesignRecommendationProvider @Inject constructor(private val resourceProvider: ResourceProvider) {
fun handleResponse(
vertical: String,
designs: List<StarterDesign>,
categories: List<StarterDesignCategory>,
responseHandler: (layouts: List<LayoutModel>, categories: List<LayoutCategoryModel>) -> Unit
) {
val verticalSlug: String? = if (vertical.isNullOrEmpty()) null else getVerticalSlug(vertical)
val hasRecommendations = !verticalSlug.isNullOrEmpty() &&
designs.any { it.group.contains(verticalSlug) }
if (hasRecommendations) {
val recommendedTitle = resourceProvider.getString(R.string.hpp_recommended_title, vertical)
// Create a new category for the recommendations
val recommendedCategory = StarterDesignCategory(
slug = "recommended_$verticalSlug", // The slug is not used but should not already exist
title = recommendedTitle,
description = recommendedTitle,
emoji = ""
)
val designsWithRecommendations = designs.map {
// Add the new category to the recommended designs so that they are filtered correctly
// in the `LayoutPickerViewModel.loadLayouts()` method
if (it.group.contains(verticalSlug)) {
it.copy(categories = it.categories + recommendedCategory)
} else {
it
}
}.toLayoutModels()
val categoriesWithRecommendations =
listOf(recommendedCategory).toLayoutCategories(recommended = true) +
categories.toLayoutCategories(randomizeOrder = true)
responseHandler(designsWithRecommendations, categoriesWithRecommendations)
} else {
// If no designs are recommended for the selected vertical recommend the blog category
val recommendedTitle = resourceProvider.getString(
R.string.hpp_recommended_title,
resourceProvider.getString(R.string.hpp_recommended_default_vertical)
)
val recommendedCategory = categories.firstOrNull { it.slug == "blog" }?.copy(
title = recommendedTitle,
description = recommendedTitle
)
if (recommendedCategory == null) {
// If there is no blog category do not show a recommendation
responseHandler(designs.toLayoutModels(), categories.toLayoutCategories(randomizeOrder = true))
} else {
val categoriesWithRecommendations =
listOf(recommendedCategory).toLayoutCategories(recommended = true, randomizeOrder = true) +
categories.toLayoutCategories(randomizeOrder = true)
responseHandler(designs.toLayoutModels(), categoriesWithRecommendations)
}
}
}
@Suppress("UseCheckOrError")
private fun getVerticalSlug(vertical: String): String? {
val slugsArray = resourceProvider.getStringArray(R.array.site_creation_intents_slugs)
val verticalArray = resourceProvider.getStringArray(R.array.site_creation_intents_strings)
if (slugsArray.size != verticalArray.size) {
throw IllegalStateException("Intents arrays size mismatch")
}
return slugsArray.getOrNull(verticalArray.indexOf(vertical))
}
}
| gpl-2.0 | a9290970588a73e96d36c98808d22ba6 | 52.285714 | 115 | 0.661467 | 5.52965 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/plain-jvm/src/main/kotlin/calls/transitive_calls/sourceCalls/TheVeryTransitiveStory.kt | 10 | 2780 | package calls.transitive_calls.sourceCalls
import transitiveStory.apiJvm.beginning.KotlinApiContainer
import transitiveStory.apiJvm.jbeginning.JavaApiContainer
import transitiveStory.bottomActual.apiCall.Jvm18JApiInheritor
import transitiveStory.bottomActual.apiCall.Jvm18KApiInheritor
import transitiveStory.bottomActual.intermediateSrc.InBottomActualIntermediate
import transitiveStory.bottomActual.intermediateSrc.IntermediateMPPClassInBottomActual
import transitiveStory.bottomActual.jApiCall.JApiCallerInJVM18
import transitiveStory.bottomActual.mppBeginning.BottomActualDeclarations
import transitiveStory.bottomActual.mppBeginning.regularTLfunInTheBottomActualCommmon
import transitiveStory.midActual.allTheCallsMirror.TheSameCallsButJava
import transitiveStory.midActual.commonSource.SomeMPPInTheCommon
import transitiveStory.midActual.commonSource.regularTLfunInTheMidActualCommmon
import transitiveStory.midActual.sourceCalls.allTheCalls.INeedAllTheSourceSets
import transitiveStory.midActual.sourceCalls.intemediateCall.SecondModCaller
class TheVeryTransitiveStory {
// ========= api calls ==========
// java
val jApiOne = JavaApiContainer()
// kotlin
val kApiOne = KotlinApiContainer()
// ========= mpp-bottom-actual calls ==========
// common source set
val interCallOne = regularTLfunInTheBottomActualCommmon("Some string from `mpp-mid-actual` module")
val interCallTwo = BottomActualDeclarations.inTheCompanionOfBottomActualDeclarations
val interCallThree = BottomActualDeclarations().simpleVal
// intermediate source set
val interCallFour = InBottomActualIntermediate().p
val interCallFive = IntermediateMPPClassInBottomActual()
// ========= jvm18 source set of `mpp-bottom-actual` ==========
// java
val interCallSix = JApiCallerInJVM18()
// kotlin
val interCallSeven = Jvm18KApiInheritor()
val interCallEight = Jvm18JApiInheritor()
val interCallNine = IntermediateMPPClassInBottomActual()
// ========= mpp-mid-actual calls ==========
// common source set
val midCommonCallOne = regularTLfunInTheMidActualCommmon("The message from `plain-jvm` module")
val midCommonCallTwo = SomeMPPInTheCommon().simpleVal
// intermediate source set
val midIntermediateCall = SecondModCaller()
class TransitiveInheritor : BottomActualDeclarations()
// ========= jvmWithJava source set of `mpp-mid-actual` ==========
// java
val midEndCallOne = TheSameCallsButJava()
// kotlin
val midEndCallTwo = INeedAllTheSourceSets()
}
fun <!LINE_MARKER!>main<!>() {
val arg = TheVeryTransitiveStory()
println("Test printing: `${arg.jApiOne}`; \n `${arg.kApiOne}`")
}
class SomeWComp {
companion object {
val callMe = "sfjn"
}
} | apache-2.0 | 0e267eea3b106f63b3c35b7eeafbf69c | 37.625 | 103 | 0.766187 | 4.641068 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/adapters/ArtistEntryAdapter.kt | 1 | 4948 | package com.kelsos.mbrc.adapters
import android.app.Activity
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.PopupMenu
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindString
import butterknife.BindView
import butterknife.ButterKnife
import com.kelsos.mbrc.R
import com.kelsos.mbrc.data.library.Artist
import com.raizlabs.android.dbflow.list.FlowCursorList
import javax.inject.Inject
class ArtistEntryAdapter
@Inject constructor(context: Activity) : RecyclerView.Adapter<ArtistEntryAdapter.ViewHolder>() {
private val inflater: LayoutInflater = LayoutInflater.from(context)
private var data: FlowCursorList<Artist>? = null
private var listener: MenuItemSelectedListener? = null
fun setMenuItemSelectedListener(listener: MenuItemSelectedListener) {
this.listener = listener
}
/**
* Called when RecyclerView needs a new [ViewHolder] of the given type to represent
* an item.
*
*
* This new ViewHolder should be constructed with a new View that can represent the items
* of the given type. You can either create a new View manually or inflate it from an XML
* layout file.
*
*
* The new ViewHolder will be used to display items of the adapter using
* [.onBindViewHolder]. Since it will be re-used to display different
* items in the data set, it is a good idea to cache references to sub views of the View to
* avoid unnecessary [View.findViewById] calls.
* @param parent The ViewGroup into which the new View will be added after it is bound to
* * an adapter position.
* *
* @param viewType The view type of the new View.
* *
* @return A new ViewHolder that holds a View of the given view type.
* *
* @see .getItemViewType
* @see .onBindViewHolder
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = inflater.inflate(R.layout.listitem_single, parent, false)
val holder = ViewHolder(view)
holder.indicator.setOnClickListener {
val popupMenu = PopupMenu(it.context, it)
popupMenu.inflate(R.menu.popup_artist)
popupMenu.setOnMenuItemClickListener { menuItem ->
val position = holder.adapterPosition.toLong()
val artist = data?.getItem(position) ?: return@setOnMenuItemClickListener false
listener?.onMenuItemSelected(menuItem, artist)
true
}
popupMenu.show()
}
holder.itemView.setOnClickListener {
val position = holder.adapterPosition.toLong()
val artist = data?.getItem(position) ?: return@setOnClickListener
listener?.onItemClicked(artist)
}
return holder
}
/**
* Called by RecyclerView to display the data at the specified position. This method
* should update the contents of the [ViewHolder.itemView] to reflect the item at
* the given position.
*
*
* Note that unlike [android.widget.ListView], RecyclerView will not call this
* method again if the position of the item changes in the data set unless the item itself
* is invalidated or the new position cannot be determined. For this reason, you should only
* use the `position` parameter while acquiring the related data item inside this
* method and should not keep a copy of it. If you need the position of an item later on
* (e.g. in a click listener), use [ViewHolder.getPosition] which will have the
* updated position.
* @param holder The ViewHolder which should be updated to represent the contents of the
* * item at the given position in the data set.
* *
* @param position The position of the item within the adapter's data set.
*/
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val artist = data?.getItem(position.toLong())
artist?.let {
holder.title.text = if (it.artist.isNullOrBlank()) {
holder.empty
} else {
it.artist
}
}
}
/**
* Returns the total number of items in the data set hold by the adapter.
* @return The total number of items in this adapter.
*/
override fun getItemCount(): Int {
return data?.count?.toInt() ?: 0
}
fun refresh() {
data?.refresh()
notifyDataSetChanged()
}
interface MenuItemSelectedListener {
fun onMenuItemSelected(menuItem: MenuItem, artist: Artist)
fun onItemClicked(artist: Artist)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@BindView(R.id.line_one)
lateinit var title: TextView
@BindView(R.id.ui_item_context_indicator)
lateinit var indicator: LinearLayout
@BindString(R.string.empty)
lateinit var empty: String
init {
ButterKnife.bind(this, itemView)
}
}
fun update(data: FlowCursorList<Artist>) {
this.data = data
notifyDataSetChanged()
}
}
| gpl-3.0 | ca68dac2ad76d4583e1b093802b4e405 | 32.432432 | 96 | 0.71827 | 4.518721 | false | false | false | false |
team401/SnakeSkin | SnakeSkin-FRC/src/main/kotlin/org/snakeskin/dsl/Auto.kt | 1 | 1995 | package org.snakeskin.dsl
import org.snakeskin.auto.steps.*
import org.snakeskin.measure.time.TimeMeasureSeconds
/**
* @author Cameron Earle
* @version 8/9/2018
*
*/
abstract class AutoStepBuilder<T: AutoStep>: IBuilder<T> {
protected val steps = arrayListOf<AutoStep>()
private fun addStep(autoStep: AutoStep) {
steps.add(autoStep)
}
fun parallel(setup: ParallelAutoStepBuilder.() -> Unit) {
val parallelBuilder = ParallelAutoStepBuilder()
parallelBuilder.setup()
addStep(parallelBuilder.build())
}
fun sequential(setup: SequentialAutoStepBuilder.() -> Unit) {
val sequentialBuilder = SequentialAutoStepBuilder()
sequentialBuilder.setup()
addStep(sequentialBuilder.build())
}
fun step(action: () -> Unit) {
addStep(LambdaStep(action))
}
fun step(autoStep: AutoStep) {
addStep(autoStep)
}
fun delay(amount: TimeMeasureSeconds) {
addStep(DelayStep(amount))
}
fun debug(output: Any) {
addStep(LambdaStep { println(output) })
}
fun waitFor(timeout: TimeMeasureSeconds = TimeMeasureSeconds(-1.0), condition: () -> Boolean) {
addStep(WaitStep(timeout, condition))
}
}
class ParallelAutoStepBuilder: AutoStepBuilder<ParallelSteps>() {
override fun build(): ParallelSteps {
return ParallelSteps(*steps.toTypedArray())
}
}
class SequentialAutoStepBuilder: AutoStepBuilder<SequentialSteps>() {
override fun build(): SequentialSteps {
return SequentialSteps(*steps.toTypedArray())
}
}
/**
* Creates an auto routine. This would be called inside of the "assembleAuto" function.
* It is used in the following context:
*
* override fun assembleAuto(): SequentialSteps {
* return auto {
* ...
* }
* }
*/
fun auto(setup: SequentialAutoStepBuilder.() -> Unit): SequentialSteps {
val builder = SequentialAutoStepBuilder()
builder.setup()
return builder.build()
} | gpl-3.0 | f65548493056527a1185e1adfbb7cd33 | 24.922078 | 99 | 0.666165 | 4.413717 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/habit/usecase/CreateHabitItemsUseCase.kt | 1 | 3622 | package io.ipoli.android.habit.usecase
import io.ipoli.android.common.UseCase
import io.ipoli.android.habit.data.Habit
import org.threeten.bp.LocalDate
class CreateHabitItemsUseCase :
UseCase<CreateHabitItemsUseCase.Params, List<CreateHabitItemsUseCase.HabitItem>> {
override fun execute(parameters: Params): List<HabitItem> {
val currentDate = parameters.currentDate
val habits = parameters.habits.sortedWith(
compareByDescending<Habit> { it.shouldBeDoneOn(currentDate) }
.thenBy { it.isCompletedForDate(currentDate) }
.thenByDescending { if (it.isUnlimited) 1 else it.timesADay }
.thenByDescending { it.isGood }
)
val (todayHabits, otherDayHabits) = habits.partition { it.shouldBeDoneOn(currentDate) }
return when {
todayHabits.isNotEmpty() && otherDayHabits.isNotEmpty() ->
listOf(HabitItem.TodaySection) +
todayHabits.map {
val isCompleted = it.isCompletedForDate(currentDate)
HabitItem.Today(
habit = it,
isCompleted = if (it.isGood) isCompleted else !isCompleted,
completedCount = it.completedCountForDate(currentDate),
canBeCompletedMoreTimes = it.canCompleteMoreForDate(currentDate),
isBestStreak = it.streak.best != 0 && it.streak.best == it.streak.current
)
} +
HabitItem.AnyOtherDaySection +
otherDayHabits.map {
HabitItem.OtherDay(
habit = it,
isBestStreak = it.streak.best != 0 && it.streak.best == it.streak.current
)
}
todayHabits.isNotEmpty() && otherDayHabits.isEmpty() ->
listOf(HabitItem.TodaySection) +
todayHabits.map {
val isCompleted = it.isCompletedForDate(currentDate)
HabitItem.Today(
habit = it,
isCompleted = if (it.isGood) isCompleted else !isCompleted,
completedCount = it.completedCountForDate(currentDate),
canBeCompletedMoreTimes = it.canCompleteMoreForDate(currentDate),
isBestStreak = it.streak.best != 0 && it.streak.best == it.streak.current
)
}
otherDayHabits.isNotEmpty() && todayHabits.isEmpty() ->
listOf(HabitItem.AnyOtherDaySection) +
otherDayHabits.map {
HabitItem.OtherDay(
habit = it,
isBestStreak = it.streak.best != 0 && it.streak.best == it.streak.current
)
}
else -> emptyList()
}
}
data class Params(val habits: List<Habit>, val currentDate: LocalDate = LocalDate.now())
sealed class HabitItem {
object TodaySection : HabitItem()
data class Today(
val habit: Habit,
val isCompleted: Boolean,
val canBeCompletedMoreTimes: Boolean,
val completedCount: Int,
val isBestStreak: Boolean
) : HabitItem()
object AnyOtherDaySection : HabitItem()
data class OtherDay(val habit: Habit, val isBestStreak: Boolean) : HabitItem()
}
} | gpl-3.0 | a0198f7601c747b5d324e0f91c30e85c | 42.130952 | 101 | 0.534787 | 5.899023 | false | false | false | false |
anitaa1990/DeviceInfo-Sample | deviceinfo/src/main/java/com/an/deviceinfo/userapps/UserAppInfo.kt | 1 | 966 | package com.an.deviceinfo.userapps
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import java.util.ArrayList
class UserAppInfo(private val context: Context) {
fun getInstalledApps(getSysPackages: Boolean): List<UserApps> {
val res = ArrayList<UserApps>()
val packs = context.packageManager.getInstalledPackages(0)
for (i in packs.indices) {
val p = packs[i]
val a = p.applicationInfo
if (!getSysPackages && a.flags and ApplicationInfo.FLAG_SYSTEM == 1) {
continue
}
val newInfo = UserApps()
newInfo.appName = p.applicationInfo.loadLabel(context.packageManager).toString()
newInfo.packageName = p.packageName
newInfo.versionName = p.versionName
newInfo.versionCode = p.versionCode
res.add(newInfo)
}
return res
}
}
| apache-2.0 | 1785efaeb3a2e83f450f53fb73054b22 | 32.310345 | 92 | 0.641822 | 4.644231 | false | false | false | false |
hzsweers/CatchUp | app/src/main/kotlin/io/sweers/catchup/ui/fragments/PagerFragment.kt | 1 | 15461 | /*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.ui.fragments
import android.animation.Animator
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Parcelable
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.animation.doOnEnd
import androidx.core.animation.doOnStart
import androidx.core.content.ContextCompat
import androidx.core.util.set
import androidx.fragment.app.Fragment
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator
import androidx.lifecycle.lifecycleScope
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.adapter.FragmentViewHolder
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.components.FragmentComponent
import dev.zacsweers.catchup.appconfig.AppConfig
import io.sweers.catchup.CatchUpPreferences
import io.sweers.catchup.R
import io.sweers.catchup.base.ui.InjectingBaseFragment
import io.sweers.catchup.base.ui.updateNavBarColor
import io.sweers.catchup.changes.ChangelogHelper
import io.sweers.catchup.databinding.FragmentPagerBinding
import io.sweers.catchup.injection.DaggerMap
import io.sweers.catchup.service.api.ServiceMeta
import io.sweers.catchup.ui.Scrollable
import io.sweers.catchup.ui.activity.SettingsActivity
import io.sweers.catchup.ui.fragments.service.ServiceFragment
import io.sweers.catchup.util.clearLightStatusBar
import io.sweers.catchup.util.isInNightMode
import io.sweers.catchup.util.resolveAttributeColor
import io.sweers.catchup.util.setLightStatusBar
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import ru.ldralighieri.corbind.material.offsetChanges
import javax.inject.Inject
import kotlin.math.abs
fun ServiceMeta.toServiceHandler() = ServiceHandler(
name,
icon,
themeColor
) { ServiceFragment.newInstance(id) }
data class ServiceHandler(
@StringRes val name: Int,
@DrawableRes val icon: Int,
@ColorRes val accent: Int,
val instantiator: () -> Fragment
)
@AndroidEntryPoint
class PagerFragment : InjectingBaseFragment<FragmentPagerBinding>() {
companion object {
private const val SETTINGS_ACTIVITY_REQUEST = 100
}
@Inject
lateinit var resolvedColorCache: ColorCache
@Inject
lateinit var serviceHandlers: Array<ServiceHandler>
@Inject
lateinit var changelogHelper: ChangelogHelper
@Inject
lateinit var catchUpPreferences: CatchUpPreferences
@Inject
lateinit var appConfig: AppConfig
private val rootLayout get() = binding.pagerFragmentRoot
private val tabLayout get() = binding.tabLayout
private val viewPager get() = binding.viewPager
private val toolbar get() = binding.toolbar
val appBarLayout get() = binding.appbarlayout
private val argbEvaluator = ArgbEvaluator()
private var statusBarColorAnimator: ValueAnimator? = null
private var tabLayoutColorAnimator: Animator? = null
private var tabLayoutIsPinned = false
private var canAnimateColor = true
private var lastPosition = 0
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
(appBarLayout.layoutParams as CoordinatorLayout.LayoutParams).behavior?.let { behavior ->
outState.run {
putParcelable(
"collapsingToolbarState",
behavior.onSaveInstanceState(rootLayout, appBarLayout)
)
}
}
}
override val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> FragmentPagerBinding =
FragmentPagerBinding::inflate
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewPager.offscreenPageLimit = 1
val pagerAdapter = object : FragmentStateAdapter(childFragmentManager, lifecycle) {
private val registeredFragments = SparseArray<Fragment>()
override fun getItemCount(): Int = serviceHandlers.size
override fun createFragment(position: Int): Fragment {
return serviceHandlers[position].instantiator().also {
registeredFragments[position] = it
}
}
// TODO not sure this is right, may need to listen to Fragment's onDestroy(View?) directly
override fun onViewDetachedFromWindow(holder: FragmentViewHolder) {
super.onViewDetachedFromWindow(holder)
registeredFragments.remove(holder.bindingAdapterPosition)
}
fun getRegisteredFragment(position: Int) = registeredFragments[position]
}
@ColorInt val colorPrimaryDark = view.context.resolveAttributeColor(com.google.android.material.R.attr.colorPrimaryDark)
val isInNightMode = view.context.isInNightMode()
if (!isInNightMode) {
// Start with a light status bar in normal mode
appBarLayout.setLightStatusBar(appConfig)
}
viewLifecycleOwner.lifecycleScope.launch {
appBarLayout.offsetChanges()
.distinctUntilChanged()
.collect { offset ->
if (offset == -toolbar.height) {
statusBarColorAnimator?.cancel()
tabLayoutIsPinned = true
val newStatusColor = [email protected](
tabLayout.selectedTabPosition
)
statusBarColorAnimator = ValueAnimator.ofArgb(colorPrimaryDark, newStatusColor)
.apply {
addUpdateListener { animation ->
[email protected]()
.window.statusBarColor = animation.animatedValue as Int
}
duration = 200
interpolator = LinearOutSlowInInterpolator()
start()
}
appBarLayout.clearLightStatusBar(appConfig)
} else {
val wasPinned = tabLayoutIsPinned
tabLayoutIsPinned = false
if (wasPinned) {
statusBarColorAnimator?.cancel()
statusBarColorAnimator = ValueAnimator.ofArgb(
[email protected]()
.window
.statusBarColor,
colorPrimaryDark
).apply {
addUpdateListener { animation ->
[email protected]()
.window.statusBarColor = animation.animatedValue as Int
}
duration = 200
interpolator = DecelerateInterpolator()
if (!isInNightMode) {
appBarLayout.setLightStatusBar(appConfig)
}
start()
}
}
}
}
}
toolbar.inflateMenu(R.menu.main)
toolbar.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.settings -> {
startActivityForResult(
Intent(activity, SettingsActivity::class.java),
SETTINGS_ACTIVITY_REQUEST
)
return@setOnMenuItemClickListener true
}
}
false
}
// Initial title
toolbar.title = resources.getString(serviceHandlers[0].name)
// Set the initial color
@ColorInt val initialColor = getAndSaveColor(0)
tabLayout.setBackgroundColor(initialColor)
viewPager.adapter = pagerAdapter
TabLayoutMediator(tabLayout, viewPager) { tab, _ ->
viewPager.setCurrentItem(tab.position, true)
}.attach()
changelogHelper.bindWith(toolbar, initialColor) {
getAndSaveColor(tabLayout.selectedTabPosition)
}
// Set icons
serviceHandlers.forEachIndexed { index, serviceHandler ->
tabLayout.getTabAt(index)?.icon = VectorDrawableCompat.create(
resources,
serviceHandler.icon,
null
)
}
// Animate color changes
// adapted from http://kubaspatny.github.io/2014/09/18/viewpager-background-transition/
viewPager.registerOnPageChangeCallback(
object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
if (canAnimateColor) {
val color: Int = if (position < pagerAdapter.itemCount - 1 && position < serviceHandlers.size - 1) {
argbEvaluator.evaluate(
positionOffset,
getAndSaveColor(position),
getAndSaveColor(position + 1)
) as Int
} else {
getAndSaveColor(serviceHandlers.size - 1)
}
tabLayout.setBackgroundColor(color)
if (tabLayoutIsPinned) {
activity?.window?.statusBarColor = color
}
activity?.updateNavBarColor(
color,
context = view.context,
uiPreferences = catchUpPreferences,
appConfig = appConfig
)
}
}
override fun onPageSelected(position: Int) {}
override fun onPageScrollStateChanged(state: Int) {
if (state == ViewPager2.SCROLL_STATE_IDLE) {
canAnimateColor = true
}
}
}
)
tabLayout.addOnTabSelectedListener(
object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
val position = tab.position
toolbar.setTitle(serviceHandlers[position].name)
// If we're switching between more than one page, we just want to manually set the color
// once rather than let the usual page scroll logic cycle through all the colors in a weird
// flashy way.
if (abs(lastPosition - position) > 1) {
canAnimateColor = false
// Start with the current tablayout color to feel more natural if we're in between
@ColorInt val startColor = (tabLayout.background as ColorDrawable).color
@ColorInt val endColor = getAndSaveColor(position)
tabLayoutColorAnimator?.cancel()
ValueAnimator.ofFloat(0f, 1f)
.run {
interpolator = FastOutSlowInInterpolator() // TODO Use singleton
duration = 400
doOnStart {
tabLayoutColorAnimator = it
}
doOnEnd {
removeAllUpdateListeners()
tabLayoutColorAnimator = null
}
addUpdateListener { animator ->
@ColorInt val color = argbEvaluator.evaluate(
animator.animatedValue as Float,
startColor,
endColor
) as Int
tabLayout.setBackgroundColor(color)
if (tabLayoutIsPinned) {
activity?.window?.statusBarColor = color
}
activity?.updateNavBarColor(
color,
context = view.context,
uiPreferences = catchUpPreferences,
appConfig = appConfig
)
}
start()
}
}
lastPosition = position
}
override fun onTabUnselected(tab: TabLayout.Tab) {}
override fun onTabReselected(tab: TabLayout.Tab) {
pagerAdapter.getRegisteredFragment(tab.position).let {
if (it is Scrollable) {
it.onRequestScrollToTop()
appBarLayout.setExpanded(true, true)
}
}
}
}
)
savedInstanceState?.run {
getParcelable<Parcelable>("collapsingToolbarState")?.let {
(appBarLayout.layoutParams as CoordinatorLayout.LayoutParams).behavior
?.onRestoreInstanceState(rootLayout, appBarLayout, it)
}
}
}
@ColorInt
private fun getAndSaveColor(position: Int): Int {
dayOnlyContext?.let {
if (resolvedColorCache[position] == R.color.no_color) {
resolvedColorCache[position] = ContextCompat.getColor(
it,
serviceHandlers[position].accent
)
}
}
return resolvedColorCache[position]
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == SETTINGS_ACTIVITY_REQUEST) {
if (resultCode == SettingsActivity.SETTINGS_RESULT_DATA && data != null) {
data.extras?.let { extras ->
if (extras.getBoolean(SettingsActivity.NIGHT_MODE_UPDATED, false) ||
extras.getBoolean(SettingsActivity.SERVICE_ORDER_UPDATED, false)
) {
activity?.recreate()
}
if (extras.getBoolean(SettingsActivity.NAV_COLOR_UPDATED, false)) {
activity?.updateNavBarColor(
color = (tabLayout.background as ColorDrawable).color,
context = requireView().context,
recreate = true,
uiPreferences = catchUpPreferences,
appConfig = appConfig
)
}
}
}
}
}
@InstallIn(FragmentComponent::class)
@dagger.Module
object Module {
@Provides
fun provideServiceHandlers(
sharedPrefs: SharedPreferences,
serviceMetas: DaggerMap<String, ServiceMeta>,
catchUpPreferences: CatchUpPreferences
): Array<ServiceHandler> {
check(serviceMetas.isNotEmpty()) {
"No services found!"
}
val currentOrder = catchUpPreferences.servicesOrder?.split(",") ?: emptyList()
return (
serviceMetas.values
.filter(ServiceMeta::enabled)
.filter { sharedPrefs.getBoolean(it.enabledPreferenceKey, true) }
.sortedBy { currentOrder.indexOf(it.id) }
.map(ServiceMeta::toServiceHandler)
)
.toTypedArray()
}
@Provides
fun provideColorCache(serviceHandlers: Array<ServiceHandler>) = ColorCache(
IntArray(
serviceHandlers.size
).apply { fill(R.color.no_color) }
)
}
}
// TODO This is cover for https://github.com/google/dagger/issues/1593
class ColorCache(val cache: IntArray) {
operator fun get(index: Int) = cache[index]
operator fun set(index: Int, value: Int) {
cache[index] = value
}
}
| apache-2.0 | 9751bb1421dc170cb66037aca9f21825 | 34.706697 | 124 | 0.667292 | 5.274991 | false | false | false | false |
GunoH/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/spellcheck/GrazieSpellchecker.kt | 5 | 4866 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie.spellcheck
import ai.grazie.detector.heuristics.rule.RuleFilter
import ai.grazie.utils.toLinkedSet
import com.intellij.grazie.GrazieConfig
import com.intellij.grazie.GraziePlugin
import com.intellij.grazie.ide.msg.GrazieStateLifecycle
import com.intellij.grazie.jlanguage.Lang
import com.intellij.grazie.jlanguage.LangTool
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.ApplicationUtil
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.ClassLoaderUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import org.languagetool.JLanguageTool
import org.languagetool.rules.spelling.SpellingCheckRule
import java.util.concurrent.Callable
object GrazieSpellchecker : GrazieStateLifecycle {
private const val MAX_SUGGESTIONS_COUNT = 3
private val filter by lazy { RuleFilter.withAllBuiltIn() }
@OptIn(ExperimentalCoroutinesApi::class)
private val executeScope = CoroutineScope(ApplicationManager.getApplication().coroutineScope.coroutineContext +
Dispatchers.Default.limitedParallelism(1))
private fun filterCheckers(word: String): Set<SpellerTool> {
val checkers = this.checkers.value
if (checkers.isEmpty()) {
return emptySet()
}
val preferred = filter.filter(listOf(word)).preferred
return checkers.asSequence().filter { checker -> preferred.any { checker.lang.equalsTo(it) } }.toSet()
}
data class SpellerTool(val tool: JLanguageTool, val lang: Lang, val speller: SpellingCheckRule, val suggestLimit: Int) {
fun check(word: String): Boolean? = synchronized(speller) {
if (word.isBlank()) return true
ClassLoaderUtil.computeWithClassLoader<Boolean, Throwable>(GraziePlugin.classLoader) {
if (speller.match(tool.getRawAnalyzedSentence(word)).isEmpty()) {
if (!speller.isMisspelled(word)) true
else {
// if the speller does not return matches, but the word is still misspelled (not in the dictionary),
// then this word was ignored by the rule (e.g. alien word), and we cannot be sure about its correctness
// let's try adding a small change to a word to see if it's alien
val mutated = word + word.last() + word.last()
if (speller.match(tool.getRawAnalyzedSentence(mutated)).isEmpty()) null else true
}
} else false
}
}
fun suggest(text: String): Set<String> = synchronized(speller) {
ClassLoaderUtil.computeWithClassLoader<Set<String>, Throwable>(GraziePlugin.classLoader) {
speller.match(tool.getRawAnalyzedSentence(text))
.flatMap { match ->
match.suggestedReplacements.map {
text.replaceRange(match.fromPos, match.toPos, it)
}
}
.take(suggestLimit).toSet()
}
}
}
@Volatile
private var checkers: Lazy<Collection<SpellerTool>> = initCheckers()
private fun initCheckers(): Lazy<Collection<SpellerTool>> {
return lazy(LazyThreadSafetyMode.PUBLICATION) {
GrazieConfig.get().availableLanguages.asSequence()
.filterNot { it.isEnglish() }
.mapNotNull { lang ->
ProgressManager.checkCanceled()
val tool = LangTool.getTool(lang)
tool.allSpellingCheckRules.firstOrNull()?.let {
SpellerTool(tool, lang, it, MAX_SUGGESTIONS_COUNT)
}
}
.toLinkedSet()
}
}
override fun update(prevState: GrazieConfig.State, newState: GrazieConfig.State) {
checkers = initCheckers()
executeScope.launch { checkers.value }
}
fun isCorrect(word: String): Boolean? {
val myCheckers = filterCheckers(word)
var isAlien = true
myCheckers.forEach { speller ->
when (speller.check(word)) {
true -> return true
false -> isAlien = false
else -> {}
}
}
return if (isAlien) null else false
}
/**
* Checks text for spelling mistakes.
*/
fun getSuggestions(word: String): Collection<String> {
val filtered = filterCheckers(word)
if (filtered.isEmpty()) {
return emptyList()
}
val indicator = EmptyProgressIndicator.notNullize(ProgressManager.getGlobalProgressIndicator())
return ApplicationUtil.runWithCheckCanceled(Callable {
filtered
.asSequence()
.map { speller ->
indicator.checkCanceled()
speller.suggest(word)
}
.flatten()
.toLinkedSet()
}, indicator)
}
}
| apache-2.0 | d41264c21050d33f49eb8429c47e87e6 | 35.586466 | 140 | 0.694821 | 4.56045 | false | false | false | false |
GunoH/intellij-community | plugins/evaluation-plugin/core/src/com/intellij/cce/report/HtmlColorClasses.kt | 8 | 337 | package com.intellij.cce.report
object HtmlColorClasses : ReportColors<String> {
override val perfectSortingColor = "perfect"
override val goodSortingColor = "good"
override val badSortingColor = "bad"
override val notFoundColor = "not-found"
override val absentLookupColor = "absent"
override val goodSortingThreshold = 5
} | apache-2.0 | 086cc75b2d0cad989de1a37c3c3c232e | 32.8 | 48 | 0.777448 | 4.109756 | false | false | false | false |
aerisweather/AerisAndroidSDK | Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/view/locations/MyLocsViewModel.kt | 1 | 1643 | package com.example.demoaerisproject.view.locations
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.demoaerisproject.data.room.MyPlace
import com.example.demoaerisproject.data.room.MyPlaceRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MyLocationViewModel @Inject constructor(
private val myPlaceRepository: MyPlaceRepository
) : ViewModel() {
protected val _event = MutableLiveData<MyLocationEvent>()
val event: LiveData<MyLocationEvent> = _event
init {
initDbListener()
}
fun initDbListener() {
_event.value = MyLocationEvent.InProgress
kotlin.runCatching {
viewModelScope.launch {
myPlaceRepository.allPlaces.collect {
_event.value = MyLocationEvent.Success(it)
}
}
}.onFailure {
_event.value = MyLocationEvent.Error(it.toString())
Log.e("LocationSearchViewModel.initEventListener", it.toString())
}
}
fun selectAsMyLocation(myPlace: MyPlace) {
viewModelScope.launch {
myPlaceRepository.resetMyLocFalse()
myPlace.myLoc = true
myPlaceRepository.update(myPlace)
}
}
}
sealed class MyLocationEvent {
object InProgress : MyLocationEvent()
class Success(val response: List<MyPlace>) : MyLocationEvent()
class Error(val msg: String) : MyLocationEvent()
} | mit | 196533e075db558328cf288675a8c693 | 29.444444 | 77 | 0.698722 | 4.933934 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/analytics/aggregated/mock/AggregatedSamples.kt | 1 | 3840 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.analytics.aggregated.mock
import org.hisp.dhis.android.core.category.Category
import org.hisp.dhis.android.core.category.CategoryOption
import org.hisp.dhis.android.core.dataelement.DataElement
import org.hisp.dhis.android.core.indicator.Indicator
import org.hisp.dhis.android.core.organisationunit.OrganisationUnit
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitLevel
import org.hisp.dhis.android.core.period.Period
import org.hisp.dhis.android.core.program.ProgramIndicator
object AggregatedSamples {
val dataElement1 = DataElement.builder()
.uid("fbfJHSPpUQD")
.displayName("ANC 1st visit")
.build()
val dataElement2 = DataElement.builder()
.uid("cYeuwXTCPkU")
.displayName("ANC 2nd visit")
.build()
val programIndicator1 = ProgramIndicator.builder()
.uid("p2Zxg0wcPQ3")
.displayName("BCG doses")
.build()
val indicator1 = Indicator.builder()
.uid("Uvn6LCg7dVU")
.displayName("ANC 1 Coverage")
.build()
val cc1 = Category.builder()
.uid("fMZEcRHuamy")
.displayName("Fixed / Outreach")
.build()
val co11 = CategoryOption.builder()
.uid("pq2XI5kz2BY")
.displayName("Fixed")
.build()
val co12 = CategoryOption.builder()
.uid("PT59n8BQbqM")
.displayName("Outreach")
.build()
val cc2 = Category.builder()
.uid("cX5k9anHEHd")
.displayName("Gender")
.build()
val co21 = CategoryOption.builder()
.uid("jRbMi0aBjYn")
.displayName("Male")
.build()
val period1 = Period.builder()
.periodId("202103")
.build()
val period2 = Period.builder()
.periodId("202104")
.build()
val orgunit1 = OrganisationUnit.builder()
.uid("DiszpKrYNg8")
.displayName("Ngelehun")
.build()
val orgunit2 = OrganisationUnit.builder()
.uid("g8upMTyEZGZ")
.displayName("Njandama")
.build()
@SuppressWarnings("MagicNumber")
val level3 = OrganisationUnitLevel.builder()
.uid("VVkwUWGNpNR")
.displayName("Level 3")
.level(3)
.build()
}
| bsd-3-clause | d67df17badd6a3d6a71a63482c7d3cad | 33.909091 | 83 | 0.6875 | 4.102564 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/ui/discover/base/BaseDiscoverFragment.kt | 1 | 4286 | package com.ashish.movieguide.ui.discover.base
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import com.ashish.movieguide.R
import com.ashish.movieguide.data.models.FilterQuery
import com.ashish.movieguide.data.models.Movie
import com.ashish.movieguide.data.models.TVShow
import com.ashish.movieguide.di.multibindings.AbstractComponent
import com.ashish.movieguide.di.multibindings.fragment.FragmentComponentBuilder
import com.ashish.movieguide.di.multibindings.fragment.FragmentComponentBuilderHost
import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewFragment
import com.ashish.movieguide.ui.common.adapter.ViewType
import com.ashish.movieguide.ui.discover.filter.FilterBottomSheetDialogFragment
import com.ashish.movieguide.ui.movie.detail.MovieDetailActivity
import com.ashish.movieguide.ui.tvshow.detail.TVShowDetailActivity
import com.ashish.movieguide.utils.Constants.ADAPTER_TYPE_MOVIE
import com.ashish.movieguide.utils.Constants.ADAPTER_TYPE_TV_SHOW
import javax.inject.Inject
import javax.inject.Provider
/**
* Created by Ashish on Jan 07.
*/
abstract class BaseDiscoverFragment<I : ViewType, P : BaseDiscoverPresenter<I>>
: BaseRecyclerViewFragment<I, DiscoverView<I>, P>(), DiscoverView<I>, FragmentComponentBuilderHost {
companion object {
const val DISCOVER_MOVIE = 0
const val DISCOVER_TV_SHOW = 1
private const val RC_FILTER_FRAGMENT = 1001
}
@Inject
lateinit var componentBuilders: Map<Class<out Fragment>, @JvmSuppressWildcards Provider<FragmentComponentBuilder<*, *>>>
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
swipeRefreshLayout.isEnabled = false
}
override fun <F : Fragment, B : FragmentComponentBuilder<F, AbstractComponent<F>>>
getFragmentComponentBuilder(fragmentKey: Class<F>, builderType: Class<B>): B {
return builderType.cast(componentBuilders[fragmentKey]!!.get())
}
override fun loadData() = presenter?.filterContents()
override fun getAdapterType(): Int {
if (isMovie()) {
return ADAPTER_TYPE_MOVIE
} else {
return ADAPTER_TYPE_TV_SHOW
}
}
override fun getEmptyTextId() = if (isMovie()) {
R.string.no_movies_available
} else {
R.string.no_tv_shows_available
}
override fun getEmptyImageId() = if (isMovie()) {
R.drawable.ic_movie_white_100dp
} else {
R.drawable.ic_tv_white_100dp
}
override fun getTransitionNameId(position: Int): Int {
if (isMovie()) {
return R.string.transition_movie_poster
} else {
return R.string.transition_tv_poster
}
}
override fun getDetailIntent(position: Int): Intent? {
if (isMovie()) {
val movie = recyclerViewAdapter.getItem<Movie>(position)
return MovieDetailActivity.createIntent(activity, movie)
} else {
val tvShow = recyclerViewAdapter.getItem<TVShow>(position)
return TVShowDetailActivity.createIntent(activity, tvShow)
}
}
abstract fun getDiscoverMediaType(): Int
private fun isMovie() = getDiscoverMediaType() == DISCOVER_MOVIE
override fun clearFilteredData() = recyclerViewAdapter.clearAll()
override fun showFilterBottomSheetDialog(filterQuery: FilterQuery) {
val filterBottomSheetFragment = FilterBottomSheetDialogFragment.newInstance(isMovie(), filterQuery)
filterBottomSheetFragment.setTargetFragment(this, RC_FILTER_FRAGMENT)
filterBottomSheetFragment.show(childFragmentManager, filterBottomSheetFragment.tag)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_discover, menu)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_filter -> performAction { presenter?.onFilterMenuItemClick() }
else -> super.onOptionsItemSelected(item)
}
} | apache-2.0 | 82f4c57400ae4949a098c020d63bb9ea | 36.605263 | 124 | 0.726785 | 4.593783 | false | false | false | false |
martijn-heil/wac-core | src/main/kotlin/tk/martijn_heil/wac_core/craft/vessel/sail/Unireme.kt | 1 | 5734 | /*
* wac-core
* Copyright (C) 2016 Martijn Heil
*
* 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 tk.martijn_heil.wac_core.craft.vessel.sail
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.block.Block
import org.bukkit.block.Sign
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.HandlerList
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerInteractEvent
import org.bukkit.plugin.Plugin
import tk.martijn_heil.wac_core.craft.RowingDirection
import tk.martijn_heil.wac_core.craft.vessel.SimpleRudder
import java.util.*
import java.util.logging.Logger
class Unireme private constructor(plugin: Plugin, logger: Logger, blocks: Collection<Block>, rotationPoint: Location, sails: Collection<SimpleSail>, rudder: SimpleRudder, rowingSign: Sign, rowingDirectionSign: Sign) : SimpleSailingVessel(plugin, logger, blocks, rotationPoint, sails, rudder, rowingSign, rowingDirectionSign) {
override var normalMaxSpeed: Int = 7000
private val listener2 = object : Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
fun onPlayerInteract(e: PlayerInteractEvent) {
if(e.clickedBlock == null) return
val state = e.clickedBlock.state
if (state is Sign && state.lines[0] == "[Craft]" && containsBlock(e.clickedBlock)) {
e.isCancelled = true
}
}
}
override fun init() {
super.init()
plugin.server.pluginManager.registerEvents(listener2, plugin)
}
override fun close() {
super.close()
HandlerList.unregisterAll(listener2)
}
companion object {
fun detect(plugin: Plugin, logger: Logger, detectionLoc: Location): SimpleSailingVessel {
val sails: MutableCollection<SimpleSail> = ArrayList()
try {
val maxSize = 5000
val allowedBlocks: Collection<Material> = Material.values().filter { it != Material.AIR && it != Material.WATER && it != Material.STATIONARY_WATER && it != Material.LAVA && it != Material.STATIONARY_LAVA }
val blocks: Collection<Block>
// Detect vessel
try {
logger.info("Detecting unireme at " + detectionLoc.x + "x " + detectionLoc.y + "y " + detectionLoc.z + "z")
blocks = tk.martijn_heil.wac_core.craft.util.detect(detectionLoc, allowedBlocks, maxSize)
} catch(e: Exception) {
logger.info("Failed to detect sailing vessel: " + (e.message ?: "unknown error"))
throw IllegalStateException(e.message)
}
val signs = blocks.map { it.state }.filter { it is Sign }.map { it as Sign }
val rotationPointSign = signs.find { it.lines[0] == "[RotationPoint]" }
if (rotationPointSign == null) {
logger.warning("Could not detect rotation point")
throw IllegalStateException("Could not detect rotation point.")
}
val rotationPoint = rotationPointSign.location
// Detect rudder
val rudderSign = signs.find { it.lines[0] == "[Rudder]" } ?: throw IllegalStateException("No rudder found.")
logger.info("Found rudder sign at " + rudderSign.x + " " + rudderSign.y + " " + rudderSign.z)
val rudder = SimpleRudder(rudderSign)
val rowingSign = signs.find { it.lines[0] == "[Rowing]" } ?: throw IllegalStateException("No rowing sign found.")
rowingSign.setLine(1, "false")
rowingSign.update(true, false)
logger.info("Found rowing sign at " + rowingSign.x + " " + rowingSign.y + " " + rudderSign.z)
val rowingDirectionSign = signs.find { it.lines[0] == "[RowingDirection]" } ?: throw IllegalStateException("No rowing direction sign found.")
if(rowingDirectionSign.lines[1] == "") rowingDirectionSign.setLine(1, RowingDirection.FORWARD.toString().toLowerCase())
logger.info("Found RowingDirection sign at " + rowingDirectionSign.x + " " + rowingDirectionSign.y + " " + rowingDirectionSign.z)
// Detect sails
signs.filter { it.lines[0] == "[Sail]" }.forEach {
logger.fine("Found sail sign at " + it.x + " " + it.y + " " + it.z)
sails.add(SimpleSail(plugin, it))
}
if (sails.isEmpty()) throw IllegalStateException("No sails found.")
val unireme = Unireme(plugin, logger, blocks, rotationPoint, sails, rudder, rowingSign, rowingDirectionSign)
unireme.init()
return unireme
} catch(t: Throwable) {
sails.forEach { it.isHoisted = true; it.close() }
throw t
}
}
}
} | gpl-3.0 | 4a28231ecb0fb16016e351a932584933 | 47.878261 | 326 | 0.609348 | 4.518519 | false | false | false | false |
sph-u/failchat | src/test/kotlin/failchat/experiment/Jna.kt | 1 | 3265 | package failchat.experiment
import com.sun.jna.platform.win32.User32
import com.sun.jna.platform.win32.WinDef.HWND
import javafx.application.Application
import javafx.stage.Stage
import javafx.stage.StageStyle
import java.util.concurrent.Executors
fun main(args: Array<String>) {
Application.launch(App::class.java)
}
private val user32 = User32.INSTANCE
private val executorService = Executors.newSingleThreadScheduledExecutor()
class App: Application() {
override fun start(primaryStage: Stage) {
// primaryStage.height = 300.0
// primaryStage.width = 300.0
// primaryStage.isAlwaysOnTop = true
// primaryStage.show()
// val hWnd = HWND(getWindowPointer(primaryStage))
// makeWindowClickTransparent(hWnd)
// executorService.schedule({
// makeWindowClickNonTransparent(hWnd)
// executorService.shutdown()
// }, 5, SECONDS)
val stages = buildStages()
stages.forEach {
it.show()
// broken after java 11
// val hWnd = HWND(getWindowPointer(it))
// val style = getWindowStyle(hWnd)
// println("style for ${it.style} stage: $style")
// it.isAlwaysOnTop = true
// val styleOnTop = getWindowStyle(hWnd)
// println("style with onTop option for ${it.style} stage: $styleOnTop")
}
}
private fun buildStages(): List<Stage> {
return listOf(StageStyle.DECORATED, StageStyle.UNDECORATED, StageStyle.TRANSPARENT)
.map {
val stage = Stage(it)
stage.height = 300.0
stage.width = 300.0
stage.show()
stage
}
}
}
private fun getWindowStyle(hWnd: HWND): Int {
return user32.GetWindowLong(hWnd, User32.GWL_EXSTYLE)
}
private fun makeWindowClickTransparent(hWnd: HWND) {
val mask = user32.GetWindowLong(hWnd, User32.GWL_EXSTYLE)
println("mask: $mask")
val newMask = (mask or User32.WS_EX_LAYERED or User32.WS_EX_TRANSPARENT)
println("new mask: $newMask")
user32.SetWindowLong(hWnd, User32.GWL_EXSTYLE, newMask)
}
private fun makeWindowClickNonTransparent(hWnd: HWND) {
val mask = user32.GetWindowLong(hWnd, User32.GWL_EXSTYLE)
println("mask: $mask")
val newMask = (mask and User32.WS_EX_LAYERED.inv() and User32.WS_EX_TRANSPARENT.inv())
println("new mask: $newMask")
user32.SetWindowLong(hWnd, User32.GWL_EXSTYLE, newMask)
}
//private fun getWindowPointer(stage: Stage): Pointer? {
// try {
// @Suppress("DEPRECATION")
// val tkStage = stage.impl_getPeer()
//
// val getPlatformWindow = tkStage.javaClass.getDeclaredMethod("getPlatformWindow")
// getPlatformWindow.isAccessible = true
// val platformWindow = getPlatformWindow.invoke(tkStage)
//
// val getNativeHandle = platformWindow.javaClass.getMethod("getNativeHandle")
// getNativeHandle.isAccessible = true
// val nativeHandle = getNativeHandle.invoke(platformWindow)
//
// return Pointer(nativeHandle as Long)
// } catch (t: Throwable) {
// System.err.println("Error getting Window Pointer. $t")
// return null
// }
//
//}
| mit | cb019af1590d655006965e09f327cc7c | 29.231481 | 91 | 0.642266 | 3.952785 | false | false | false | false |
dahlstrom-g/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/dependency/analyzer/util/ScopeUiUtil.kt | 8 | 6803 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.externalSystem.dependency.analyzer.util
import com.intellij.ide.nls.NlsMessages
import com.intellij.ide.plugins.newui.HorizontalLayout
import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerDependency.Scope
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.observable.properties.ObservableMutableProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.observable.util.bind
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.observable.util.whenItemSelected
import com.intellij.openapi.observable.util.whenMousePressed
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.ListUtil
import com.intellij.ui.components.DropDownLink
import com.intellij.ui.components.JBList
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.ThreeStateCheckBox
import org.apache.commons.lang.StringUtils
import java.awt.Component
import javax.swing.*
internal class SearchScopeSelector(property: ObservableMutableProperty<List<ScopeItem>>) : JPanel() {
init {
val dropDownLink = SearchScopeDropDownLink(property)
.apply { border = JBUI.Borders.empty(BORDER, ICON_TEXT_GAP / 2, BORDER, BORDER) }
val label = JLabel(ExternalSystemBundle.message("external.system.dependency.analyzer.scope.label"))
.apply { border = JBUI.Borders.empty(BORDER, BORDER, BORDER, ICON_TEXT_GAP / 2) }
.apply { labelFor = dropDownLink }
layout = HorizontalLayout(0)
border = JBUI.Borders.empty()
add(label)
add(dropDownLink)
}
}
private class SearchScopePopupContent(scopes: List<ScopeItem>) : JBList<ScopeProperty>() {
private val propertyGraph = PropertyGraph(isBlockPropagation = false)
private val anyScopeProperty = propertyGraph.lazyProperty(::suggestAnyScopeState)
private val scopeProperties = scopes.map { ScopeProperty.Just(it.scope, propertyGraph.lazyProperty { it.isSelected }) }
private fun suggestAnyScopeState(): ThreeStateCheckBox.State {
return when {
scopeProperties.all { it.property.get() } -> ThreeStateCheckBox.State.SELECTED
!scopeProperties.any { it.property.get() } -> ThreeStateCheckBox.State.NOT_SELECTED
else -> ThreeStateCheckBox.State.DONT_CARE
}
}
private fun suggestScopeState(currentState: Boolean): Boolean {
return when (anyScopeProperty.get()) {
ThreeStateCheckBox.State.SELECTED -> true
ThreeStateCheckBox.State.NOT_SELECTED -> false
ThreeStateCheckBox.State.DONT_CARE -> currentState
}
}
fun afterChange(listener: (List<ScopeItem>) -> Unit) {
for (scope in scopeProperties) {
scope.property.afterChange {
listener(scopeProperties.map { ScopeItem(it.scope, it.property.get()) })
}
}
}
init {
val anyScope = ScopeProperty.Any(anyScopeProperty)
model = createDefaultListModel(listOf(anyScope) + scopeProperties)
border = emptyListBorder()
cellRenderer = SearchScopePropertyRenderer()
selectionMode = ListSelectionModel.SINGLE_SELECTION
ListUtil.installAutoSelectOnMouseMove(this)
setupListPopupPreferredWidth(this)
whenMousePressed {
when (val scope = selectedValue) {
is ScopeProperty.Any -> scope.property.set(ThreeStateCheckBox.nextState(scope.property.get(), false))
is ScopeProperty.Just -> scope.property.set(!scope.property.get())
}
}
propertyGraph.afterPropagation {
repaint()
}
for (scope in scopeProperties) {
anyScopeProperty.dependsOn(scope.property) {
suggestAnyScopeState()
}
scope.property.dependsOn(anyScopeProperty) {
suggestScopeState(scope.property.get())
}
}
}
companion object {
fun createPopup(scopes: List<ScopeItem>, onChange: (List<ScopeItem>) -> Unit): JBPopup {
val content = SearchScopePopupContent(scopes)
content.afterChange(onChange)
return JBPopupFactory.getInstance()
.createComponentPopupBuilder(content, null)
.createPopup()
}
}
}
private class SearchScopePropertyRenderer : ListCellRenderer<ScopeProperty> {
override fun getListCellRendererComponent(
list: JList<out ScopeProperty>,
value: ScopeProperty,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component {
val checkBox = when (value) {
is ScopeProperty.Any ->
ThreeStateCheckBox(ExternalSystemBundle.message("external.system.dependency.analyzer.scope.any"))
.apply { isThirdStateEnabled = false }
.apply { state = value.property.get() }
.bind(value.property)
is ScopeProperty.Just ->
JCheckBox(value.scope.title)
.apply { [email protected] = value.property.get() }
.bind(value.property)
}
return checkBox
.apply { border = emptyListCellBorder(list, index, if (index > 0) 1 else 0) }
.apply { background = if (isSelected) list.selectionBackground else list.background }
.apply { foreground = if (isSelected) list.selectionForeground else list.foreground }
.apply { isOpaque = true }
.apply { isEnabled = list.isEnabled }
.apply { font = list.font }
}
}
private class SearchScopeDropDownLink(
property: ObservableMutableProperty<List<ScopeItem>>
) : DropDownLink<List<ScopeItem>>(
property.get(),
{ SearchScopePopupContent.createPopup(property.get(), it::selectedItem.setter) }
) {
override fun popupPoint() =
super.popupPoint()
.apply { x += insets.left }
override fun itemToString(item: List<ScopeItem>): @NlsSafe String {
return when {
item.all { it.isSelected } -> ExternalSystemBundle.message("external.system.dependency.analyzer.scope.any")
!item.any { it.isSelected } -> ExternalSystemBundle.message("external.system.dependency.analyzer.scope.none")
else -> {
val scopes = item.filter { it.isSelected }.map { it.scope.title }
StringUtils.abbreviate(NlsMessages.formatNarrowAndList(scopes), 30)
}
}
}
init {
autoHideOnDisable = false
foreground = JBUI.CurrentTheme.Label.foreground()
whenItemSelected { text = itemToString(selectedItem) }
bind(property)
}
}
internal class ScopeItem(
val scope: Scope,
val isSelected: Boolean
) {
override fun toString() = "$isSelected: $scope"
}
private sealed interface ScopeProperty {
class Any(val property: GraphProperty<ThreeStateCheckBox.State>) : ScopeProperty
class Just(val scope: Scope, val property: GraphProperty<Boolean>) : ScopeProperty
} | apache-2.0 | 02dd903b0a41a8ea848fc26fb2ba6717 | 37.011173 | 121 | 0.729825 | 4.475658 | false | false | false | false |
dahlstrom-g/intellij-community | python/src/com/jetbrains/python/sdk/PySdkRendering.kt | 3 | 5910 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.intellij.icons.AllIcons
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.LayeredIcon
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.SimpleTextAttributes
import com.jetbrains.python.PyBundle
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import org.jetbrains.annotations.Nls
import javax.swing.Icon
val noInterpreterMarker: String = "<${PyBundle.message("python.sdk.there.is.no.interpreter")}>"
fun name(sdk: Sdk): Triple<String?, String, String?> = name(sdk, sdk.name)
/**
* Returns modifier that shortly describes that is wrong with passed [sdk], [name] and additional info.
*/
fun name(sdk: Sdk, name: String): Triple<String?, String, String?> {
val modifier = when {
PythonSdkUtil.isInvalid(sdk) || PythonSdkType.hasInvalidRemoteCredentials(sdk) -> "invalid"
PythonSdkType.isIncompleteRemote(sdk) -> "incomplete"
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) -> "unsupported"
else -> null
}
val providedForSdk = PySdkProvider.EP_NAME.extensions.firstNotNullOfOrNull { it.getSdkAdditionalText(sdk) }
val secondary = providedForSdk ?: if (PythonSdkType.isRunAsRootViaSudo(sdk)) "[sudo]" else null
return Triple(modifier, name, secondary)
}
/**
* Returns a path to be rendered as the sdk's path.
*
* Initial value is taken from the [sdk],
* then it is converted to a path relative to the user home directory.
*
* Returns null if the initial path or the relative value are presented in the sdk's name.
*
* @see FileUtil.getLocationRelativeToUserHome
*/
fun path(sdk: Sdk): String? {
val name = sdk.name
val homePath = sdk.homePath ?: return null
if (sdk.isTargetBased()) {
return homePath
}
if (sdk.sdkAdditionalData is PyRemoteSdkAdditionalDataMarker) {
return homePath.takeIf { homePath !in name }
}
return homePath.let { FileUtil.getLocationRelativeToUserHome(it) }.takeIf { homePath !in name && it !in name }
}
/**
* Returns an icon to be used as the sdk's icon.
*
* Result is wrapped with [AllIcons.Actions.Cancel]
* if the sdk is local and does not exist, or remote and incomplete or has invalid credentials, or is not supported.
*
* @see PythonSdkUtil.isInvalid
* @see PythonSdkType.isIncompleteRemote
* @see PythonSdkType.hasInvalidRemoteCredentials
* @see LanguageLevel.SUPPORTED_LEVELS
*/
fun icon(sdk: Sdk): Icon? {
val flavor: PythonSdkFlavor? = when (sdk.sdkAdditionalData) {
!is PyRemoteSdkAdditionalDataMarker -> PythonSdkFlavor.getPlatformIndependentFlavor(sdk.homePath)
else -> null
}
val icon = flavor?.icon ?: ((sdk.sdkType as? SdkType)?.icon ?: return null)
val providedIcon = PySdkProvider.EP_NAME.extensions.firstNotNullOfOrNull { it.getSdkIcon(sdk) }
return when {
PythonSdkUtil.isInvalid(sdk) ||
PythonSdkType.isIncompleteRemote(sdk) ||
PythonSdkType.hasInvalidRemoteCredentials(sdk) ||
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) ->
wrapIconWithWarningDecorator(icon)
sdk is PyDetectedSdk -> IconLoader.getTransparentIcon(icon)
providedIcon != null -> providedIcon
else -> icon
}
}
/**
* Groups valid sdks associated with the [module] by types.
* Virtual environments, pipenv and conda environments are considered as [PyRenderedSdkType.VIRTUALENV].
* Remote interpreters are considered as [PyRenderedSdkType.REMOTE].
* All the others are considered as [PyRenderedSdkType.SYSTEM].
*
* @see Sdk.isAssociatedWithAnotherModule
* @see PythonSdkUtil.isVirtualEnv
* @see PythonSdkUtil.isCondaVirtualEnv
* @see PythonSdkUtil.isRemote
* @see PyRenderedSdkType
*/
fun groupModuleSdksByTypes(allSdks: List<Sdk>, module: Module?, invalid: (Sdk) -> Boolean): Map<PyRenderedSdkType, List<Sdk>> {
return allSdks
.asSequence()
.filter { !it.isAssociatedWithAnotherModule(module) && !invalid(it) }
.groupBy {
when {
PythonSdkUtil.isVirtualEnv(it) || PythonSdkUtil.isCondaVirtualEnv(it) -> PyRenderedSdkType.VIRTUALENV
PythonSdkUtil.isRemote(it) -> PyRenderedSdkType.REMOTE
else -> PyRenderedSdkType.SYSTEM
}
}
}
/**
* Order is important, sdks are rendered in the same order as the types are defined.
*
* @see groupModuleSdksByTypes
*/
enum class PyRenderedSdkType {
VIRTUALENV, SYSTEM, REMOTE
}
private fun wrapIconWithWarningDecorator(icon: Icon): LayeredIcon =
LayeredIcon(2).apply {
setIcon(icon, 0)
setIcon(AllIcons.Actions.Cancel, 1)
}
internal fun SimpleColoredComponent.customizeWithSdkValue(value: Any?, nullSdkName: @Nls String, nullSdkValue: Sdk?) {
when (value) {
is PySdkToInstall -> {
value.renderInList(this)
}
is Sdk -> {
appendName(value, name(value))
icon = icon(value)
}
is String -> append(value)
null -> {
if (nullSdkValue != null) {
appendName(nullSdkValue, name(nullSdkValue, nullSdkName))
icon = icon(nullSdkValue)
}
else {
append(nullSdkName)
}
}
}
}
private fun SimpleColoredComponent.appendName(sdk: Sdk, name: Triple<String?, String, String?>) {
val (modifier, primary, secondary) = name
if (modifier != null) {
append("[$modifier] $primary", SimpleTextAttributes.ERROR_ATTRIBUTES)
}
else {
append(primary)
}
if (secondary != null) {
append(" $secondary", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES)
}
path(sdk)?.let { append(" $it", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES) }
} | apache-2.0 | 79243a2cf9ebaccd970c1c91037a81ae | 33.16763 | 140 | 0.730795 | 4.273319 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/KotlinSdkCreationChecker.kt | 3 | 1286 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.test
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import org.jetbrains.kotlin.idea.framework.KotlinSdkType
import org.jetbrains.kotlin.idea.util.application.runReadAction
class KotlinSdkCreationChecker {
private val projectJdkTable: ProjectJdkTable
get() = runReadAction { ProjectJdkTable.getInstance() }
private val sdksBefore: Array<out Sdk> = projectJdkTable.allJdks
fun getKotlinSdks() = projectJdkTable.allJdks.filter { it.sdkType is KotlinSdkType }
private fun getCreatedKotlinSdks() =
projectJdkTable.allJdks.filter { !sdksBefore.contains(it) && it.sdkType is KotlinSdkType }
fun isKotlinSdkCreated() = getCreatedKotlinSdks().isNotEmpty()
fun removeNewKotlinSdk() {
ApplicationManager.getApplication().invokeAndWait {
runWriteAction {
getCreatedKotlinSdks().forEach { projectJdkTable.removeJdk(it) }
}
}
}
} | apache-2.0 | 88c9e2024ea45af336ee95f3234a70d0 | 39.21875 | 158 | 0.755832 | 4.85283 | false | false | false | false |
xmartlabs/Android-Base-Project | core/src/main/java/com/xmartlabs/bigbang/core/controller/EntityRepository.kt | 1 | 6905 | package com.xmartlabs.bigbang.core.controller
import androidx.annotation.CheckResult
import com.xmartlabs.bigbang.core.extensions.applyIoSchedulers
import com.xmartlabs.bigbang.core.extensions.observeOnIo
import com.xmartlabs.bigbang.core.extensions.subscribeOnIo
import com.xmartlabs.bigbang.core.model.EntityWithId
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.Single
/**
* [Controller] that provides all the helpers needed to perform CRUD operations with both the service and a local
* database.
* Clients of this class should extend it and expose the desired CRUD operations making use of the provided helpers.
* @param <Id> the type of the primary key
* *
* @param <E> the entity to be manipulated
* *
* @param <Condition> to be able to filter the entities before returning them
* *
* @param <S> the [EntityServiceProvider] type
*/
abstract class EntityRepository<Id, E : EntityWithId<Id>, in Condition, out S : EntityServiceProvider<Id, E>,
out DAO : EntityDao<Id, E, Condition>>(
protected val entityDao: DAO,
protected val entityServiceProvider: S
) {
/**
* Retrieves the entities from the db that match the `conditions` and, when the service call returns,
* creates/updates the entities in the db. Then, it emits all the service entities.
*
* @param serviceCall the [Single] that makes the service call
* *
* @param conditions the set of [Condition] to filter the entities
* *
* @return a [Flowable] that will emit the local entities matching the conditions and the ones retrieved from
* * the service call.
*/
@CheckResult
protected open fun getEntities(serviceCall: Single<List<E>>, vararg conditions: Condition) = Flowable
.concatArrayDelayError(
entityDao.getEntities(*conditions).toFlowable(),
serviceCall.applyIoSchedulers().toFlowable())
.subscribeOnIo()
.observeOnIo(true)
.scan { _, serviceEntities -> entityDao.deleteAndInsertEntities(serviceEntities, *conditions).blockingGet() }
.applyIoSchedulers()
/**
* Retrieves the entity with the `id` provided from the local db if present and updates/creates the said entity
* after retrieving it from service.
*
* *
* @param id the primary key value of the entity
* *
* @param serviceCall the [Single] that makes the service call
* *
* @return the entity with the `id`
*/
@CheckResult
protected open fun getEntity(id: Id, serviceCall: (Id) -> Single<E>) =
Observable.mergeDelayError(entityDao.getEntity(id).toObservable(),
getServiceEntity(id, serviceCall).toObservable())
/**
* Retrieves the entity from db and, only if not present, then it's retrieved from service.
*
* *
* @param id the primary key value of the entity
* *
* @param serviceCall the [Single] that makes the service call
* *
* @return the entity with the `id`
*/
@CheckResult
protected open fun getEntityFromDbIfPresentOrGetFromService(id: Id, serviceCall: (Id) -> Single<E>) =
entityDao.getEntity(id)
.switchIfEmpty(getServiceEntity(id, serviceCall).toMaybe()).toSingle()
/**
* Retrieves the entity whose primary key value equals `id` from the service.
* *
* @param id the primary key value of the entity
* *
* @param serviceCall the [Single] that makes the service call
* *
* @return the entity with the `id`
*/
@CheckResult
protected open fun getServiceEntity(id: Id, serviceCall: (Id) -> Single<E>) =
serviceCall(id).applyIoSchedulers()
.flatMap { entityDao.createEntity(it) }
/**
* Retrieves the entity whose primary key value equals `id` from the service and stores the result in db.
*
* @param serviceCall the [Single] that makes the service call
* *
* @return the entity with the `id`
*/
@CheckResult
protected open fun createEntityAndGetValue(serviceCall: Single<E>) =
serviceCall.applyIoSchedulers()
.flatMap { entityDao.createEntity(it) }
/**
* Stores the entity retrieved from service whose primary key value equals `id` into the db.
*
* @param serviceCall the [Single] that makes the service call
* *
* @return a [Completable] that indicates whether or not the entity could be created
*/
@CheckResult
protected open fun createEntity(serviceCall: Single<E>) = createEntityAndGetValue(serviceCall).toCompletable()
/**
* Retrieves the entity from the service and updates it locally.
*
* @param entity the entity to update
* *
* @param serviceCall the function that makes the service call
* *
* @return the updated entity
*/
@CheckResult
protected open fun updateEntityAndGetValue(entity: E, serviceCall: (Id, E) -> Completable) =
updateEntityAndGetValue(entity, serviceCall(entity.id, entity))
/**
* Updates the local entity with the values from `entity` if the `completable` completes successfully.
*
* @param entity the entity to update
* *
* @param completable the [Completable] that, if successful, will trigger the update
* *
* @return the updated entity
*/
@CheckResult
protected open fun updateEntityAndGetValue(entity: E, completable: Completable) =
completable.applyIoSchedulers()
.toSingleDefault(entity)
.flatMap(entityDao::updateEntity)
/**
* Updates the `entity` with the contents from the service call.
*
* @param entity the entity to update
* *
* @param serviceCall the function that makes the service call
* *
* @return a [Completable] that indicates whether or not the entity could be updated
*/
@CheckResult
protected open fun updateEntity(entity: E, serviceCall: (Id, E) -> Completable) =
updateEntityAndGetValue(entity, serviceCall).toCompletable()
/**
* Makes the service call to delete the entity and also deletes it locally.
* *
* @param entityId the value of the primary key of the entity to be deleted
* *
* @param serviceCall the function that makes the service call
* *
* @return a [Completable] that indicates whether or not the entity could be deleted
*/
@CheckResult
protected open fun deleteEntity(entityId: Id, serviceCall: (Id) -> Completable) =
serviceCall(entityId).applyIoSchedulers()
.concatWith(entityDao.deleteEntityWithId(entityId))
/**
* Makes the service call to delete the entity and also deletes it locally.
*
* @param entity the entity to be deleted
* *
* @param serviceCall the function that makes the service call
* *
* @return a [Completable] that indicates whether or not the entity could be deleted
*/
@CheckResult
protected open fun deleteEntity(entity: E, serviceCall: (Id) -> Completable) =
serviceCall(entity.id).applyIoSchedulers()
.concatWith(entityDao.deleteEntity(entity))
}
| apache-2.0 | 636ad1bef5855e2cdcbcb1361c0e0295 | 35.925134 | 117 | 0.702534 | 4.477951 | false | false | false | false |
elpassion/mainframer-intellij-plugin | src/test/kotlin/com/elpassion/mainframerplugin/action/configure/configurator/ConfiguratorTest.kt | 1 | 5048 | package com.elpassion.mainframerplugin.action.configure.configurator
import com.elpassion.android.commons.rxjavatest.thenJust
import com.elpassion.mainframerplugin.common.ToolConfigurationImpl
import com.elpassion.mainframerplugin.task.MainframerTaskDefaultSettingsProvider
import com.elpassion.mainframerplugin.task.TaskData
import com.elpassion.mainframerplugin.util.toolFilename
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import com.nhaarman.mockito_kotlin.*
import io.reactivex.Maybe
import org.junit.Assert
import java.io.File
class ConfiguratorTest : LightPlatformCodeInsightFixtureTestCase() {
private val configurationFromUi = mock<(ConfiguratorIn) -> Maybe<ConfiguratorOut>>()
override fun setUp() {
super.setUp()
stubConfigurationFromUi()
}
fun testShouldReturnChosenVersion() {
stubConfigurationFromUi(version = "1.0.0")
configurator(project, configurationFromUi)(emptyList()).test().assertValue { it.version == "1.0.0" }
}
fun testShouldReturnDefaultMainframerPathVersion() {
stubConfigurationFromUi(version = "1.0.0")
configurator(project, configurationFromUi)(emptyList()).test().assertValue { it.file == File(project.basePath, toolFilename) }
}
fun testConfigurationFromUiRunWithGivenVersionList() {
configureMainframerInProject(versionList = listOf("1.0.0"))
verify(configurationFromUi).invoke(argThat { versionList == listOf("1.0.0") })
}
fun testConfigurationFromUiRunReallyWithGivenVersionList() {
configureMainframerInProject(versionList = listOf("1.1.0"))
verify(configurationFromUi).invoke(argThat { versionList == listOf("1.1.0") })
}
fun testConfigurationFromUiRunWithBuildCommandFromProvider() {
stubMainframerTaskDefaultSettingsProvider(TaskData(buildCommand = "./gradlew"))
configureMainframerInProject()
verify(configurationFromUi).invoke(argThat { buildCommand == "./gradlew" })
}
fun testConfigurationFromUiRunReallyWithBuildCommandFromProvider() {
stubMainframerTaskDefaultSettingsProvider(TaskData(buildCommand = "./buckw"))
configureMainframerInProject()
verify(configurationFromUi).invoke(argThat { buildCommand == "./buckw" })
}
fun testConfigurationFromUiRunWithRemoteMachineNameFromToolProperties() {
ToolConfigurationImpl(project.basePath).writeRemoteMachineName("test_value")
configureMainframerInProject()
verify(configurationFromUi).invoke(argThat { remoteName == "test_value" })
}
fun testConfigurationFromUiReallyRunWithRemoteMachineNameFromToolProperties() {
ToolConfigurationImpl(project.basePath).writeRemoteMachineName("test_2_value")
configureMainframerInProject()
verify(configurationFromUi).invoke(argThat { remoteName == "test_2_value" })
}
fun testShouldCreateToolPropertiesFileWithRemoteMachineName() {
stubConfigurationFromUi(remoteName = "remote")
configureMainframerInProject()
val configurationFile = File(File(project.basePath, ".mainframer"), "config")
Assert.assertTrue(configurationFile.exists())
Assert.assertTrue(configurationFile.readLines().any { it == "remote_machine=remote" })
}
fun testShouldSaveChosenBuildCommandToSettingsProvider() {
stubConfigurationFromUi(buildCommand = "buildCmd")
configureMainframerInProject()
Assert.assertEquals("buildCmd", settingsProviderTask().buildCommand)
}
fun testShouldReallySaveChosenBuildCommandToSettingsProvider() {
stubConfigurationFromUi(buildCommand = "otherCmd")
configureMainframerInProject()
Assert.assertEquals("otherCmd", settingsProviderTask().buildCommand)
}
fun testShouldSaveMainframerPathToSettingsProvider() {
configureMainframerInProject()
Assert.assertEquals(File(project.basePath, toolFilename).absolutePath, settingsProviderTask().mainframerPath)
}
private fun configureMainframerInProject(versionList: List<String> = emptyList()) {
configurator(project, configurationFromUi)(versionList).subscribe()
}
private fun stubMainframerTaskDefaultSettingsProvider(taskData: TaskData) {
MainframerTaskDefaultSettingsProvider.getInstance(project).taskData = taskData
}
private fun settingsProviderTask() = MainframerTaskDefaultSettingsProvider.getInstance(project).taskData
private fun stubConfigurationFromUi(version: String = "0.0.1",
buildCommand: String = "./gradlew",
remoteName: String = "not_local") {
whenever(configurationFromUi.invoke(any())).thenJust(
ConfiguratorOut(version = version,
buildCommand = buildCommand,
remoteName = remoteName))
}
override fun tearDown() {
stubMainframerTaskDefaultSettingsProvider(TaskData())
super.tearDown()
}
} | apache-2.0 | 0e7261dc195155ae34f55e399edddd8e | 40.385246 | 134 | 0.727615 | 5.736364 | false | true | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/AtColorSettingsPage.kt | 1 | 2244 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.at
import com.demonwav.mcdev.asset.PlatformAssets
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
class AtColorSettingsPage : ColorSettingsPage {
override fun getIcon() = PlatformAssets.MCP_ICON
override fun getHighlighter() = AtSyntaxHighlighter()
override fun getDemoText() =
"""
# Minecraft
public net.minecraft.block.BlockFlowerPot func_149928_a(Lnet/minecraft/block/Block;I)Z # canNotContain
private-f net.minecraft.inventory.ContainerChest field_7515F4_f # numRows
protected net.minecraft.block.state.BlockStateContainer${'$'}StateImplementation
public-f net.minecraft.item.Item func_77656_e(I)Lnet/minecraft/item/Item; # setMaxDamage
public+f net.minecraft.server.management.UserList *
default+f net.minecraft.item.Item *()
public net.minecraft.world.demo.DemoWorldServer func_175680_a(IIZ)Z # isChunkLoaded
""".trimIndent()
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey>? = null
override fun getAttributeDescriptors() = DESCRIPTORS
override fun getColorDescriptors(): Array<out ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getDisplayName() = "Access Transformers"
companion object {
private val DESCRIPTORS = arrayOf(
AttributesDescriptor("Keyword", AtSyntaxHighlighter.KEYWORD),
AttributesDescriptor("Class Name", AtSyntaxHighlighter.CLASS_NAME),
AttributesDescriptor("Class Value", AtSyntaxHighlighter.CLASS_VALUE),
AttributesDescriptor("Primitive Value", AtSyntaxHighlighter.PRIMITIVE),
AttributesDescriptor("Element Name", AtSyntaxHighlighter.ELEMENT_NAME),
AttributesDescriptor("Asterisk", AtSyntaxHighlighter.ASTERISK),
AttributesDescriptor("Comment", AtSyntaxHighlighter.COMMENT)
)
}
}
| mit | 973cdf6833d5fdfa81919fdef458dd1f | 42.153846 | 110 | 0.739305 | 4.97561 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/index/geojson/GeoJsonBoundingBoxIndexer.kt | 1 | 1780 | package io.georocket.index.geojson
import de.undercouch.actson.JsonEvent
import io.georocket.index.generic.BoundingBoxIndexer
import io.georocket.util.JsonStreamEvent
/**
* Indexes bounding boxes of GeoJSON chunks
* @author Michel Kraemer
*/
class GeoJsonBoundingBoxIndexer : BoundingBoxIndexer<JsonStreamEvent>() {
/**
* The current level in the parsed GeoJSON chunk. Will be increased
* every time the start of an object or an array is found and decreased
* every time the object or array is closed.
*/
private var level = 0
/**
* The level where the `coordinates` field was found. The value
* is `-1` if the field has not been found yet or if we already
* scanned past it.
*/
private var coordinatesLevel = -1
/**
* The last encountered X ordinate
*/
private var currentX = 0.0
/**
* `0` if the next number found should be the X ordinate,
* `1` if it should be Y.
*/
private var currentOrdinate = 0
override fun onEvent(event: JsonStreamEvent) {
when (event.event) {
JsonEvent.START_ARRAY, JsonEvent.START_OBJECT -> level++
JsonEvent.FIELD_NAME -> if ("coordinates" == event.currentValue) {
currentOrdinate = 0
coordinatesLevel = level
}
JsonEvent.VALUE_INT, JsonEvent.VALUE_DOUBLE -> if (coordinatesLevel >= 0) {
val d = (event.currentValue as Number).toDouble()
if (currentOrdinate == 0) {
currentX = d
currentOrdinate = 1
} else if (currentOrdinate == 1) {
addToBoundingBox(currentX, d)
currentOrdinate = 0
}
}
JsonEvent.END_ARRAY, JsonEvent.END_OBJECT -> {
level--
if (coordinatesLevel == level) {
coordinatesLevel = -1
}
}
}
}
}
| apache-2.0 | f1b9f51c1b1553bf64a2b63c68a7cf9e | 26.384615 | 81 | 0.640449 | 4.268585 | false | false | false | false |
denzelby/telegram-bot-bumblebee | telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/youtube/entity/Chat.kt | 1 | 602 | package com.github.bumblebee.command.youtube.entity
import javax.persistence.*
@Entity
@Table(name = "BB_YOUTUBE_SUBBED_CHATS")
class Chat {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null
var chatId: Long = 0
@ManyToOne
@JoinColumn(name = "SUBSCRIPTION_SUBID")
var subscription: Subscription? = null
@Suppress("unused")
constructor()
constructor(chatId: Long, subscription: Subscription) {
this.chatId = chatId
this.subscription = subscription
}
override fun toString(): String = "chatId: $chatId"
}
| mit | 62686f6a7c1870a618fe9a8c9cc03021 | 20.5 | 59 | 0.674419 | 4.123288 | false | false | false | false |
google/intellij-community | plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/ElementAnnotator.kt | 1 | 9684 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.highlighter
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.colors.CodeInsightColors
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.MultiRangeReference
import com.intellij.psi.PsiElement
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.config.KotlinFacetSettingsProvider
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtReferenceExpression
internal class ElementAnnotator(
private val element: PsiElement,
private val shouldSuppressUnusedParameter: (KtParameter) -> Boolean
) {
fun registerDiagnosticsAnnotations(
holder: HighlightInfoHolder,
diagnostics: Collection<Diagnostic>,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>?,
highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?,
noFixes: Boolean,
calculatingInProgress: Boolean
) = diagnostics.groupBy { it.factory }
.forEach {
registerSameFactoryDiagnosticsAnnotations(
holder,
it.value,
highlightInfoByDiagnostic,
highlightInfoByTextRange,
noFixes,
calculatingInProgress
)
}
private fun registerSameFactoryDiagnosticsAnnotations(
holder: HighlightInfoHolder,
diagnostics: Collection<Diagnostic>,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>?,
highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?,
noFixes: Boolean,
calculatingInProgress: Boolean
) {
val presentationInfo = presentationInfo(diagnostics) ?: return
setUpAnnotations(
holder,
diagnostics,
presentationInfo,
highlightInfoByDiagnostic,
highlightInfoByTextRange,
noFixes,
calculatingInProgress
)
}
fun registerDiagnosticsQuickFixes(
diagnostics: List<Diagnostic>,
highlightInfoByDiagnostic: Map<Diagnostic, HighlightInfo>
) = diagnostics.groupBy { it.factory }
.forEach { registerDiagnosticsSameFactoryQuickFixes(it.value, highlightInfoByDiagnostic) }
private fun registerDiagnosticsSameFactoryQuickFixes(
diagnostics: List<Diagnostic>,
highlightInfoByDiagnostic: Map<Diagnostic, HighlightInfo>
) {
val presentationInfo = presentationInfo(diagnostics) ?: return
val fixesMap = createFixesMap(diagnostics) ?: return
diagnostics.forEach {
val highlightInfo = highlightInfoByDiagnostic[it] ?: return
presentationInfo.applyFixes(fixesMap, it, highlightInfo)
}
}
private fun presentationInfo(diagnostics: Collection<Diagnostic>): AnnotationPresentationInfo? {
if (diagnostics.isEmpty() || !diagnostics.any { it.isValid }) return null
val diagnostic = diagnostics.first()
// hack till the root cause #KT-21246 is fixed
if (isUnstableAbiClassDiagnosticForModulesWithEnabledUnstableAbi(diagnostic)) return null
val factory = diagnostic.factory
if (suppressDeprecatedAnnotation && factory == Errors.DEPRECATION) return null
assert(diagnostics.all { it.psiElement == element && it.factory == factory })
val ranges = diagnostic.textRanges
val presentationInfo: AnnotationPresentationInfo = when (factory.severity) {
Severity.ERROR -> {
when (factory) {
in Errors.UNRESOLVED_REFERENCE_DIAGNOSTICS -> {
val referenceExpression = element as KtReferenceExpression
val reference = referenceExpression.mainReference
if (reference is MultiRangeReference) {
AnnotationPresentationInfo(
ranges = reference.ranges.map { it.shiftRight(referenceExpression.textOffset) },
highlightType = ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
)
} else {
AnnotationPresentationInfo(ranges, highlightType = ProblemHighlightType.LIKE_UNKNOWN_SYMBOL)
}
}
Errors.ILLEGAL_ESCAPE -> AnnotationPresentationInfo(
ranges, textAttributes = KotlinHighlightingColors.INVALID_STRING_ESCAPE
)
Errors.REDECLARATION -> AnnotationPresentationInfo(
ranges = listOf(diagnostic.textRanges.first()), nonDefaultMessage = ""
)
else -> {
AnnotationPresentationInfo(
ranges,
highlightType = if (factory == Errors.INVISIBLE_REFERENCE)
ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
else
null
)
}
}
}
Severity.WARNING -> {
if (factory == Errors.UNUSED_PARAMETER && shouldSuppressUnusedParameter(element as KtParameter)) {
return null
}
AnnotationPresentationInfo(
ranges,
textAttributes = when (factory) {
Errors.DEPRECATION -> CodeInsightColors.DEPRECATED_ATTRIBUTES
Errors.UNUSED_ANONYMOUS_PARAMETER -> CodeInsightColors.WEAK_WARNING_ATTRIBUTES
else -> null
},
highlightType = when (factory) {
in Errors.UNUSED_ELEMENT_DIAGNOSTICS, Errors.UNUSED_DESTRUCTURED_PARAMETER_ENTRY ->
ProblemHighlightType.LIKE_UNUSED_SYMBOL
Errors.UNUSED_ANONYMOUS_PARAMETER -> ProblemHighlightType.WEAK_WARNING
else -> null
}
)
}
Severity.INFO -> AnnotationPresentationInfo(ranges, highlightType = ProblemHighlightType.INFORMATION)
}
return presentationInfo
}
private fun setUpAnnotations(
holder: HighlightInfoHolder,
diagnostics: Collection<Diagnostic>,
data: AnnotationPresentationInfo,
highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>?,
highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?,
noFixes: Boolean,
calculatingInProgress: Boolean
) {
val fixesMap = createFixesMap(diagnostics, noFixes)
data.processDiagnostics(holder, diagnostics, highlightInfoByDiagnostic, highlightInfoByTextRange, fixesMap, calculatingInProgress)
}
private fun createFixesMap(
diagnostics: Collection<Diagnostic>,
noFixes: Boolean = false
): MultiMap<Diagnostic, IntentionAction>? {
return if (noFixes) {
null
} else {
try {
Fe10QuickFixProvider.getInstance(element.project).createQuickFixes(diagnostics)
} catch (e: Exception) {
if (e is ControlFlowException) {
throw e
}
LOG.error(e)
MultiMap()
}
}
}
private fun isUnstableAbiClassDiagnosticForModulesWithEnabledUnstableAbi(diagnostic: Diagnostic): Boolean {
val factory = diagnostic.factory
if (factory != Errors.IR_WITH_UNSTABLE_ABI_COMPILED_CLASS && factory != Errors.FIR_COMPILED_CLASS) return false
val module = element.module ?: return false
val moduleFacetSettings = KotlinFacetSettingsProvider.getInstance(element.project)?.getSettings(module) ?: return false
return when (factory) {
Errors.IR_WITH_UNSTABLE_ABI_COMPILED_CLASS ->
moduleFacetSettings.isCompilerSettingPresent(K2JVMCompilerArguments::useIR) &&
!moduleFacetSettings.isCompilerSettingPresent(K2JVMCompilerArguments::useOldBackend)
Errors.FIR_COMPILED_CLASS ->
moduleFacetSettings.isCompilerSettingPresent(K2JVMCompilerArguments::useK2)
else -> error(factory)
}
}
companion object {
val LOG = Logger.getInstance(ElementAnnotator::class.java)
val suppressDeprecatedAnnotationRegistryKey = Registry.get("kotlin.highlighting.suppress.deprecated")
var suppressDeprecatedAnnotation = suppressDeprecatedAnnotationRegistryKey.asBoolean()
fun updateSuppressDeprecatedAnnotationValue() {
suppressDeprecatedAnnotation = suppressDeprecatedAnnotationRegistryKey.asBoolean()
}
}
}
| apache-2.0 | b1837eae106b552dc14566dfd0e1d939 | 42.621622 | 158 | 0.643329 | 6.354331 | false | false | false | false |
apollographql/apollo-android | apollo-mockserver/src/jsMain/kotlin/com/apollographql/apollo3/mockserver/MockServer.kt | 1 | 1723 | package com.apollographql.apollo3.mockserver
import Buffer
import net.AddressInfo
import okio.ByteString.Companion.toByteString
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
actual class MockServer : MockServerInterface {
private val responseQueue = mutableListOf<MockResponse>()
private val requests = mutableListOf<MockRecordedRequest>()
private val server = http.createServer { req, res ->
val requestBody = StringBuilder()
req.on("data") { chunk ->
when (chunk) {
is String -> requestBody.append(chunk)
is Buffer -> requestBody.append(chunk.toString("utf8"))
else -> println("WTF")
}
}
req.on("end") { _ ->
requests.add(
MockRecordedRequest(
req.method,
req.url,
req.httpVersion,
req.rawHeaders.toList().zipWithNext().toMap(),
requestBody.toString().encodeToByteArray().toByteString()
)
)
}
val mockResponse = responseQueue.removeFirst()
res.statusCode = mockResponse.statusCode
mockResponse.headers.forEach {
res.setHeader(it.key, it.value)
}
res.end(mockResponse.body.utf8())
}.listen()
override suspend fun url() = suspendCoroutine<String> { cont ->
server.on("listening") { _ ->
cont.resume("http://localhost:${server.address().unsafeCast<AddressInfo>().port}")
}
}
override fun enqueue(mockResponse: MockResponse) {
responseQueue.add(mockResponse)
}
override fun takeRequest(): MockRecordedRequest {
return requests.removeFirst()
}
override suspend fun stop() = suspendCoroutine<Unit> { cont ->
server.close {
cont.resume(Unit)
}
}
}
| mit | 98314bff6393004eb6d2237865e4deac | 27.245902 | 88 | 0.655252 | 4.558201 | false | false | false | false |
StephaneBg/ScoreIt | data/src/main/kotlin/com/sbgapps/scoreit/data/interactor/ScoreBoardUseCase.kt | 1 | 1178 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.data.interactor
import com.sbgapps.scoreit.data.model.ScoreBoard
import com.sbgapps.scoreit.data.repository.CacheRepo
class ScoreBoardUseCase(private val cacheRepo: CacheRepo) {
private var scoreBoard: ScoreBoard? = null
fun getScoreBoard(): ScoreBoard = scoreBoard ?: cacheRepo.loadScoreBoard().also { scoreBoard = it }
fun saveScoreBoard(scoreBoard: ScoreBoard) {
this.scoreBoard = scoreBoard
cacheRepo.saveScoreBoard(scoreBoard)
}
fun reset(): ScoreBoard = getScoreBoard().copy(scoreOne = 0, scoreTwo = 0)
}
| apache-2.0 | 5c8ec824fb1afc80e0b8b108f687a64f | 33.617647 | 103 | 0.743415 | 4.115385 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/main/kotlin/com/masahirosaito/spigot/homes/commands/subcommands/player/privatecommands/PlayerPrivateCommand.kt | 1 | 2198 | package com.masahirosaito.spigot.homes.commands.subcommands.player.privatecommands
import com.masahirosaito.spigot.homes.Configs.onPrivate
import com.masahirosaito.spigot.homes.Homes.Companion.homes
import com.masahirosaito.spigot.homes.Permission.home_command_private
import com.masahirosaito.spigot.homes.PlayerDataManager
import com.masahirosaito.spigot.homes.commands.BaseCommand
import com.masahirosaito.spigot.homes.commands.CommandUsage
import com.masahirosaito.spigot.homes.commands.subcommands.player.PlayerCommand
import com.masahirosaito.spigot.homes.strings.commands.PrivateCommandStrings.DESCRIPTION
import com.masahirosaito.spigot.homes.strings.commands.PrivateCommandStrings.SET_DEFAULT_HOME_PRIVATE
import com.masahirosaito.spigot.homes.strings.commands.PrivateCommandStrings.SET_DEFAULT_HOME_PUBLIC
import com.masahirosaito.spigot.homes.strings.commands.PrivateCommandStrings.USAGE_PRIVATE
import com.masahirosaito.spigot.homes.strings.commands.PrivateCommandStrings.USAGE_PRIVATE_NAME
import org.bukkit.entity.Player
class PlayerPrivateCommand : PlayerCommand {
override var payNow: Boolean = true
override val name: String = "private"
override val description: String = DESCRIPTION()
override val permissions: List<String> = listOf(home_command_private)
override val usage: CommandUsage = CommandUsage(this, listOf(
"/home private (on/off)" to USAGE_PRIVATE(),
"/home private (on/off) <home_name>" to USAGE_PRIVATE_NAME()
))
override val commands: List<BaseCommand> = listOf(
PlayerPrivateNameCommand(this)
)
override fun fee(): Double = homes.fee.PRIVATE
override fun configs(): List<Boolean> = listOf(onPrivate)
override fun isValidArgs(args: List<String>): Boolean = args.size == 1 && (args[0] == "on" || args[0] == "off")
override fun execute(player: Player, args: List<String>) {
if (args[0] == "on") {
PlayerDataManager.setDefaultHomePrivate(player, true)
send(player, SET_DEFAULT_HOME_PRIVATE())
} else {
PlayerDataManager.setDefaultHomePrivate(player, false)
send(player, SET_DEFAULT_HOME_PUBLIC())
}
}
}
| apache-2.0 | fd0c52b1628028e99e17c307ad707195 | 47.844444 | 115 | 0.752502 | 4.309804 | false | false | false | false |
allotria/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/util/ASTUtils.kt | 3 | 1132 | // 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.intellij.plugins.markdown.util
import com.intellij.lang.ASTNode
private fun ASTNode.traverse(next: (ASTNode) -> ASTNode?): Sequence<ASTNode> = sequence<ASTNode> {
var cur = next(this@traverse)
while (cur != null) {
yield(cur)
cur = next(cur)
}
}
/**
* Get all direct children of [this] node.
* Does not include [this]
*/
internal fun ASTNode.children(): Sequence<ASTNode> = sequence {
val first = [email protected] ?: return@sequence
yield(first)
yieldAll(first.nextSiblings())
}
/**
* Get parent chain of this node.
* Does not include [this]
*/
internal fun ASTNode.parents(): Sequence<ASTNode> = traverse { it.treeParent }
/**
* Get previous siblings of [this] node.
* Does not include [this]
*/
internal fun ASTNode.prevSiblings(): Sequence<ASTNode> = traverse { it.treePrev }
/**
* Get next siblings of [this] node.
* Does not include [this]
*/
internal fun ASTNode.nextSiblings(): Sequence<ASTNode> = traverse { it.treeNext }
| apache-2.0 | 7932fb50524cd7676146bc7f6d4a7440 | 28.025641 | 140 | 0.70318 | 3.66343 | false | false | false | false |
deadpixelsociety/roto-ld34 | core/src/com/thedeadpixelsociety/ld34/systems/AnimationSystem.kt | 1 | 808 | package com.thedeadpixelsociety.ld34.systems
import com.badlogic.ashley.core.ComponentMapper
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.systems.IteratingSystem
import com.thedeadpixelsociety.ld34.components.AnimationComponent
class AnimationSystem() : IteratingSystem(Family.one(AnimationComponent::class.java).get()) {
private val animationMapper = ComponentMapper.getFor(AnimationComponent::class.java)
override fun processEntity(entity: Entity?, deltaTime: Float) {
val animation = animationMapper.get(entity)
if (animation.animationTime > 0f) animation.t = animation.time / animation.animationTime
if (animation.time >= animation.animationTime) animation.time = 0f else animation.time += deltaTime
}
}
| mit | bc72072edfe1005e55e67ec9d8f92e84 | 43.888889 | 107 | 0.785891 | 4.539326 | false | false | false | false |
allotria/intellij-community | platform/platform-api/src/com/intellij/ui/list/LeftRightRenderer.kt | 2 | 2006 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.list
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import java.awt.Component
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.ListCellRenderer
/**
* A renderer which combines two renderers.
*
* [mainRenderer] component is aligned to the left, [rightRenderer] component is aligned to the right.
* This renderer uses background from [mainRenderer] component.
*/
abstract class LeftRightRenderer<T> : ListCellRenderer<T> {
protected abstract val mainRenderer: ListCellRenderer<T>
protected abstract val rightRenderer: ListCellRenderer<T>
private val spacer = JPanel().apply {
border = JBUI.Borders.empty(0, 2)
}
private val component = JPanel(BorderLayout())
final override fun getListCellRendererComponent(list: JList<out T>,
value: T,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
val mainComponent = mainRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
val rightComponent = rightRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
mainComponent.background.let {
component.background = it
spacer.background = it
rightComponent.background = it
}
component.apply {
removeAll()
add(mainComponent, BorderLayout.WEST)
add(spacer, BorderLayout.CENTER)
add(rightComponent, BorderLayout.EAST)
accessibleContext.accessibleName = listOfNotNull(
mainComponent.accessibleContext?.accessibleName,
rightComponent.accessibleContext?.accessibleName
).joinToString(separator = " ")
}
return component
}
}
| apache-2.0 | 7fd0ad1dbcff00364efc64965bf18807 | 37.576923 | 140 | 0.676969 | 5.130435 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/HighlightingProblem.kt | 2 | 3136 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.analysis.problemsView.toolWindow
import com.intellij.analysis.problemsView.FileProblem
import com.intellij.analysis.problemsView.ProblemsProvider
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInsight.daemon.HighlightDisplayKey
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.openapi.editor.ex.RangeHighlighterEx
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.xml.util.XmlStringUtil.escapeString
import javax.swing.Icon
internal class HighlightingProblem(
override val provider: ProblemsProvider,
override val file: VirtualFile,
private val highlighter: RangeHighlighterEx
) : FileProblem {
private fun getIcon(level: HighlightDisplayLevel) = if (severity >= level.severity.myVal) level.icon else null
internal val info: HighlightInfo?
get() = HighlightInfo.fromRangeHighlighter(highlighter)
override val icon: Icon
get() = HighlightDisplayLevel.find(info?.severity)?.icon
?: getIcon(HighlightDisplayLevel.ERROR)
?: getIcon(HighlightDisplayLevel.WARNING)
?: HighlightDisplayLevel.WEAK_WARNING.icon
override val text: String
get() {
val text = info?.description ?: return "Invalid"
val pos = text.indexOfFirst { StringUtil.isLineBreak(it) }
return if (pos < 0 || text.startsWith("<html>", ignoreCase = true)) text
else text.substring(0, pos) + StringUtil.ELLIPSIS
}
override val group: String?
get() {
val id = info?.inspectionToolId ?: return null
return HighlightDisplayKey.getDisplayNameByKey(HighlightDisplayKey.findById(id))
}
override val description: String?
get() {
val text = info?.description ?: return null
val pos = text.indexOfFirst { StringUtil.isLineBreak(it) }
return if (pos < 0 || text.startsWith("<html>", ignoreCase = true)) null
else "<html>" + StringUtil.join(StringUtil.splitByLines(escapeString(text)), "<br/>")
}
val severity: Int
get() = info?.severity?.myVal ?: -1
override fun hashCode() = highlighter.hashCode()
override fun equals(other: Any?) = other is HighlightingProblem && other.highlighter == highlighter
override val line: Int
get() = position?.line ?: -1
override val column: Int
get() = position?.column ?: -1
private var position: CachedPosition? = null
get() = info?.actualStartOffset?.let {
if (it != field?.offset) field = computePosition(it)
field
}
private fun computePosition(offset: Int): CachedPosition? {
if (offset < 0) return null
val document = ProblemsView.getDocument(provider.project, file) ?: return null
if (offset > document.textLength) return null
val line = document.getLineNumber(offset)
return CachedPosition(offset, line, offset - document.getLineStartOffset(line))
}
private class CachedPosition(val offset: Int, val line: Int, val column: Int)
}
| apache-2.0 | edc544cf6d287b99c71cb04dbbff7d90 | 37.243902 | 140 | 0.727997 | 4.51223 | false | false | false | false |
Kotlin/kotlinx.coroutines | benchmarks/src/jmh/kotlin/benchmarks/flow/CombineTwoFlowsBenchmark.kt | 1 | 1413 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks.flow
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.flow.internal.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.*
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(value = 1)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
open class CombineTwoFlowsBenchmark {
@Param("100", "100000", "1000000")
private var size = 100000
@Benchmark
fun combinePlain() = runBlocking {
val flow = (1 until size.toLong()).asFlow()
flow.combine(flow) { a, b -> a + b }.collect()
}
@Benchmark
fun combineTransform() = runBlocking {
val flow = (1 until size.toLong()).asFlow()
flow.combineTransform(flow) { a, b -> emit(a + b) }.collect()
}
@Benchmark
fun combineVararg() = runBlocking {
val flow = (1 until size.toLong()).asFlow()
combine(listOf(flow, flow)) { arr -> arr[0] + arr[1] }.collect()
}
@Benchmark
fun combineTransformVararg() = runBlocking {
val flow = (1 until size.toLong()).asFlow()
combineTransform(listOf(flow, flow)) { arr -> emit(arr[0] + arr[1]) }.collect()
}
}
| apache-2.0 | 3f40a0a68b6202e92e40f50f100fcb1e | 29.06383 | 102 | 0.653928 | 3.818919 | false | false | false | false |
udevbe/westford | compositor/src/main/kotlin/org/westford/compositor/x11/egl/X11EglOutput.kt | 3 | 4110 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.x11.egl
import com.google.auto.factory.AutoFactory
import com.google.auto.factory.Provided
import org.freedesktop.wayland.server.Display
import org.westford.compositor.core.EglOutput
import org.westford.compositor.core.EglOutputState
import org.westford.compositor.core.Scene
import org.westford.compositor.protocol.WlOutput
import org.westford.compositor.x11.X11Output
@AutoFactory(allowSubclasses = true,
className = "X11EglOutputFactory") class X11EglOutput(@param:Provided private val display: Display,
private @Provided val gles2PainterFactory: org.westford.compositor.gles2.Gles2PainterFactory,
@param:Provided private val scene: Scene,
val x11Output: X11Output,
override val eglSurface: Long,
override val eglContext: Long,
override val eglDisplay: Long) : EglOutput {
private var renderScheduled = false
override var state: EglOutputState? = null
override fun render(wlOutput: WlOutput) {
//TODO unit test 2 cases here: schedule idle, no-op when already scheduled
whenIdleDoRender(wlOutput)
}
private fun whenIdleDoRender(wlOutput: WlOutput) {
if (!this.renderScheduled) {
this.renderScheduled = true
this.display.eventLoop.addIdle { doRender(wlOutput) }
}
}
private fun doRender(wlOutput: WlOutput) {
paint(wlOutput)
this.display.flushClients()
this.renderScheduled = false
}
private fun paint(wlOutput: WlOutput) {
val subscene = this.scene.subsection(wlOutput.output.region)
val gles2Painter = this.gles2PainterFactory.create(this,
wlOutput)
//naive generic single pass, bottom to top overdraw rendering.
val lockViews = subscene.lockViews
val fullscreenView = subscene.fullscreenView
//lockscreen(s) hide all other screens.
if (!lockViews.isEmpty()) {
lockViews.forEach {
gles2Painter.paint(it)
}
}
else {
val fullscreenPainted = fullscreenView?.let {
gles2Painter.paint(it)
} ?: false
if (!fullscreenPainted) {
//fullscreen view not visible, paint the rest of the subscene.
//TODO for now we use a simple back to front overdraw painting
subscene.backgroundView?.let {
gles2Painter.paint(it)
}
subscene.underViews.forEach {
gles2Painter.paint(it)
}
subscene.applicationViews.forEach {
gles2Painter.paint(it)
}
subscene.overViews.forEach {
gles2Painter.paint(it)
}
}
}
subscene.cursorViews.forEach {
gles2Painter.paint(it)
}
gles2Painter.commit()
}
}
| agpl-3.0 | 975b7c63d842dc2056b4c2b865170934 | 37.773585 | 160 | 0.584185 | 5.061576 | false | false | false | false |
leafclick/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunAnythingProvider.kt | 1 | 4877 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.execution
import com.intellij.ide.actions.runAnything.RunAnythingContext
import com.intellij.ide.actions.runAnything.RunAnythingContext.*
import com.intellij.ide.actions.runAnything.RunAnythingUtil.fetchProject
import com.intellij.ide.actions.runAnything.activity.RunAnythingCommandLineProvider
import com.intellij.ide.actions.runAnything.activity.RunAnythingProvider
import com.intellij.ide.actions.runAnything.getPath
import com.intellij.openapi.actionSystem.DataContext
import icons.OpenapiIcons
import org.jetbrains.idea.maven.model.MavenConstants
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenArtifactUtil
import javax.swing.Icon
class MavenRunAnythingProvider : RunAnythingCommandLineProvider() {
override fun getHelpCommand() = HELP_COMMAND
override fun getHelpIcon(): Icon? = OpenapiIcons.RepositoryLibraryLogo
override fun getHelpGroupTitle() = "Maven"
override fun getIcon(value: String): Icon? = OpenapiIcons.RepositoryLibraryLogo
override fun getCompletionGroupTitle() = "Maven goals"
override fun getHelpCommandPlaceholder() = "mvn <goals...> <options...>"
override fun getMainListItem(dataContext: DataContext, value: String) =
RunAnythingMavenItem(getCommand(value), getIcon(value))
override fun suggestCompletionVariants(dataContext: DataContext, commandLine: CommandLine): Sequence<String> {
val basicPhasesVariants = completeBasicPhases(commandLine).sorted()
val customGoalsVariants = completeCustomGoals(dataContext, commandLine).sorted()
val longOptionsVariants = completeOptions(commandLine, isLongOpt = true).sorted()
val shortOptionsVariants = completeOptions(commandLine, isLongOpt = false).sorted()
return when {
commandLine.toComplete.startsWith("--") ->
longOptionsVariants + shortOptionsVariants + basicPhasesVariants + customGoalsVariants
commandLine.toComplete.startsWith("-") ->
shortOptionsVariants + longOptionsVariants + basicPhasesVariants + customGoalsVariants
else ->
basicPhasesVariants + customGoalsVariants + longOptionsVariants + shortOptionsVariants
}
}
override fun run(dataContext: DataContext, commandLine: CommandLine): Boolean {
val project = fetchProject(dataContext)
val context = dataContext.getData(EXECUTING_CONTEXT) ?: ProjectContext(project)
val projectsManager = MavenProjectsManager.getInstance(project)
val mavenProject = context.getMavenProject(projectsManager)
val workingDirPath = mavenProject?.directory ?: context.getPath() ?: return false
val pomFileName = mavenProject?.file?.name ?: MavenConstants.POM_XML
val explicitProfiles = projectsManager.explicitProfiles
val enabledProfiles = explicitProfiles.enabledProfiles
val disabledProfiles = explicitProfiles.disabledProfiles
val goals = commandLine.parameters
val params = MavenRunnerParameters(true, workingDirPath, pomFileName, goals, enabledProfiles, disabledProfiles)
val mavenRunner = MavenRunner.getInstance(project)
mavenRunner.run(params, mavenRunner.settings, null)
return true
}
private fun RunAnythingContext.getMavenProject(projectsManager: MavenProjectsManager) = when (this) {
is ProjectContext -> projectsManager.rootProjects.firstOrNull()
is ModuleContext -> projectsManager.findProject(module)
is RecentDirectoryContext -> null
is BrowseRecentDirectoryContext -> null
}
private fun completeOptions(commandLine: CommandLine, isLongOpt: Boolean): Sequence<String> {
return MavenCommandLineOptions.getAllOptions().asSequence()
.mapNotNull { it.getName(isLongOpt) }
.filter { it !in commandLine }
}
private fun completeBasicPhases(commandLine: CommandLine): Sequence<String> {
return MavenConstants.BASIC_PHASES.asSequence().filter { it !in commandLine }
}
private fun completeCustomGoals(dataContext: DataContext, commandLine: CommandLine): Sequence<String> {
val project = fetchProject(dataContext)
val context = dataContext.getData(RunAnythingProvider.EXECUTING_CONTEXT) ?: ProjectContext(project)
val projectsManager = MavenProjectsManager.getInstance(project)
if (!projectsManager.isMavenizedProject) return emptySequence()
val mavenProject = context.getMavenProject(projectsManager) ?: return emptySequence()
val localRepository = projectsManager.localRepository
return mavenProject.declaredPlugins.asSequence()
.mapNotNull { MavenArtifactUtil.readPluginInfo(localRepository, it.mavenId) }
.flatMap { it.mojos.asSequence() }
.map { it.displayName }
.filter { it !in commandLine }
}
companion object {
const val HELP_COMMAND = "mvn"
}
}
| apache-2.0 | eb919982362751ef0201b6c6feaabf54 | 47.77 | 140 | 0.782448 | 5.043433 | false | false | false | false |
crispab/codekvast | product/server/backoffice/src/main/java/io/codekvast/backoffice/rules/impl/FactDAO.kt | 1 | 5659 | /*
* Copyright (c) 2015-2022 Hallin Information Technology AB
*
* 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 io.codekvast.backoffice.rules.impl
import com.google.gson.GsonBuilder
import io.codekvast.backoffice.facts.PersistentFact
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.PreparedStatementCreator
import org.springframework.jdbc.core.RowMapper
import org.springframework.jdbc.support.GeneratedKeyHolder
import org.springframework.jdbc.support.KeyHolder
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.SQLDataException
import java.sql.Statement.RETURN_GENERATED_KEYS
import java.time.Instant
/** @author [email protected]
*/
@Repository
class FactDAO(private val jdbcTemplate: JdbcTemplate) {
val logger: Logger = LoggerFactory.getLogger(this::class.java)
private val gson = GsonBuilder().registerTypeAdapter(Instant::class.java, InstantTypeAdapter()).create()
@Transactional(rollbackFor = [Exception::class], propagation = Propagation.MANDATORY)
fun getFacts(customerId: Long): List<FactWrapper> {
val rowMapper = RowMapper { rs, _ ->
val id = rs.getLong("id")
val type = rs.getString("type")
val data = rs.getString("data")
try {
val fact = parseJson(data, type)
FactWrapper(id, fact as PersistentFact)
} catch (e: ClassCastException) {
throw SQLDataException("Cannot load fact of type '$type'", e)
} catch (e: ClassNotFoundException) {
throw SQLDataException("Cannot load fact of type '$type'", e)
}
}
val wrappers = jdbcTemplate.query(
"SELECT id, type, data FROM facts WHERE customerId = ?",
rowMapper, customerId)
logger.trace("Retrieved the persistent facts {} for customer {}", wrappers, customerId)
logger.debug("Retrieved {} persistent facts for customer {}", wrappers.size, customerId)
return wrappers
}
@Transactional(rollbackFor = [Exception::class], propagation = Propagation.MANDATORY)
fun addFact(customerId: Long, fact: PersistentFact): Long {
val keyHolder: KeyHolder = GeneratedKeyHolder()
val inserted = jdbcTemplate.update(
AddFactStatementCreator(customerId, getType(fact), gson.toJson(fact)), keyHolder)
val factId: Long = keyHolder.key?.toLong() ?: -1L
if (factId < 0) {
logger.error("Failed to get generated key")
}
if (inserted <= 0) {
logger.error("Attempt to insert duplicate fact {}:{}", customerId, factId)
}
return factId
}
@Transactional(rollbackFor = [Exception::class], propagation = Propagation.MANDATORY)
fun updateFact(customerId: Long, factId: Long, fact: PersistentFact) {
val updated = jdbcTemplate.update(
"UPDATE facts SET type = ?, data = ? WHERE id = ? AND customerId = ?",
getType(fact), gson.toJson(fact), factId, customerId)
if (updated <= 0) {
logger.error("Failed to update fact {}:{}", customerId, factId)
}
}
@Transactional(rollbackFor = [Exception::class], propagation = Propagation.MANDATORY)
fun removeFact(customerId: Long, factId: Long) {
val deleted = jdbcTemplate.update(
"DELETE FROM facts WHERE id = ? AND customerId = ?", factId, customerId)
if (deleted <= 0) {
logger.error("Failed to delete fact {}:{}", customerId, factId)
}
}
private fun getType(fact: PersistentFact) = fact.javaClass.name
fun parseJson(data: String, type: String) = gson.fromJson(data, Class.forName(type))
private class AddFactStatementCreator(private val customerId: Long,
private val type: String,
private val data: String) : PreparedStatementCreator {
override fun createPreparedStatement(con: Connection): PreparedStatement {
val ps = con.prepareStatement(
"INSERT IGNORE INTO facts(customerId, type, data) VALUES(?, ?, ?)",
RETURN_GENERATED_KEYS)
ps.setLong(1, customerId)
ps.setString(2, type)
ps.setString(3, data)
return ps
}
}
}
| mit | db25f6951818cdd2cad3d1b2ae28722b | 43.210938 | 108 | 0.672027 | 4.747483 | false | false | false | false |
zdary/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/create/GHPRCreateDirectionComponentFactory.kt | 1 | 9970 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.toolwindow.create
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.ComboboxSpeedSearch
import com.intellij.ui.MutableCollectionComboBoxModel
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBTextField
import com.intellij.ui.layout.*
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UI
import com.intellij.util.ui.UIUtil
import git4idea.GitBranch
import git4idea.GitLocalBranch
import git4idea.GitRemoteBranch
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.api.GHRepositoryPath
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.util.GHGitRepositoryMapping
import org.jetbrains.plugins.github.util.GHProjectRepositoriesManager
import org.jetbrains.plugins.github.util.GithubGitHelper
import java.awt.event.ActionEvent
import javax.swing.ComboBoxModel
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
class GHPRCreateDirectionComponentFactory(private val repositoriesManager: GHProjectRepositoriesManager,
private val model: GHPRCreateDirectionModel) {
fun create(): JComponent {
val base = ActionLink("")
base.addActionListener {
chooseBaseBranch(base, model.baseRepo, model.baseBranch, model::baseBranch::set)
}
val head = ActionLink("")
head.addActionListener {
chooseHeadRepoAndBranch(head, model.headRepo, model.headBranch) { repo, branch ->
model.setHead(repo, branch)
model.headSetByUser = true
}
}
val changesWarningLabel = JLabel(AllIcons.General.Warning)
model.addAndInvokeDirectionChangesListener {
val baseRepoPath = model.baseRepo.repository.repositoryPath
val headRepo = model.headRepo
val headRepoPath = headRepo?.repository?.repositoryPath
val baseBranch = model.baseBranch
val headBranch = model.headBranch
val showRepoOwners = headRepoPath != null && baseRepoPath != headRepoPath
val baseText = getRepoText(baseRepoPath, showRepoOwners, baseBranch)
base.text = baseText
base.toolTipText = baseText
val headText = getRepoText(headRepoPath, showRepoOwners, headBranch)
head.text = headText
head.toolTipText = headText
with(changesWarningLabel) {
if (headRepo != null && headBranch != null && headBranch is GitLocalBranch) {
val headRemote = headRepo.gitRemote
val pushTarget = GithubGitHelper.findPushTarget(headRemote.repository, headRemote.remote, headBranch)
if (pushTarget == null) {
toolTipText = GithubBundle.message("pull.request.create.warning.push", headBranch.name, headRemote.remote.name)
isVisible = true
return@with
}
else {
val repo = headRemote.repository
val localHash = repo.branches.getHash(headBranch)
val remoteHash = repo.branches.getHash(pushTarget.branch)
if (localHash != remoteHash) {
toolTipText = GithubBundle.message("pull.request.create.warning.not.synced", headBranch.name, pushTarget.branch.name)
isVisible = true
return@with
}
}
}
isVisible = false
}
}
return JPanel(null).apply {
isOpaque = false
layout = MigLayout(LC()
.gridGap("0", "0")
.insets("0", "0", "0", "0"))
add(base, CC().minWidth("${UI.scale(30)}"))
add(JLabel(" ${UIUtil.leftArrow()} ").apply {
foreground = UIUtil.getInactiveTextColor()
border = JBUI.Borders.empty(0, 5)
})
add(head, CC().minWidth("${UI.scale(30)}"))
add(changesWarningLabel, CC().gapLeft("${UI.scale(10)}"))
}
}
private fun chooseBaseBranch(parentComponent: JComponent,
currentRepo: GHGitRepositoryMapping,
currentBranch: GitRemoteBranch?,
applySelection: (GitRemoteBranch?) -> Unit) {
val branchModel = MutableCollectionComboBoxModel<GitRemoteBranch>().apply {
val remote = currentRepo.gitRemote.remote
val branches = currentRepo.gitRemote.repository.branches.remoteBranches.filter {
it.remote == remote
}
replaceAll(branches.sortedWith(BRANCHES_COMPARATOR))
selectedItem = currentBranch.takeIf { it != null && branches.contains(it) }
}
val popup = createPopup(branchModel,
GithubBundle.message("pull.request.create.direction.base.repo"),
JBTextField(currentRepo.repository.repositoryPath.toString()).apply {
isEnabled = false
}) {
applySelection(branchModel.selected)
}
popup.showUnderneathOf(parentComponent)
}
private fun chooseHeadRepoAndBranch(parentComponent: JComponent,
currentRepo: GHGitRepositoryMapping?,
currentBranch: GitBranch?,
applySelection: (GHGitRepositoryMapping?, GitBranch?) -> Unit) {
val repoModel = CollectionComboBoxModel(repositoriesManager.knownRepositories.toList(), currentRepo)
val branchModel = MutableCollectionComboBoxModel<GitBranch>()
repoModel.addListDataListener(object : ListDataListener {
override fun intervalAdded(e: ListDataEvent) {}
override fun intervalRemoved(e: ListDataEvent) {}
override fun contentsChanged(e: ListDataEvent) {
if (e.index0 == -1 && e.index1 == -1) updateHeadBranches(repoModel.selected, branchModel)
}
})
updateHeadBranches(repoModel.selected, branchModel)
if (currentBranch != null && branchModel.items.contains(currentBranch)) branchModel.selectedItem = currentBranch
val popup = createPopup(branchModel,
GithubBundle.message("pull.request.create.direction.head.repo"),
ComboBox(repoModel).apply {
renderer = SimpleListCellRenderer.create("") {
it?.repository?.repositoryPath?.toString()
}
}) {
applySelection(repoModel.selected, branchModel.selected)
}
popup.showUnderneathOf(parentComponent)
}
private fun <T : GitBranch> createPopup(branchModel: ComboBoxModel<T>,
@Nls repoRowMessage: String,
repoComponent: JComponent,
onSave: () -> Unit): JBPopup {
var buttonHandler: ((ActionEvent) -> Unit)? = null
val branchComponent = ComboBox(branchModel).apply {
renderer = SimpleListCellRenderer.create<GitBranch>("", GitBranch::getName)
}.also {
ComboboxSpeedSearch.installSpeedSearch(it, GitBranch::getName)
}
val panel = panel(LCFlags.fill) {
row(repoRowMessage) {
repoComponent(CCFlags.growX)
}
row(GithubBundle.message("pull.request.create.direction.branch")) {
branchComponent(CCFlags.growX)
}
row {
right {
button(GithubBundle.message("pull.request.create.direction.save")) {
buttonHandler?.invoke(it)
}
}
}
}.apply {
isFocusCycleRoot = true
border = JBUI.Borders.empty(8, 8, 0, 8)
}
return JBPopupFactory.getInstance()
.createComponentPopupBuilder(panel, repoComponent.takeIf { it.isEnabled } ?: branchComponent)
.setFocusable(false)
.createPopup().apply {
setRequestFocus(true)
}.also { popup ->
branchModel.addListDataListener(object : ListDataListener {
override fun intervalAdded(e: ListDataEvent?) {
invokeLater { popup.pack(true, false) }
}
override fun intervalRemoved(e: ListDataEvent?) {
invokeLater { popup.pack(true, false) }
}
override fun contentsChanged(e: ListDataEvent?) {}
})
buttonHandler = {
onSave()
popup.closeOk(null)
}
}
}
private fun updateHeadBranches(repoMapping: GHGitRepositoryMapping?, branchModel: MutableCollectionComboBoxModel<GitBranch>) {
val repo = repoMapping?.gitRemote?.repository
if (repo == null) {
branchModel.replaceAll(emptyList())
return
}
val remote = repoMapping.gitRemote.remote
val remoteBranches = repo.branches.remoteBranches.filter {
it.remote == remote
}
val branches = repo.branches.localBranches.sortedWith(BRANCHES_COMPARATOR) + remoteBranches.sortedWith(BRANCHES_COMPARATOR)
branchModel.replaceAll(branches)
branchModel.selectedItem = repo.currentBranch
}
companion object {
private val BRANCHES_COMPARATOR = Comparator<GitBranch> { b1, b2 -> StringUtil.naturalCompare(b1.name, b2.name) }
@NlsSafe
private fun getRepoText(repo: GHRepositoryPath?, showOwner: Boolean, branch: GitBranch?): String {
if (repo == null || branch == null) return "Select..."
return repo.toString(showOwner) + ":" + branch.name
}
}
} | apache-2.0 | 9e669d47ad870efed5cb130e77b78e09 | 38.56746 | 140 | 0.659779 | 4.98999 | false | false | false | false |
zdary/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/editor/VcsLogEditor.kt | 3 | 2879 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.ui.editor
import com.intellij.diff.util.FileEditorBase
import com.intellij.icons.AllIcons
import com.intellij.ide.FileIconProvider
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorPolicy
import com.intellij.openapi.fileEditor.FileEditorProvider
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.impl.VcsLogContentUtil
import com.intellij.vcs.log.impl.disposeLogUis
import java.awt.BorderLayout
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JPanel
class VcsLogFileType private constructor() : FileType {
override fun getName(): String = "VcsLog"
override fun getDescription(): String = VcsLogBundle.message("filetype.vcs.log.description")
override fun getDefaultExtension(): String = ""
override fun getIcon(): Icon? = AllIcons.Vcs.Branch
override fun isBinary(): Boolean = true
override fun isReadOnly(): Boolean = true
companion object {
val INSTANCE = VcsLogFileType()
}
}
abstract class VcsLogFile(name: String) : LightVirtualFile(name, VcsLogFileType.INSTANCE, "") {
init {
isWritable = false
}
abstract fun createMainComponent(project: Project): JComponent
}
class VcsLogIconProvider : FileIconProvider {
override fun getIcon(file: VirtualFile, flags: Int, project: Project?): Icon? = (file as? VcsLogFile)?.fileType?.icon
}
class VcsLogEditor(private val project: Project, private val vcsLogFile: VcsLogFile) : FileEditorBase() {
internal val rootComponent: JComponent = JPanel(BorderLayout()).also {
it.add(vcsLogFile.createMainComponent(project), BorderLayout.CENTER)
}
override fun getComponent(): JComponent = rootComponent
override fun getPreferredFocusedComponent(): JComponent? = VcsLogContentUtil.getLogUis(component).firstOrNull()?.mainComponent
override fun getName(): String = VcsLogBundle.message("vcs.log.editor.name")
override fun getFile() = vcsLogFile
}
class VcsLogEditorProvider : FileEditorProvider, DumbAware {
override fun accept(project: Project, file: VirtualFile): Boolean = file is VcsLogFile
override fun createEditor(project: Project, file: VirtualFile): FileEditor {
return VcsLogEditor(project, file as VcsLogFile)
}
override fun getEditorTypeId(): String = "VcsLogEditor"
override fun getPolicy(): FileEditorPolicy = FileEditorPolicy.HIDE_DEFAULT_EDITOR
override fun disposeEditor(editor: FileEditor) {
editor.disposeLogUis()
super.disposeEditor(editor)
}
}
| apache-2.0 | 2131652df48d12664455f695b10f6c68 | 37.905405 | 140 | 0.787774 | 4.456656 | false | false | false | false |
mpcjanssen/simpletask-android | app/src/cloudless/java/nl/mpcjanssen/simpletask/remote/LoginScreen.kt | 1 | 3772 | /**
* This file is part of Todo.txt Touch, an Android app for managing your todo.txt file (http://todotxt.com).
* Copyright (c) 2009-2012 Todo.txt contributors (http://todotxt.com)
* LICENSE:
* Todo.txt Touch 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 2 of the License, or (at your option) any
* later version.
* Todo.txt Touch 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 Todo.txt Touch. If not, see
* //www.gnu.org/licenses/>.
* @author Todo.txt contributors @yahoogroups.com>
* *
* @license http://www.gnu.org/licenses/gpl.html
* *
* @copyright 2009-2012 Todo.txt contributors (http://todotxt.com)
*/
package nl.mpcjanssen.simpletask.remote
import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.provider.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
import androidx.core.app.ActivityCompat
import nl.mpcjanssen.simpletask.Simpletask
import nl.mpcjanssen.simpletask.ThemedNoActionBarActivity
import nl.mpcjanssen.simpletask.TodoApplication
import nl.mpcjanssen.simpletask.databinding.LoginBinding
import nl.mpcjanssen.simpletask.util.showToastLong
class LoginScreen : ThemedNoActionBarActivity() {
private lateinit var binding: LoginBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (FileStore.isAuthenticated) {
switchToTodolist()
}
setTheme(TodoApplication.config.activeTheme)
binding = LoginBinding.inflate(layoutInflater)
setContentView(binding.root)
val loginButton = binding.login
loginButton.setOnClickListener {
startLogin()
}
}
private fun switchToTodolist() {
val intent = Intent(this, Simpletask::class.java)
startActivity(intent)
finish()
}
private fun finishLogin() {
if (FileStore.isAuthenticated) {
switchToTodolist()
} else {
showToastLong(this, "Storage access denied")
}
}
internal fun continueLogin() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager() ) {
val intent = Intent()
intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
val uri: Uri = Uri.fromParts("package", this.packageName, null)
intent.setData(uri)
startActivityForResult(intent, REQUEST_FULL_PERMISSION)
} else {
finishLogin()
}
}
internal fun startLogin() {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_WRITE_PERMISSION)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
REQUEST_WRITE_PERMISSION -> continueLogin()
REQUEST_FULL_PERMISSION -> finishLogin()
}
}
companion object {
private val REQUEST_WRITE_PERMISSION = 1
private val REQUEST_FULL_PERMISSION = 2
internal val TAG = LoginScreen::class.java.simpleName
}
}
| gpl-3.0 | c5fa87d05e6d9fe8623fff43be7ca938 | 35.269231 | 119 | 0.694327 | 4.720901 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/data/network/NetworkUtil.kt | 1 | 7542 | package tech.salroid.filmy.data.network
import android.content.Context
import android.net.ConnectivityManager
import android.util.Log
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import tech.salroid.filmy.BuildConfig
import tech.salroid.filmy.data.local.db.entity.MovieDetails
import tech.salroid.filmy.data.local.model.*
object NetworkUtil {
fun getInTheatersMovies(successCallback: (MoviesResponse?) -> Unit, errorCallback: () -> Unit) {
val call = RetrofitClient.filmyApi.getInTheatersMovies()
call.enqueue(object : Callback<MoviesResponse> {
override fun onResponse(
call: Call<MoviesResponse>,
response: Response<MoviesResponse>
) {
Log.d("webi", "InTheater Movies: ${response.body()}")
successCallback.invoke(response.body())
}
override fun onFailure(call: Call<MoviesResponse>, t: Throwable) {
Log.d("webi", "InTheater Movies Error: ${t.message}")
}
})
}
fun getUpComing(successCallback: (MoviesResponse?) -> Unit, errorCallback: () -> Unit) {
val call = RetrofitClient.filmyApi.getUpcomingMovies()
call.enqueue(object : Callback<MoviesResponse> {
override fun onResponse(
call: Call<MoviesResponse>,
response: Response<MoviesResponse>
) {
Log.d("webi", "Upcoming Movies: ${response.body()}")
successCallback.invoke(response.body())
}
override fun onFailure(call: Call<MoviesResponse>, t: Throwable) {
Log.d("webi", "Upcoming Movies Error: ${t.message}")
}
})
}
fun getTrendingMovies(successCallback: (MoviesResponse?) -> Unit, errorCallback: () -> Unit) {
val call = RetrofitClient.filmyApi.getTrendingMovies()
call.enqueue(object : Callback<MoviesResponse> {
override fun onResponse(
call: Call<MoviesResponse>,
response: Response<MoviesResponse>
) {
Log.d("webi", "Trending Movies: ${response.body()}")
successCallback.invoke(response.body())
}
override fun onFailure(call: Call<MoviesResponse>, t: Throwable) {
Log.d("webi", "Trending Movies Error: ${t.message}")
}
})
}
fun getMovieDetails(
movieId: String,
successCallback: (MovieDetails?) -> Unit,
errorCallback: () -> Unit
) {
val call = RetrofitClient.filmyApi.getMovieDetails(movieId)
call.enqueue(object : Callback<MovieDetails> {
override fun onResponse(
call: Call<MovieDetails>,
response: Response<MovieDetails>
) {
Log.d("webi", "Movie Details: ${response.body()}")
successCallback.invoke(response.body())
}
override fun onFailure(call: Call<MovieDetails>, t: Throwable) {
Log.d("webi", "Movie Details Error: ${t.message}")
}
})
}
fun getRating(
movieId: String,
successCallback: (RatingResponse?) -> Unit,
errorCallback: () -> Unit
) {
val call = RetrofitClient.filmyApi.getOMDBRatings(
FilmyApi.BASE_URL_OMDB,
movieId,
BuildConfig.OMDB_API_KEY,
true,
"json"
)
call.enqueue(object : Callback<RatingResponse> {
override fun onResponse(
call: Call<RatingResponse>,
response: Response<RatingResponse>
) {
Log.d("webi", "Ratings: ${response.body()}")
successCallback.invoke(response.body())
}
override fun onFailure(call: Call<RatingResponse>, t: Throwable) {
Log.d("webi", "Ratings Error: ${t.message}")
}
})
}
fun getCastAndCrew(
movieId: String,
successCallback: (CastAndCrewResponse?) -> Unit,
errorCallback: () -> Unit
) {
val call = RetrofitClient.filmyApi.getCasts(movieId)
call.enqueue(object : Callback<CastAndCrewResponse> {
override fun onResponse(
call: Call<CastAndCrewResponse>,
response: Response<CastAndCrewResponse>
) {
Log.d("webi", "Cast and Crew: ${response.body()}")
successCallback.invoke(response.body())
}
override fun onFailure(call: Call<CastAndCrewResponse>, t: Throwable) {
Log.d("webi", "Cast Error: ${t.message}")
}
})
}
fun getSimilarMovies(
movieId: String,
successCallback: (SimilarMoviesResponse?) -> Unit,
errorCallback: () -> Unit
) {
val call = RetrofitClient.filmyApi.getSimilarMovies(movieId)
call.enqueue(object : Callback<SimilarMoviesResponse> {
override fun onResponse(
call: Call<SimilarMoviesResponse>,
response: Response<SimilarMoviesResponse>
) {
Log.d("webi", "Similar Movies: ${response.body()}")
successCallback.invoke(response.body())
}
override fun onFailure(call: Call<SimilarMoviesResponse>, t: Throwable) {
Log.d("webi", "Similar Movies Error: ${t.message}")
}
})
}
fun getCastDetails(
movieId: String,
successCallback: (CastDetailsResponse?) -> Unit,
errorCallback: () -> Unit
) {
val call = RetrofitClient.filmyApi.getCastDetails(movieId)
call.enqueue(object : Callback<CastDetailsResponse> {
override fun onResponse(
call: Call<CastDetailsResponse>,
response: Response<CastDetailsResponse>
) {
Log.d("webi", "Cast Details: ${response.body()}")
successCallback.invoke(response.body())
}
override fun onFailure(call: Call<CastDetailsResponse>, t: Throwable) {
Log.d("webi", "Cast Details Error: ${t.message}")
}
})
}
fun getCastMovieDetails(
movieId: String,
successCallback: (CastMovieDetailsResponse?) -> Unit,
errorCallback: () -> Unit
) {
val call = RetrofitClient.filmyApi.getCastMovieDetails(movieId)
call.enqueue(object : Callback<CastMovieDetailsResponse> {
override fun onResponse(
call: Call<CastMovieDetailsResponse>,
response: Response<CastMovieDetailsResponse>
) {
Log.d("webi", "Cast Movie Details: ${response.body()}")
successCallback.invoke(response.body())
}
override fun onFailure(call: Call<CastMovieDetailsResponse>, t: Throwable) {
Log.d("webi", "Cast Movie Details Error: ${t.message}")
}
})
}
suspend fun searchMovies(query: String): SearchResultResponse? {
val response = RetrofitClient.filmyApi.searchMovies(query)
return if (response.isSuccessful) {
response.body()
} else {
null
}
}
fun isNetworkConnected(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return cm.activeNetworkInfo != null
}
} | apache-2.0 | b502af5edd62da417b76ec6c9535dd84 | 33.760369 | 100 | 0.567489 | 5.127124 | false | false | false | false |
smmribeiro/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookCellLinesLexer.kt | 1 | 2880 | package org.jetbrains.plugins.notebooks.visualization
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.Document
import com.intellij.psi.tree.IElementType
import org.jetbrains.plugins.notebooks.visualization.NotebookCellLines.CellType
import org.jetbrains.plugins.notebooks.visualization.NotebookCellLines.MarkersAtLines
import kotlin.math.max
interface NotebookCellLinesLexer {
fun shouldParseWholeFile(): Boolean = false
fun markerSequence(chars: CharSequence, ordinalIncrement: Int, offsetIncrement: Int): Sequence<NotebookCellLines.Marker>
companion object {
fun defaultMarkerSequence(underlyingLexerFactory: () -> Lexer,
tokenToCellType: (IElementType) -> CellType?,
chars: CharSequence,
ordinalIncrement: Int,
offsetIncrement: Int): Sequence<NotebookCellLines.Marker> = sequence {
val lexer = underlyingLexerFactory()
lexer.start(chars, 0, chars.length)
var ordinal = 0
while (true) {
val tokenType = lexer.tokenType ?: break
val cellType = tokenToCellType(tokenType)
if (cellType != null) {
yield(NotebookCellLines.Marker(
ordinal = ordinal++ + ordinalIncrement,
type = cellType,
offset = lexer.currentPosition.offset + offsetIncrement,
length = lexer.tokenText.length,
))
}
lexer.advance()
}
}
private fun defaultIntervals(document: Document, markers: List<NotebookCellLines.Marker>): List<NotebookCellLines.Interval> {
val intervals = toIntervalsInfo(document, markers)
val result = mutableListOf<NotebookCellLines.Interval>()
for (i in 0 until (intervals.size - 1)) {
result += NotebookCellLines.Interval(ordinal = i, type = intervals[i].second,
lines = intervals[i].first until intervals[i + 1].first, markers = intervals[i].third)
}
return result
}
fun intervalsGeneratorFromLexer(lexer: NotebookCellLinesLexer): (Document) -> List<NotebookCellLines.Interval> = { document ->
val markers = lexer.markerSequence(document.charsSequence, 0, 0).toList()
defaultIntervals(document, markers)
}
}
}
private fun toIntervalsInfo(document: Document, markers: List<NotebookCellLines.Marker>): List<Triple<Int, CellType, MarkersAtLines>> {
val m = mutableListOf<Triple<Int, CellType, MarkersAtLines>>()
// add first if necessary
if (markers.isEmpty() || document.getLineNumber(markers.first().offset) != 0) {
m += Triple(0, CellType.RAW, MarkersAtLines.NO)
}
for (marker in markers) {
m += Triple(document.getLineNumber(marker.offset), marker.type, MarkersAtLines.TOP)
}
// marker for the end
m += Triple(max(document.lineCount, 1), CellType.RAW, MarkersAtLines.NO)
return m
} | apache-2.0 | 76f12c8ccd20477103092edf2f626134 | 39.013889 | 135 | 0.682986 | 4.682927 | false | false | false | false |
vuyaniShabangu/now.next | Research/Tower-develop/Tower-develop/Android/src/org/droidplanner/android/fragments/actionbar/VehicleStatusFragment.kt | 13 | 4789 | package org.droidplanner.android.fragments.actionbar
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.o3dr.services.android.lib.drone.attribute.AttributeEvent
import com.o3dr.services.android.lib.drone.attribute.AttributeType
import com.o3dr.services.android.lib.drone.property.Battery
import com.o3dr.services.android.lib.drone.property.State
import org.droidplanner.android.R
import org.droidplanner.android.fragments.helpers.ApiListenerFragment
import kotlin.properties.Delegates
/**
* Created by Fredia Huya-Kouadio on 7/24/15.
*/
public class VehicleStatusFragment : ApiListenerFragment() {
companion object {
private val filter = initFilter()
private fun initFilter(): IntentFilter {
val filter = IntentFilter()
filter.addAction(AttributeEvent.STATE_CONNECTED)
filter.addAction(AttributeEvent.STATE_DISCONNECTED)
filter.addAction(AttributeEvent.HEARTBEAT_TIMEOUT)
filter.addAction(AttributeEvent.HEARTBEAT_RESTORED)
filter.addAction(AttributeEvent.BATTERY_UPDATED)
return filter
}
}
private val receiver = object : BroadcastReceiver(){
override fun onReceive(context: Context, intent: Intent) {
when(intent.action){
AttributeEvent.STATE_CONNECTED -> updateAllStatus()
AttributeEvent.STATE_DISCONNECTED -> updateAllStatus()
AttributeEvent.HEARTBEAT_RESTORED -> updateConnectionStatus()
AttributeEvent.HEARTBEAT_TIMEOUT -> updateConnectionStatus()
AttributeEvent.BATTERY_UPDATED -> updateBatteryStatus()
}
}
}
private var title: CharSequence = ""
private val connectedIcon by lazy(LazyThreadSafetyMode.NONE) {
view?.findViewById(R.id.status_vehicle_connection) as ImageView?
}
private val batteryIcon by lazy(LazyThreadSafetyMode.NONE) {
view?.findViewById(R.id.status_vehicle_battery) as ImageView?
}
private var titleView: TextView? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View?{
return inflater?.inflate(R.layout.fragment_vehicle_status, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?){
super.onViewCreated(view, savedInstanceState)
titleView = view.findViewById(R.id.status_actionbar_title) as TextView?
titleView?.text = title
}
override fun onApiConnected() {
updateAllStatus()
broadcastManager.registerReceiver(receiver, filter)
}
override fun onApiDisconnected() {
broadcastManager.unregisterReceiver(receiver)
updateAllStatus()
}
private fun updateAllStatus(){
updateBatteryStatus()
updateConnectionStatus()
}
private fun updateConnectionStatus() {
val drone = drone
connectedIcon?.setImageLevel(
if(drone == null || !drone.isConnected)
0
else {
val state: State = drone.getAttribute(AttributeType.STATE)
if (state.isTelemetryLive)
2
else
1
}
)
}
fun setTitle(title: CharSequence){
this.title = title
titleView?.text = title
}
private fun updateBatteryStatus() {
val drone = drone
batteryIcon?.setImageLevel(
if(drone == null || !drone.isConnected){
0
}
else{
val battery: Battery = drone.getAttribute(AttributeType.BATTERY)
val battRemain = battery.batteryRemain
if (battRemain >= 100) {
8
} else if (battRemain >= 87.5) {
7
} else if (battRemain >= 75) {
6
} else if (battRemain >= 62.5) {
5
} else if (battRemain >= 50) {
4
} else if (battRemain >= 37.5) {
3
} else if (battRemain >= 25) {
2
} else if (battRemain >= 12.5) {
1
} else {
0
}
}
)
}
} | mit | 27666723d310d1f5b75ad5739b2e77fd | 31.364865 | 116 | 0.590938 | 5.362822 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/ibl/EnvironmentHelper.kt | 1 | 3544 | package de.fabmax.kool.pipeline.ibl
import de.fabmax.kool.AssetManager
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.scene.Scene
import de.fabmax.kool.util.Color
import de.fabmax.kool.util.ColorGradient
object EnvironmentHelper {
fun singleColorEnvironment(scene: Scene, color: Color, autoDispose: Boolean = true): EnvironmentMaps {
val bgColor = TextureData2d.singleColor(color.toLinear())
val props = TextureProps(
addressModeU = AddressMode.CLAMP_TO_EDGE, addressModeV = AddressMode.CLAMP_TO_EDGE, addressModeW = AddressMode.CLAMP_TO_EDGE,
minFilter = FilterMethod.NEAREST, magFilter = FilterMethod.NEAREST,
mipMapping = false, maxAnisotropy = 1
)
val cubeTex = TextureCube(props, "singleColorEnv-$color") {
TextureDataCube(bgColor, bgColor, bgColor, bgColor, bgColor, bgColor)
}
val maps = EnvironmentMaps(cubeTex, cubeTex)
if (autoDispose) {
scene.onDispose += {
maps.dispose()
}
}
return maps
}
fun gradientColorEnvironment(scene: Scene, gradient: ColorGradient, autoDispose: Boolean = true): EnvironmentMaps {
val gradientTex = GradientTexture(gradient)
val gradientPass = GradientCubeGenerator(scene, gradientTex)
scene.onDispose += {
gradientTex.dispose()
}
return renderPassEnvironment(scene, gradientPass, autoDispose)
}
suspend fun hdriEnvironment(scene: Scene, hdriPath: String, assetManager: AssetManager, autoDispose: Boolean = true, brightness: Float = 1f): EnvironmentMaps {
val hdriTexProps = TextureProps(minFilter = FilterMethod.NEAREST, magFilter = FilterMethod.NEAREST, mipMapping = false, maxAnisotropy = 1)
val hdri = assetManager.loadAndPrepareTexture(hdriPath, hdriTexProps)
return hdriEnvironment(scene, hdri, autoDispose, brightness)
}
fun hdriEnvironment(scene: Scene, hdri: Texture2d, autoDispose: Boolean = true, brightness: Float = 1f): EnvironmentMaps {
val rgbeDecoder = RgbeDecoder(scene, hdri, brightness)
if (autoDispose) {
scene.onDispose += {
hdri.dispose()
}
}
return renderPassEnvironment(scene, rgbeDecoder, autoDispose)
}
fun renderPassEnvironment(scene: Scene, renderPass: OffscreenRenderPass, autoDispose: Boolean = true): EnvironmentMaps {
val tex = when (renderPass) {
is OffscreenRenderPassCube -> renderPass.colorTexture!!
is OffscreenRenderPass2d -> renderPass.colorTexture!!
else -> throw IllegalArgumentException("Supplied OffscreenRenderPass must be OffscreenRenderPassCube or OffscreenRenderPass2d")
}
val irrMapPass = IrradianceMapPass.irradianceMap(scene, tex)
val reflMapPass = ReflectionMapPass.reflectionMap(scene, tex)
irrMapPass.dependsOn(renderPass)
reflMapPass.dependsOn(renderPass)
val maps = EnvironmentMaps(irrMapPass.copyColor(), reflMapPass.copyColor())
if (autoDispose) {
scene.onDispose += {
maps.dispose()
}
}
scene.addOffscreenPass(renderPass)
scene.addOffscreenPass(irrMapPass)
scene.addOffscreenPass(reflMapPass)
return maps
}
}
class EnvironmentMaps(val irradianceMap: TextureCube, val reflectionMap: TextureCube) {
fun dispose() {
irradianceMap.dispose()
reflectionMap.dispose()
}
}
| apache-2.0 | 21a3c98ba7c8f3e92ad93c8bdd134d87 | 39.735632 | 163 | 0.673251 | 4.700265 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/BackingAddOnsFragmentViewModel.kt | 1 | 28569 | package com.kickstarter.viewmodels
import android.util.Pair
import androidx.annotation.NonNull
import com.kickstarter.libs.Environment
import com.kickstarter.libs.FragmentViewModel
import com.kickstarter.libs.rx.transformers.Transformers.combineLatestPair
import com.kickstarter.libs.rx.transformers.Transformers.takeWhen
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.RewardUtils
import com.kickstarter.libs.utils.RewardUtils.isDigital
import com.kickstarter.libs.utils.RewardUtils.isLocalPickup
import com.kickstarter.libs.utils.RewardUtils.isShippable
import com.kickstarter.mock.factories.ShippingRuleFactory
import com.kickstarter.models.Backing
import com.kickstarter.models.Project
import com.kickstarter.models.Reward
import com.kickstarter.models.ShippingRule
import com.kickstarter.ui.ArgumentsKey
import com.kickstarter.ui.data.PledgeData
import com.kickstarter.ui.data.PledgeReason
import com.kickstarter.ui.data.ProjectData
import com.kickstarter.ui.fragments.BackingAddOnsFragment
import com.kickstarter.viewmodels.usecases.ShowPledgeFragmentUseCase
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
import java.util.Locale
class BackingAddOnsFragmentViewModel {
interface Inputs {
/** Configure with the current [ProjectData] and [Reward].
* @param projectData we get the Project for currency
*/
fun configureWith(pledgeDataAndReason: Pair<PledgeData, PledgeReason>)
/** Call when user selects a shipping location. */
fun shippingRuleSelected(shippingRule: ShippingRule)
/** Emits when the CTA button has been pressed */
fun continueButtonPressed()
/** Emits the quantity per AddOn Id selected */
fun quantityPerId(quantityPerId: Pair<Int, Long>)
/** Invoked when the retry button on the add-on Error alert dialog is pressed */
fun retryButtonPressed()
}
interface Outputs {
/** Emits a Pair containing the projectData and the pledgeReason. */
fun showPledgeFragment(): Observable<Triple<PledgeData, PledgeReason, Boolean>>
/** Emits a Pair containing the projectData and the list for Add-ons associated to that project. */
fun addOnsList(): Observable<Triple<ProjectData, List<Reward>, ShippingRule>>
/** Emits the current selected shipping rule. */
fun selectedShippingRule(): Observable<ShippingRule>
/** Emits a pair of list of shipping rules to be selected and the project. */
fun shippingRulesAndProject(): Observable<Pair<List<ShippingRule>, Project>>
/** Emits the total sum of addOns selected in each item of the addOns list. */
fun totalSelectedAddOns(): Observable<Int>
/** Emits whether or not the shipping selector is visible **/
fun shippingSelectorIsGone(): Observable<Boolean>
/** Emits whether or not the continue button should be enabled **/
fun isEnabledCTAButton(): Observable<Boolean>
/** Emits whether or not the empty state should be shown **/
fun isEmptyState(): Observable<Boolean>
/** Emits an alert dialog when add-ons request results in error **/
fun showErrorDialog(): Observable<Boolean>
}
class ViewModel(@NonNull val environment: Environment) : FragmentViewModel<BackingAddOnsFragment>(environment), Outputs, Inputs {
val inputs = this
val outputs = this
private val shippingRules = PublishSubject.create<List<ShippingRule>>()
private val addOnsFromGraph = PublishSubject.create<List<Reward>>()
private var pledgeDataAndReason = BehaviorSubject.create<Pair<PledgeData, PledgeReason>>()
private val shippingRuleSelected = PublishSubject.create<ShippingRule>()
private val shippingRulesAndProject = PublishSubject.create<Pair<List<ShippingRule>, Project>>()
private val projectAndReward: Observable<Pair<Project, Reward>>
private val retryButtonPressed = BehaviorSubject.create<Boolean>()
private val pledgeFragmentData = PublishSubject.create<Pair<PledgeData, PledgeReason>>()
private val showPledgeFragment = PublishSubject.create<Triple<PledgeData, PledgeReason, Boolean>>()
private val shippingSelectorIsGone = BehaviorSubject.create<Boolean>()
private val addOnsListFiltered = PublishSubject.create<Triple<ProjectData, List<Reward>, ShippingRule>>()
private val isEmptyState = PublishSubject.create<Boolean>()
private val showErrorDialog = BehaviorSubject.create<Boolean>()
private val continueButtonPressed = BehaviorSubject.create<Void>()
private val isEnabledCTAButton = BehaviorSubject.create<Boolean>()
// - Current addOns selection
private val totalSelectedAddOns = BehaviorSubject.create(0)
private val quantityPerId = PublishSubject.create<Pair<Int, Long>>()
private val currentSelection = BehaviorSubject.create(mutableMapOf<Long, Int>())
// - Environment Objects
private val currentUser = requireNotNull(this.environment.currentUser()?.observable())
private val optimizely = requireNotNull(this.environment.optimizely())
private val apolloClient = requireNotNull(this.environment.apolloClient())
private val currentConfig = requireNotNull(environment.currentConfig())
init {
val pledgeData = arguments()
.map { it.getParcelable(ArgumentsKey.PLEDGE_PLEDGE_DATA) as PledgeData? }
.ofType(PledgeData::class.java)
pledgeData
.take(1)
.compose(bindToLifecycle())
.subscribe(this.analyticEvents::trackAddOnsScreenViewed)
val pledgeReason = arguments()
.map { it.getSerializable(ArgumentsKey.PLEDGE_PLEDGE_REASON) as PledgeReason }
val projectData = pledgeData
.map { it.projectData() }
val project = projectData
.map { it.project() }
val rewardPledge = pledgeData
.map { it.reward() }
val backing = projectData
.map { getBackingFromProjectData(it) }
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
val backingReward = backing
.map { it.reward() }
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
val isSameReward = rewardPledge
.compose<Pair<Reward, Reward>>(combineLatestPair(backingReward))
.map { it.first.id() == it.second.id() }
isSameReward
.filter { !it }
.compose(bindToLifecycle())
.subscribe {
this.currentSelection.value?.clear()
}
val filteredBackingReward = backingReward
.compose<Pair<Reward, Boolean>>(combineLatestPair(isSameReward))
.filter { it.second }
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
.map { it.first }
val reward = Observable.merge(rewardPledge, filteredBackingReward)
projectAndReward = project
.compose<Pair<Project, Reward>>(combineLatestPair(reward))
// - If changing rewards do not emmit the backing information
val backingShippingRule = backing
.compose<Pair<Backing, Boolean>>(combineLatestPair(isSameReward))
.filter { it.second }
.map { it.first }
.compose<Pair<Backing, List<ShippingRule>>>(combineLatestPair(shippingRules))
.map {
it.second.first { rule ->
rule.location()?.id() == it.first.locationId()
}
}
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
// - In case of digital Reward to follow the same flow as the rest of use cases use and empty shippingRule
reward
.filter { isDigital(it) || !isShippable(it) || isLocalPickup(it) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe {
this.shippingSelectorIsGone.onNext(true)
}
val addOnsFromBacking = backing
.compose<Pair<Backing, Boolean>>(combineLatestPair(isSameReward))
.filter { it.second }
.map { it.first }
.map { it.addOns()?.toList() }
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
.distinctUntilChanged()
val combinedList = addOnsFromBacking
.compose<Pair<List<Reward>, List<Reward>>>(combineLatestPair(addOnsFromGraph))
.map { joinSelectedWithAvailableAddOns(it.first, it.second) }
.distinctUntilChanged()
val addonsList = Observable.merge(addOnsFromGraph, combinedList)
.map { filterOutUnAvailableOrEndedExceptIfBacked(it) }
.distinctUntilChanged()
shippingRules
.compose<Pair<List<ShippingRule>, Project>>(combineLatestPair(project))
.compose(bindToLifecycle())
.subscribe(this.shippingRulesAndProject)
val defaultShippingRule = shippingRules
.filter { it.isNotEmpty() }
.compose<Pair<List<ShippingRule>, Reward>>(combineLatestPair(reward))
.filter { !isDigital(it.second) && isShippable(it.second) && !isLocalPickup(it.second) }
.switchMap { defaultShippingRule(it.first) }
val shippingRule = getSelectedShippingRule(defaultShippingRule, isSameReward, backingShippingRule, reward)
shippingRule
.distinctUntilChanged { rule1, rule2 ->
rule1.location()?.id() == rule2.location()?.id() && rule1.cost() == rule2.cost()
}
.compose(bindToLifecycle())
.subscribe {
this.shippingRuleSelected.onNext(it)
}
Observable
.combineLatest(this.retryButtonPressed.startWith(false), reward) { _, rw ->
return@combineLatest this.apolloClient
.getShippingRules(rw)
.doOnError {
this.showErrorDialog.onNext(true)
this.shippingSelectorIsGone.onNext(true)
}
.onErrorResumeNext(Observable.empty())
}
.filter { ObjectUtils.isNotNull(it) }
.switchMap { it }
.map { it.shippingRules() }
.filter { ObjectUtils.isNotNull(it) }
.compose(bindToLifecycle())
.subscribe {
shippingRules.onNext(it.filterNotNull())
}
val location = this.shippingRuleSelected
.map { it.location() }
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
Observable
.combineLatest(this.retryButtonPressed.startWith(false), project, location) {
_, pj, shipRuleLocation ->
val projectSlug = pj.slug() ?: ""
return@combineLatest this.apolloClient
.getProjectAddOns(projectSlug, shipRuleLocation)
.doOnError {
this.showErrorDialog.onNext(true)
this.shippingSelectorIsGone.onNext(true)
}
.onErrorResumeNext(Observable.empty())
}
.switchMap { it }
.filter { ObjectUtils.isNotNull(it) }
.subscribe(addOnsFromGraph)
val filteredAddOns = Observable.combineLatest(addonsList, projectData, this.shippingRuleSelected, reward) {
list, pData, rule, rw ->
return@combineLatest filterByLocation(list, pData, rule, rw)
}
.distinctUntilChanged()
.compose(bindToLifecycle())
filteredAddOns
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.addOnsListFiltered)
filteredAddOns
.map { it.second.isEmpty() }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.isEmptyState)
this.quantityPerId
.compose<Pair<Pair<Int, Long>, Triple<ProjectData, List<Reward>, ShippingRule>>>(combineLatestPair(this.addOnsListFiltered))
.compose(bindToLifecycle())
.distinctUntilChanged()
.subscribe {
updateQuantityById(it.first)
calculateTotal(it.second.second)
}
// - .startWith(ShippingRuleFactory.emptyShippingRule()) because we need to trigger this validation every time the AddOns selection changes for digital rewards as well
val isButtonEnabled = Observable.combineLatest(
backingShippingRule.startWith(ShippingRuleFactory.emptyShippingRule()),
addOnsFromBacking,
this.shippingRuleSelected,
this.currentSelection.take(1),
this.quantityPerId
) {
backedRule, backedList, actualRule, currentSelection, _ ->
return@combineLatest isDifferentLocation(backedRule, actualRule) || isDifferentSelection(backedList, currentSelection)
}
.distinctUntilChanged()
isButtonEnabled
.compose(bindToLifecycle())
.subscribe {
this.isEnabledCTAButton.onNext(it)
}
val updatedPledgeDataAndReason = getUpdatedPledgeData(
this.addOnsListFiltered,
pledgeData,
pledgeReason,
reward,
this.shippingRuleSelected,
this.currentSelection.take(1),
this.continueButtonPressed
)
updatedPledgeDataAndReason
.compose<Pair<PledgeData, PledgeReason>>(takeWhen(this.continueButtonPressed))
.compose(bindToLifecycle())
.subscribe {
this.analyticEvents.trackAddOnsContinueCTA(it.first)
this.pledgeFragmentData.onNext(it)
}
ShowPledgeFragmentUseCase(this.pledgeFragmentData)
.data(this.currentUser, this.optimizely)
.compose(bindToLifecycle())
.subscribe {
this.showPledgeFragment.onNext(it)
}
}
/**
* Observable containing the correct shippingRule to each case
*/
private fun getSelectedShippingRule(
defaultShippingRule: Observable<ShippingRule>,
isSameReward: Observable<Boolean>,
backingShippingRule: Observable<ShippingRule>,
reward: Observable<Reward>
): Observable<ShippingRule> {
return Observable.combineLatest(
defaultShippingRule.startWith(ShippingRuleFactory.emptyShippingRule()),
isSameReward.startWith(false),
backingShippingRule.startWith(ShippingRuleFactory.emptyShippingRule()),
reward
) { defaultShipping, sameRw, backingRule, rw ->
return@combineLatest chooseShippingRule(defaultShipping, backingRule, sameRw, rw)
}
}
/**
* The use cases for populating the shipping rule selector:
* - First pledge or choosing another reward, we load in the shipping selector the default shipping rule
* - Digital or not shippable we return empty shippingRule to unify flow for all rewards types
* - Choosing to update same reward use the backing shippingRule
*/
private fun chooseShippingRule(defaultShipping: ShippingRule, backingShippingRule: ShippingRule, sameReward: Boolean, rw: Reward): ShippingRule =
when {
isDigital(rw) || !isShippable(rw) || isLocalPickup(rw) -> ShippingRuleFactory.emptyShippingRule()
sameReward -> backingShippingRule
else -> defaultShipping
}
/**
* Updates the pledgeData object if necessary. This observable should
* emit only once, when the user press the continue button. As we will update
* the selected quantity into the concrete items.
*
* @return updatedPledgeData depending on the selected shipping rule,
* if any addOn has been selected
*/
private fun getUpdatedPledgeData(
filteredList: Observable<Triple<ProjectData, List<Reward>, ShippingRule>>,
pledgeData: Observable<PledgeData>,
pledgeReason: Observable<PledgeReason>,
reward: Observable<Reward>,
shippingRule: Observable<ShippingRule>,
currentSelection: Observable<MutableMap<Long, Int>>,
continueButtonPressed: Observable<Void>
): Observable<Pair<PledgeData, PledgeReason>> {
return Observable.combineLatest(filteredList, pledgeData, pledgeReason, reward, shippingRule, currentSelection, continueButtonPressed) {
listAddOns, pledgeData, pledgeReason, rw, shippingRule, currentSelection, _ ->
val updatedList = updateQuantity(listAddOns.second, currentSelection)
val selectedAddOns = getSelectedAddOns(updatedList)
val updatedPledgeData = updatePledgeData(selectedAddOns, rw, pledgeData, shippingRule)
return@combineLatest Pair(updatedPledgeData, pledgeReason)
}
}
/**
* Updated list filtering out the addOns with quantity higher than 1
* @return selected addOns
*/
private fun getSelectedAddOns(updatedList: List<Reward>): List<Reward> {
return updatedList.filter { addOn ->
addOn.quantity()?.let { it > 0 } ?: false
}
}
/**
* Update the pledgeData according to:
* - The user has selected addOns, the reward is digital or shippable
*
* @param finalList
* @param rw
* @param pledgeData
* @param shippingRule
*
* @return pledgeData
*/
private fun updatePledgeData(finalList: List<Reward>, rw: Reward, pledgeData: PledgeData, shippingRule: ShippingRule) =
if (finalList.isNotEmpty()) {
if (isShippable(rw) && !isDigital(rw) && !isLocalPickup(rw)) {
pledgeData.toBuilder()
.addOns(finalList)
.shippingRule(shippingRule)
.build()
} else pledgeData.toBuilder()
.addOns(finalList)
.build()
} else {
pledgeData.toBuilder()
.build()
}
/**
* Update the items in the list with the current selected amount.
*
* This function should be called when the user hits the button
* either to continue or skip addOns.
* We update the amount at this point in order to avoid re-build the
* entire list every time the selection for some concrete addOns change,
* which leads to re-triggering all the subscriptions.
*
* @param addOnsList -> actual addOns list
* @param currentSelection -> current selection of addOns
*/
private fun updateQuantity(addOnsList: List<Reward>, currentSelection: MutableMap<Long, Int>): List<Reward> =
addOnsList.map { addOn ->
if (currentSelection.containsKey(addOn.id())) {
return@map addOn.toBuilder().quantity(currentSelection[addOn.id()]).build()
} else return@map addOn
}
/**
* In case selecting the same reward, if any of the addOns is unavailable or
* has an invalid time range but has been backed do NOT filter out that addOn
* and allow to modify the selection.
*
* In case selecting another reward or new pledge, filter out the unavailable/invalid time range ones
*
* @param combinedList -> combinedList of Graph addOns and backed ones
* @return List<Reward> -> filtered list depending on availability and time range if new pledge
* @return List<Reward> -> not filtered if the addOn item was previously backed
*/
private fun filterOutUnAvailableOrEndedExceptIfBacked(combinedList: List<Reward>): List<Reward> {
return combinedList.filter { addOn ->
addOn.quantity()?.let { it > 0 } ?: (addOn.isAvailable() && RewardUtils.isValidTimeRange(addOn))
}
}
/**
* Extract the ID:quantity from the original baked AddOns list
* in case the ID's of those addOns and the quantity are the same
* as the current selected ones the selection is the same as the
* backed one.
*
* @param backedList -> addOns list from backing object
* @param currentSelection -> map holding addOns selection, on first load if backed addOns
* will hold the id and amount by id.
* @return Boolean -> true in case different selection or new item selected false otherwise
*/
private fun isDifferentSelection(backedList: List<Reward>, currentSelection: MutableMap<Long, Int>): Boolean {
val backedSelection: MutableMap<Long, Int> = mutableMapOf()
backedList
.map {
backedSelection.put(it.id(), it.quantity() ?: 0)
}
val isBackedItemList = currentSelection.map { item ->
if (backedSelection.containsKey(item.key)) backedSelection[item.key] == item.value
else false
}
val isNewItemSelected = currentSelection.map { item ->
if (!backedSelection.containsKey(item.key)) item.value > 0
else false
}.any { it }
val sameSelection = isBackedItemList.filter { it }.size == backedSelection.size
return !sameSelection || isNewItemSelected
}
private fun isDifferentLocation(backedRule: ShippingRule, actualRule: ShippingRule) =
backedRule.location()?.id() != actualRule.location()?.id()
private fun calculateTotal(list: List<Reward>) =
this.currentSelection
.take(1)
.map { map ->
var total = 0
list.map { total += map[it.id()] ?: 0 }
return@map total
}
.filter { ObjectUtils.isNotNull(it) }
.compose(bindToLifecycle())
.subscribe {
this.totalSelectedAddOns.onNext(it)
}
private fun joinSelectedWithAvailableAddOns(backingList: List<Reward>, graphList: List<Reward>): List<Reward> {
return graphList
.map { graphAddOn ->
modifyIfBacked(backingList, graphAddOn)
}
}
/**
* If the addOn is previously backed, return the backedAddOn containing
* in the field quantity the amount of backed addOns.
* Modify it to hold the shippingRules from the graphAddOn, that information
* is not available in backing -> addOns graphQL schema.
*/
private fun modifyIfBacked(backingList: List<Reward>, graphAddOn: Reward): Reward {
return backingList.firstOrNull { it.id() == graphAddOn.id() }?.let {
return@let it.toBuilder().shippingRules(graphAddOn.shippingRules()).build()
} ?: graphAddOn
}
private fun getBackingFromProjectData(pData: ProjectData?) = pData?.project()?.backing()
?: pData?.backing()
private fun updateQuantityById(updated: Pair<Int, Long>) =
this.currentSelection
.take(1)
.subscribe { selection ->
selection[updated.second] = updated.first
}
private fun defaultShippingRule(shippingRules: List<ShippingRule>): Observable<ShippingRule> {
return this.currentConfig.observable()
.map { it.countryCode() }
.map { countryCode ->
shippingRules.firstOrNull { it.location()?.country() == countryCode }
?: shippingRules.first()
}
}
// - This will disappear when the query is ready in the backend [CT-649]
private fun filterByLocation(addOns: List<Reward>, pData: ProjectData, rule: ShippingRule, rw: Reward): Triple<ProjectData, List<Reward>, ShippingRule> {
val filteredAddOns = when (rw.shippingPreference()) {
Reward.ShippingPreference.UNRESTRICTED.name,
Reward.ShippingPreference.UNRESTRICTED.name.lowercase(Locale.getDefault()) -> {
addOns.filter {
it.shippingPreferenceType() == Reward.ShippingPreference.UNRESTRICTED || containsLocation(rule, it) || isDigital(it)
}
}
Reward.ShippingPreference.RESTRICTED.name,
Reward.ShippingPreference.RESTRICTED.name.lowercase(Locale.getDefault()) -> {
addOns.filter { containsLocation(rule, it) || isDigital(it) }
}
Reward.ShippingPreference.LOCAL.name,
Reward.ShippingPreference.LOCAL.name.lowercase(Locale.getDefault()) -> {
addOns.filter { it.localReceiptLocation() == rw.localReceiptLocation() || isDigital(it) }
}
else -> {
if (isDigital(rw))
addOns.filter { isDigital(it) }
else emptyList()
}
}
return Triple(pData, filteredAddOns, rule)
}
private fun containsLocation(rule: ShippingRule, reward: Reward): Boolean {
val idLocations = reward
.shippingRules()
?.map {
it.location()?.id()
} ?: emptyList()
return idLocations.contains(rule.location()?.id())
}
// - Inputs
override fun configureWith(pledgeDataAndReason: Pair<PledgeData, PledgeReason>) = this.pledgeDataAndReason.onNext(pledgeDataAndReason)
override fun shippingRuleSelected(shippingRule: ShippingRule) = this.shippingRuleSelected.onNext(shippingRule)
override fun continueButtonPressed() = this.continueButtonPressed.onNext(null)
override fun quantityPerId(quantityPerId: Pair<Int, Long>) = this.quantityPerId.onNext(quantityPerId)
override fun retryButtonPressed() = this.retryButtonPressed.onNext(true)
// - Outputs
@NonNull
override fun showPledgeFragment(): Observable<Triple<PledgeData, PledgeReason, Boolean>> = this.showPledgeFragment
override fun addOnsList(): Observable<Triple<ProjectData, List<Reward>, ShippingRule>> = this.addOnsListFiltered
override fun selectedShippingRule(): Observable<ShippingRule> = this.shippingRuleSelected
override fun shippingRulesAndProject(): Observable<Pair<List<ShippingRule>, Project>> = this.shippingRulesAndProject
override fun totalSelectedAddOns(): Observable<Int> = this.totalSelectedAddOns
override fun shippingSelectorIsGone(): Observable<Boolean> = this.shippingSelectorIsGone
override fun isEnabledCTAButton(): Observable<Boolean> = this.isEnabledCTAButton
override fun isEmptyState(): Observable<Boolean> = this.isEmptyState
override fun showErrorDialog(): Observable<Boolean> = this.showErrorDialog
}
}
| apache-2.0 | 0872708dbb142a21dcc2cb0682448148 | 44.857143 | 179 | 0.603521 | 5.657228 | false | false | false | false |
fabmax/kool | kool-core/src/jsMain/kotlin/de/fabmax/kool/platform/ImageAtlasTextureData.kt | 1 | 1305 | package de.fabmax.kool.platform
import de.fabmax.kool.pipeline.TexFormat
import de.fabmax.kool.pipeline.TextureData
import kotlinx.browser.document
import org.w3c.dom.CanvasRenderingContext2D
import org.w3c.dom.HTMLCanvasElement
import org.w3c.dom.HTMLImageElement
import org.w3c.dom.ImageData
class ImageAtlasTextureData(image: HTMLImageElement, tilesX: Int, tilesY: Int, fmt: TexFormat?) : TextureData() {
override val data: Array<ImageData>
init {
if (!image.complete) {
throw IllegalStateException("Image must be complete")
}
width = image.width / tilesX
height = image.height / tilesY
val w = width.toDouble()
val h = height.toDouble()
depth = tilesX * tilesY
fmt?.let { format = it }
val canvas = document.createElement("canvas") as HTMLCanvasElement
canvas.width = width
canvas.height = height
val canvasCtx = canvas.getContext("2d") as CanvasRenderingContext2D
data = Array(depth) { i ->
val x = (i % tilesX).toDouble()
val y = (i / tilesX).toDouble()
canvasCtx.clearRect(0.0, 0.0, w, h)
canvasCtx.drawImage(image, x * w, y * h, w, h, 0.0, 0.0, w, h)
canvasCtx.getImageData(0.0, 0.0, w, h)
}
}
} | apache-2.0 | 0b578a45a4e052cab236946f176c3f42 | 32.487179 | 113 | 0.634483 | 3.760807 | false | false | false | false |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Delivery_Status.kt | 1 | 874 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_General_Delivery_Status(
injector: HasAndroidInjector
) : DanaRS_Packet(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__DELIVERY_STATUS
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override fun getFriendlyName(): String {
return "REVIEW__DELIVERY_STATUS"
}
} | agpl-3.0 | 16a19ff3b839b361701cc89492780f32 | 28.166667 | 75 | 0.66476 | 4.528497 | false | false | false | false |
intrications/quick-call-back-notification-android | app/src/main/java/com/intrications/callbacknotification/CallReceiver.kt | 1 | 2217 | package com.intrications.callbacknotification
import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.support.v4.app.NotificationCompat
import com.intrications.callbacknotification.util.PhonecallReceiver
import java.util.*
class CallReceiver : PhonecallReceiver() {
override fun onIncomingCallStarted(ctx: Context, number: String, start: Date) {
showNotification(ctx, number)
setAlarmToHideNotification(ctx, number)
}
private fun setAlarmToHideNotification(ctx: Context, number: String) {
val intent = Intent(ctx, CancelNotificationReceiver::class.java)
intent.putExtra("phone_number", number)
val pendingIntent = PendingIntent.getBroadcast(ctx, 999, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val am = ctx.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val tenMinutes = 1000 * 60 * 10
am.set(AlarmManager.RTC, System.currentTimeMillis() + tenMinutes, pendingIntent)
}
private fun showNotification(ctx: Context, number: String) {
val callIntent = Intent(Intent.ACTION_DIAL)
callIntent.data = Uri.parse("tel:" + number)
val pendingIntent = PendingIntent.getActivity(ctx, 0, callIntent, 0)
val builder = NotificationCompat.Builder(ctx)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.ic_status)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentTitle("Phone call from " + number)
.setContentText("Tap to call back")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Use hashcode of number so there is one notification for each phone number
nm.notify(number.hashCode(), builder.build())
}
override fun onIncomingCallEnded(ctx: Context, number: String, start: Date, end: Date) {
}
override fun onMissedCall(ctx: Context, number: String, start: Date) {
}
} | apache-2.0 | 564bfdaa9700d5b318a2c46d656982c8 | 39.327273 | 107 | 0.707713 | 4.638075 | false | false | false | false |
siosio/intellij-community | plugins/ml-local-models/src/com/intellij/ml/local/models/LocalModelsTraining.kt | 2 | 6394 | package com.intellij.ml.local.models
import com.intellij.lang.Language
import com.intellij.ml.local.MlLocalModelsBundle
import com.intellij.ml.local.models.api.LocalModelBuilder
import com.intellij.ml.local.models.api.LocalModelFactory
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.progress.util.ProgressIndicatorUtils
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ContentIterator
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.VirtualFileWithId
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.source.resolve.ResolveCache
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import kotlin.system.measureTimeMillis
object LocalModelsTraining {
private val LOG = logger<LocalModelsTraining>()
private const val MAX_FILE_PROCESSING_RETRIES = 10
private const val DELAY_BETWEEN_RETRIES_IN_MS = 300L
@Volatile private var isTraining = false
fun isTraining(): Boolean = isTraining
fun train(project: Project, language: Language) = ApplicationManager.getApplication().executeOnPooledThread {
val fileType = language.associatedFileType ?: throw IllegalArgumentException("Unsupported language")
if (isTraining) {
LOG.error("Training has already started.")
return@executeOnPooledThread
}
isTraining = true
val modelsManager = LocalModelsManager.getInstance(project)
val factories = LocalModelFactory.forLanguage(language)
factories.forEach { modelsManager.unregisterModel(language, it.id) }
val id2builder = factories.associate { it.id to it.modelBuilder(project, language) }
val task = object : Task.Backgroundable(project, MlLocalModelsBundle.message("ml.local.models.training.title"), true) {
override fun run(indicator: ProgressIndicator) {
val files = getFiles(project, fileType)
id2builder.forEach { it.value.onStarted() }
val ids = id2builder.keys.joinToString(", ")
LOG.info("Local models training started for language ${language.id} and models: $ids")
val ms = measureTimeMillis {
processFiles(files, id2builder, project, indicator)
}
markModelsFinished(LocalModelBuilder.FinishReason.SUCCESS)
LOG.info("Training finished for language ${language.id} and models: $ids. Duration: $ms ms")
id2builder.forEach {
it.value.build()?.let { model ->
modelsManager.registerModel(language, model)
}
}
}
override fun onCancel() = markModelsFinished(LocalModelBuilder.FinishReason.CANCEL)
override fun onThrowable(error: Throwable) {
markModelsFinished(LocalModelBuilder.FinishReason.ERROR)
super.onThrowable(error)
}
private fun markModelsFinished(reason: LocalModelBuilder.FinishReason) = id2builder.forEach { it.value.onFinished(reason) }
override fun onFinished() {
isTraining = false
}
}
ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, BackgroundableProcessIndicator(task))
}
private fun processFiles(files: Set<Int>, modelBuilders: Map<String, LocalModelBuilder>, project: Project,
indicator: ProgressIndicator) {
val resolveCache = ResolveCache.getInstance(project)
val dumbService = DumbService.getInstance(project)
indicator.isIndeterminate = false
indicator.text = MlLocalModelsBundle.message("ml.local.models.training.files.processing")
indicator.fraction = 0.0
val processed = AtomicInteger(0)
for (fileId in files) {
for (id2builder in modelBuilders) {
if (indicator.isCanceled) {
throw ProcessCanceledException()
}
var retriesCount = 0
while (retriesCount < MAX_FILE_PROCESSING_RETRIES &&
!tryProcessFile(fileId, id2builder.key, id2builder.value.fileVisitor(), project)) {
if (indicator.isCanceled) {
throw ProcessCanceledException()
}
if (dumbService.isDumb) {
dumbService.waitForSmartMode()
} else {
try {
TimeUnit.MILLISECONDS.sleep(DELAY_BETWEEN_RETRIES_IN_MS)
} catch (ignore: InterruptedException) { }
}
retriesCount++
ProgressIndicatorUtils.yieldToPendingWriteActions(indicator)
}
if (retriesCount >= MAX_FILE_PROCESSING_RETRIES) {
LOG.warn("Too much retries to process file with id: $fileId. Model: ${id2builder.key}")
}
}
resolveCache.clearCache(true)
indicator.fraction = processed.incrementAndGet().toDouble() / files.size
}
}
private fun tryProcessFile(fileId: Int, modelId: String, fileVisitor: PsiElementVisitor, project: Project): Boolean =
ProgressIndicatorUtils.runInReadActionWithWriteActionPriority {
if (DumbService.isDumb(project)) {
throw ProcessCanceledException()
}
VirtualFileManager.getInstance().findFileById(fileId)?.let { file ->
PsiManager.getInstance(project).findFile(file)?.let { psiFile ->
try {
psiFile.accept(fileVisitor)
}
catch (pce: ProcessCanceledException) {
throw pce
}
catch (e: Throwable) {
LOG.warn("Model: $modelId. File: ${file.path}.", e)
}
}
}
}
private fun getFiles(project: Project, fileType: FileType): Set<Int> {
val index = ProjectFileIndex.getInstance(project)
val fileIds = mutableSetOf<Int>()
runReadAction {
index.iterateContent(ContentIterator { file ->
if (file is VirtualFileWithId && file.fileType == fileType) {
fileIds.add(file.id)
}
true
})
}
return fileIds
}
} | apache-2.0 | 1ffe1e8ef3d77f7622052290a6000b67 | 39.732484 | 129 | 0.709102 | 4.667153 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddConstModifierFix.kt | 1 | 5379 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementFactory
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.search.allScope
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.resolve.checkers.ConstModifierChecker
import org.jetbrains.kotlin.resolve.source.PsiSourceElement
class AddConstModifierFix(property: KtProperty) : AddModifierFix(property, KtTokens.CONST_KEYWORD), CleanupFix {
private val pointer = property.createSmartPointer()
override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) {
val property = pointer.element ?: return
addConstModifier(property)
}
companion object {
private val removeAnnotations = listOf(FqName("kotlin.jvm.JvmStatic"), FqName("kotlin.jvm.JvmField"))
fun addConstModifier(property: KtProperty) {
val annotationsToRemove = removeAnnotations.mapNotNull { property.findAnnotation(it) }
replaceReferencesToGetterByReferenceToField(property)
runWriteAction {
property.addModifier(KtTokens.CONST_KEYWORD)
annotationsToRemove.forEach(KtAnnotationEntry::delete)
}
}
}
}
class AddConstModifierIntention : SelfTargetingIntention<KtProperty>(
KtProperty::class.java,
KotlinBundle.lazyMessage("fix.add.const.modifier"),
) {
override fun applyTo(element: KtProperty, editor: Editor?) = AddConstModifierFix.addConstModifier(element)
override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean = isApplicableTo(element)
companion object {
fun isApplicableTo(element: KtProperty): Boolean {
with(element) {
if (isLocal || isVar || hasDelegate() || initializer == null
|| getter?.hasBody() == true || receiverTypeReference != null
|| hasModifier(KtTokens.CONST_KEYWORD) || hasModifier(KtTokens.OVERRIDE_KEYWORD) || hasActualModifier()
) {
return false
}
}
val propertyDescriptor = element.descriptor as? VariableDescriptor ?: return false
return ConstModifierChecker.canBeConst(element, element, propertyDescriptor)
}
}
}
object ConstFixFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val expr = diagnostic.psiElement as? KtReferenceExpression ?: return null
val targetDescriptor = expr.resolveToCall()?.resultingDescriptor as? VariableDescriptor ?: return null
val declaration = (targetDescriptor.source as? PsiSourceElement)?.psi as? KtProperty ?: return null
if (ConstModifierChecker.canBeConst(declaration, declaration, targetDescriptor)) {
return AddConstModifierFix(declaration)
}
return null
}
}
fun replaceReferencesToGetterByReferenceToField(property: KtProperty) {
val project = property.project
val getter = LightClassUtil.getLightClassPropertyMethods(property).getter ?: return
val javaScope = GlobalSearchScope.getScopeRestrictedByFileTypes(project.allScope(), JavaFileType.INSTANCE)
val backingField = LightClassUtil.getLightClassPropertyMethods(property).backingField
if (backingField != null) {
val getterUsages = ReferencesSearch.search(getter, javaScope).findAll()
val factory = PsiElementFactory.getInstance(project)
val fieldFQName = backingField.containingClass!!.qualifiedName + "." + backingField.name
runWriteAction {
getterUsages.forEach {
val call = it.element.getNonStrictParentOfType<PsiMethodCallExpression>()
if (call != null && it.element == call.methodExpression) {
val fieldRef = factory.createExpressionFromText(fieldFQName, it.element)
call.replace(fieldRef)
}
}
}
}
}
| apache-2.0 | d50c2dbe0a47708c9880ee0c9f09d047 | 44.584746 | 158 | 0.738613 | 5.207164 | false | false | false | false |
lsmaira/gradle | buildSrc/subprojects/buildquality/src/main/kotlin/org/gradle/gradlebuild/buildquality/incubation/IncubatingApiReportTask.kt | 1 | 9055 | package org.gradle.gradlebuild.buildquality.incubation
import com.github.javaparser.JavaParser
import com.github.javaparser.ast.CompilationUnit
import com.github.javaparser.ast.Node
import com.github.javaparser.ast.body.AnnotationDeclaration
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
import com.github.javaparser.ast.body.EnumDeclaration
import com.github.javaparser.ast.body.MethodDeclaration
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations
import com.github.javaparser.ast.nodeTypes.NodeWithJavadoc
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName
import com.github.javaparser.javadoc.description.JavadocSnippet
import com.github.javaparser.symbolsolver.JavaSymbolSolver
import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver
import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver
import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver
import org.gradle.api.DefaultTask
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.workers.IsolationMode
import org.gradle.workers.WorkerExecutor
import java.io.File
import javax.inject.Inject
@CacheableTask
open class IncubatingApiReportTask
@Inject constructor(private val workerExecutor: WorkerExecutor) : DefaultTask() {
@InputFile
@PathSensitive(PathSensitivity.RELATIVE)
val versionFile: RegularFileProperty = project.objects.fileProperty()
@InputFile
@PathSensitive(PathSensitivity.RELATIVE)
val releasedVersionsFile: RegularFileProperty = project.objects.fileProperty()
@Input
val title: Property<String> = project.objects.property(String::class.java).also {
it.set(project.provider { project.name })
}
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
val sources: ConfigurableFileCollection = project.files()
@OutputFile
val htmlReportFile: RegularFileProperty = project.objects.fileProperty().also {
it.set(project.layout.buildDirectory.file("reports/incubating.html"))
}
@OutputFile
val textReportFile: RegularFileProperty = project.objects.fileProperty().also {
it.set(project.layout.buildDirectory.file("reports/incubating.txt"))
}
@TaskAction
fun analyze() = workerExecutor.submit(Analyzer::class.java) {
isolationMode = IsolationMode.CLASSLOADER
params(versionFile.asFile.get(), sources.files, htmlReportFile.asFile.get(), textReportFile.asFile.get(), title.get(), releasedVersionsFile.asFile.get())
}
}
open
class Analyzer @Inject constructor(
private val versionFile: File,
private val srcDirs: Set<File>,
private val htmlReportFile: File,
private val textReportFile: File,
private val title: String,
private val releasedVersionsFile: File
) : Runnable {
override
fun run() {
val versionToIncubating = mutableMapOf<String, MutableSet<String>>()
srcDirs.forEach { srcDir ->
if (srcDir.exists()) {
val solver = JavaSymbolSolver(CombinedTypeSolver(JavaParserTypeSolver(srcDir), ReflectionTypeSolver()))
srcDir.walkTopDown().forEach {
if (it.name.endsWith(".java")) {
try {
parseJavaFile(it, versionToIncubating, solver)
} catch (e: Exception) {
println("Unable to parse $it: ${e.message}")
}
}
}
}
}
generateTextReport(versionToIncubating)
generateHtmlReport(versionToIncubating)
}
private
fun parseJavaFile(file: File, versionToIncubating: MutableMap<String, MutableSet<String>>, solver: JavaSymbolSolver) =
JavaParser.parse(file).run {
solver.inject(this)
findAll(Node::class.java)
.filter {
it is NodeWithAnnotations<*> &&
it.annotations.any { it.nameAsString == "Incubating" }
}.map {
val node = it as NodeWithAnnotations<*>
val version = findVersionFromJavadoc(node)
?: "Not found"
Pair(version, nodeName(it, this, file))
}.forEach {
versionToIncubating.getOrPut(it.first) {
mutableSetOf()
}.add(it.second)
}
}
private
fun findVersionFromJavadoc(node: NodeWithAnnotations<*>): String? = if (node is NodeWithJavadoc<*>) {
node.javadoc.map {
it.blockTags.find {
it.tagName == "since"
}?.content?.elements?.find {
it is JavadocSnippet
}?.toText()
}.orElse(null)
} else {
null
}
private
fun nodeName(it: Node?, unit: CompilationUnit, file: File) = when (it) {
is EnumDeclaration -> tryResolve({ it.resolve().qualifiedName }) { inferClassName(unit) }
is ClassOrInterfaceDeclaration -> tryResolve({ it.resolve().qualifiedName }) { inferClassName(unit) }
is MethodDeclaration -> tryResolve({ it.resolve().qualifiedSignature }) { inferClassName(unit) }
is AnnotationDeclaration -> tryResolve({ it.resolve().qualifiedName }) { inferClassName(unit) }
is NodeWithSimpleName<*> -> it.nameAsString
else -> unit.primaryTypeName.orElse(file.name)
}
private
fun inferClassName(unit: CompilationUnit) = "${unit.packageDeclaration.map { it.nameAsString }.orElse("")}.${unit.primaryTypeName.orElse("")}"
private
inline fun tryResolve(resolver: () -> String, or: () -> String) = try {
resolver()
} catch (e: Throwable) {
or()
}
private
fun generateHtmlReport(versionToIncubating: Map<String, Set<String>>) {
htmlReportFile.parentFile.mkdirs()
htmlReportFile.printWriter(Charsets.UTF_8).use { writer ->
writer.println("""<html lang="en">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Incubating APIs for $title</title>
<link xmlns:xslthl="http://xslthl.sf.net" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,400i,700">
<meta xmlns:xslthl="http://xslthl.sf.net" content="width=device-width, initial-scale=1" name="viewport">
<link xmlns:xslthl="http://xslthl.sf.net" type="text/css" rel="stylesheet" href="https://docs.gradle.org/current/userguide/base.css">
</head>
<body>
<h1>Incubating APIs for $title</h1>
""")
val versions = versionsDates()
versionToIncubating.toSortedMap().forEach {
writer.println("<a name=\"sec_${it.key}\"></a>")
writer.println("<h2>Incubating since ${it.key} (${versions.get(it.key)?.run { "released on $this" }
?: "unreleased"})</h2>")
writer.println("<ul>")
it.value.sorted().forEach {
writer.println(" <li>${it.escape()}</li>")
}
writer.println("</ul>")
}
writer.println("</body></html>")
}
}
private
fun generateTextReport(versionToIncubating: Map<String, Set<String>>) {
textReportFile.parentFile.mkdirs()
textReportFile.printWriter(Charsets.UTF_8).use { writer ->
val versions = versionsDates()
versionToIncubating.toSortedMap().forEach {
val version = it.key
val releaseDate = versions.get(it.key) ?: "unreleased"
it.value.sorted().forEach {
writer.println("$version;$releaseDate;$it")
}
}
}
}
private
fun versionsDates(): Map<String, String> {
val versions = mutableMapOf<String, String>()
var version: String? = null
releasedVersionsFile.forEachLine(Charsets.UTF_8) {
val line = it.trim()
if (line.startsWith("\"version\"")) {
version = line.substring(line.indexOf("\"", 11) + 1, line.lastIndexOf("\""))
}
if (line.startsWith("\"buildTime\"")) {
var date = line.substring(line.indexOf("\"", 12) + 1, line.lastIndexOf("\""))
date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8)
versions.put(version!!, date)
}
}
return versions
}
private
fun String.escape() = replace("<", "<").replace(">", ">")
}
| apache-2.0 | 6fe599820bebe1ba325ee86df8d5d1b1 | 38.889868 | 161 | 0.635229 | 4.612837 | false | false | false | false |
kivensolo/UiUsingListView | app/src/main/java/com/kingz/ipcdemo/BookShopService.kt | 1 | 3125 | package com.kingz.ipcdemo
import android.app.Service
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import com.zeke.kangaroo.utils.ZLog
import java.util.*
/**
* @author zeke.wang
* @date 2020/3/20
* @maintainer zeke.wang
* @copyright 2020 www.xgimi.com Inc. All rights reserved.
* @desc:
*/
class BookShopService : Service() {
val TAG = BookShopService::class.java.simpleName
private val mBooks: MutableList<Book> = ArrayList()
private var mICallback: ICallback? = null
override fun onCreate() {
super.onCreate()
initBookShop()
}
private fun initBookShop() {
val book = Book()
book.name = "Android开发艺术探索"
book.price = 28
mBooks.add(book)
}
//由AIDL文件生成的BookManager
private val mServiceStub = object : IBookManager.Stub() {
override fun deleteBook(book: Book?, callback: ICallback?) {
mICallback = callback
notifySucess("delete sucess.")
}
override fun addBookInout(book: Book?) {}
override fun setBookName(book: Book?, name: String?) {
}
override fun addBookOut(book: Book?) {}
override fun getBookCount(): Int {
return books.size
}
override fun setBookPrice(book: Book?, price: Int) {}
override fun addBookIn(book: Book?) {}
override fun addBook(book: Book?) {
synchronized (this) {
book?:Book()
//尝试修改book的参数
//观察其到客户端的反馈
book?.price = 2333
if (!mBooks.contains(book)) {
if (book != null) {
mBooks.add(book)
}
}
//打印mBooks列表,观察客户端传过来的值
ZLog.e(TAG, "invoking addBooks() method , now the list is : $mBooks")
}
}
override fun getBooks(): MutableList<Book> {
synchronized(this) {
ZLog.d(TAG, "invoking getBooks() method , now the list is : $mBooks")
return mBooks
}
}
}
private fun notifySucess(msg: String) {
mICallback?.onSuccess(msg)
}
/**
* 客户端调用 bindService(serviceIntent, conn, BIND_AUTO_CREATE)
* bind成功后触发回调.
* @param intent 启动Service的intent
* @return
* Null : oBind返回值是null的情况下, 生命周期为:
* onCreate() --> onBind()
* Local Binder Object(本地Binder对象), 生命周期为:
* onCreate() ----> onBind() ----> onServiceConnected()
*
* 客户端调用多次bindService, 以上生命周期都不会被多次调用。
*/
override fun onBind(intent: Intent): IBinder? {
ZLog.d(TAG, "on bind,intent = $intent")
return mServiceStub
}
override fun unbindService(conn: ServiceConnection?) {
super.unbindService(conn)
}
override fun onDestroy() {
super.onDestroy()
}
}
| gpl-2.0 | ef6505a7bacf9dd963387a9636791a53 | 25.724771 | 85 | 0.5678 | 4.045833 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/main/java/org/ethereum/crypto/MGF1BytesGeneratorExt.kt | 1 | 3655 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* 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 org.ethereum.crypto
import org.spongycastle.crypto.DataLengthException
import org.spongycastle.crypto.DerivationFunction
import org.spongycastle.crypto.DerivationParameters
import org.spongycastle.crypto.Digest
import org.spongycastle.crypto.params.MGFParameters
/**
* This class is borrowed from spongycastle project
* The only change made is addition of 'counterStart' parameter to
* conform to Crypto++ capabilities
*/
internal class MGF1BytesGeneratorExt(val digest: Digest, private val counterStart: Int) : DerivationFunction {
private val hLen: Int = digest.digestSize
private var seed: ByteArray? = null
override fun init(param: DerivationParameters) {
if (param !is MGFParameters) {
throw IllegalArgumentException("MGF parameters required for MGF1Generator")
} else {
this.seed = param.seed
}
}
private fun ItoOSP(i: Int, sp: ByteArray) {
sp[0] = i.ushr(24).toByte()
sp[1] = i.ushr(16).toByte()
sp[2] = i.ushr(8).toByte()
sp[3] = i.toByte()
}
@Throws(DataLengthException::class, IllegalArgumentException::class)
override fun generateBytes(out: ByteArray, outOff: Int, len: Int): Int {
if (out.size - len < outOff) {
throw DataLengthException("output buffer too small")
} else {
val hashBuf = ByteArray(this.hLen)
val C = ByteArray(4)
var counter = 0
var hashCounter = counterStart
this.digest.reset()
if (len > this.hLen) {
do {
this.ItoOSP(hashCounter++, C)
this.digest.update(this.seed, 0, this.seed!!.size)
this.digest.update(C, 0, C.size)
this.digest.doFinal(hashBuf, 0)
System.arraycopy(hashBuf, 0, out, outOff + counter * this.hLen, this.hLen)
++counter
} while (counter < len / this.hLen)
}
if (counter * this.hLen < len) {
this.ItoOSP(hashCounter, C)
this.digest.update(this.seed, 0, this.seed!!.size)
this.digest.update(C, 0, C.size)
this.digest.doFinal(hashBuf, 0)
System.arraycopy(hashBuf, 0, out, outOff + counter * this.hLen, len - counter * this.hLen)
}
return len
}
}
}
| mit | 8761ab1ed14c6100224c2d6ad73dfcfd | 39.164835 | 110 | 0.646238 | 4.205984 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddExclExclCallFix.kt | 4 | 6770 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Errors.UNSAFE_CALL
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceiverValue
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.util.isValidOperator
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun getAddExclExclCallFix(element: PsiElement?, checkImplicitReceivers: Boolean = false): AddExclExclCallFix? {
fun KtExpression?.asFix(implicitReceiver: Boolean = false) = this?.let { AddExclExclCallFix(it, implicitReceiver) }
val psiElement = element ?: return null
if ((psiElement as? KtExpression).isNullExpression()) {
return null
}
if (psiElement is LeafPsiElement && psiElement.elementType == KtTokens.DOT) {
return (psiElement.prevSibling as? KtExpression).asFix()
}
return when (psiElement) {
is KtArrayAccessExpression -> psiElement.asFix()
is KtOperationReferenceExpression -> {
when (val parent = psiElement.parent) {
is KtUnaryExpression -> parent.baseExpression.asFix()
is KtBinaryExpression -> {
val receiver = if (KtPsiUtil.isInOrNotInOperation(parent)) parent.right else parent.left
receiver.asFix()
}
else -> null
}
}
is KtExpression -> {
val parent = psiElement.parent
val context = psiElement.analyze()
if (checkImplicitReceivers && psiElement.getResolvedCall(context)?.getImplicitReceiverValue() is ExtensionReceiver) {
val expressionToReplace = parent as? KtCallExpression ?: parent as? KtCallableReferenceExpression ?: psiElement
expressionToReplace.asFix(implicitReceiver = true)
} else {
val targetElement = parent.safeAs<KtCallableReferenceExpression>()?.receiverExpression ?: psiElement
context[BindingContext.EXPRESSION_TYPE_INFO, targetElement]?.let {
val type = it.type
val dataFlowValueFactory = targetElement.getResolutionFacade().dataFlowValueFactory
if (type != null) {
val nullability = it.dataFlowInfo.getStableNullability(
dataFlowValueFactory.createDataFlowValue(targetElement, type, context, targetElement.findModuleDescriptor())
)
if (!nullability.canBeNonNull()) return null
}
}
targetElement.asFix()
}
}
else -> null
}
}
object UnsafeCallExclExclFixFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val psiElement = diagnostic.psiElement
if (diagnostic.factory == UNSAFE_CALL && psiElement is KtArrayAccessExpression) {
psiElement.arrayExpression?.let { return getAddExclExclCallFix(it) }
}
return getAddExclExclCallFix(psiElement, checkImplicitReceivers = true)
}
}
object SmartCastImpossibleExclExclFixFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
if (diagnostic.factory !== Errors.SMARTCAST_IMPOSSIBLE) return null
val element = diagnostic.psiElement as? KtExpression ?: return null
val analyze = element.analyze(BodyResolveMode.PARTIAL)
val type = analyze.getType(element)
if (type == null || !TypeUtils.isNullableType(type)) return null
val diagnosticWithParameters = Errors.SMARTCAST_IMPOSSIBLE.cast(diagnostic)
val expectedType = diagnosticWithParameters.a
if (TypeUtils.isNullableType(expectedType)) return null
val nullableExpectedType = TypeUtils.makeNullable(expectedType)
if (!type.isSubtypeOf(nullableExpectedType)) return null
return getAddExclExclCallFix(element)
}
}
object MissingIteratorExclExclFixFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = diagnostic.psiElement as? KtExpression ?: return null
val analyze = element.analyze(BodyResolveMode.PARTIAL)
val type = analyze.getType(element)
if (type == null || !TypeUtils.isNullableType(type)) return null
val descriptor = type.constructor.declarationDescriptor
fun hasIteratorFunction(classifierDescriptor: ClassifierDescriptor?): Boolean {
if (classifierDescriptor !is ClassDescriptor) return false
val memberScope = classifierDescriptor.unsubstitutedMemberScope
val functions = memberScope.getContributedFunctions(OperatorNameConventions.ITERATOR, NoLookupLocation.FROM_IDE)
return functions.any { it.isValidOperator() }
}
when (descriptor) {
is TypeParameterDescriptor -> {
if (descriptor.upperBounds.none { hasIteratorFunction(it.constructor.declarationDescriptor) }) return null
}
is ClassifierDescriptor -> {
if (!hasIteratorFunction(descriptor)) return null
}
else -> return null
}
return getAddExclExclCallFix(element)
}
} | apache-2.0 | 0d99fd3f84b3f0b1ba7eb7aa83891dcf | 46.34965 | 158 | 0.712408 | 5.636969 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceToStringWithStringTemplateInspection.kt | 1 | 1777 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.dropCurlyBracketsIfPossible
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.intentions.isToString
import org.jetbrains.kotlin.psi.*
class ReplaceToStringWithStringTemplateInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
) {
override fun isApplicable(element: KtDotQualifiedExpression): Boolean {
if (element.receiverExpression !is KtReferenceExpression) return false
if (element.parent is KtBlockStringTemplateEntry) return false
return element.isToString()
}
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val variable = element.receiverExpression.text
val replaced = element.replace(KtPsiFactory(project).createExpression("\"\${$variable}\""))
val blockStringTemplateEntry = (replaced as? KtStringTemplateExpression)?.entries?.firstOrNull() as? KtBlockStringTemplateEntry
blockStringTemplateEntry?.dropCurlyBracketsIfPossible()
}
override fun inspectionText(element: KtDotQualifiedExpression) =
KotlinBundle.message("inspection.replace.to.string.with.string.template.display.name")
override val defaultFixText get() = KotlinBundle.message("replace.tostring.with.string.template")
} | apache-2.0 | 3a0e7dc3d3d65a07cedffe7b198d5b00 | 52.878788 | 158 | 0.796286 | 5.272997 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/components/BasicOptionButtonUI.kt | 2 | 16097 | // 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.ui.components
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager.getApplication
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.OptionAction
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.ui.popup.ListPopup
import com.intellij.openapi.util.Condition
import com.intellij.ui.ScreenUtil
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.components.JBOptionButton.Companion.PROP_OPTIONS
import com.intellij.ui.components.JBOptionButton.Companion.PROP_OPTION_TOOLTIP
import com.intellij.ui.popup.ActionPopupStep
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.ui.popup.list.PopupListElementRenderer
import com.intellij.util.ui.AbstractLayoutManager
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.scale
import java.awt.*
import java.awt.event.*
import java.beans.PropertyChangeListener
import java.util.function.Supplier
import javax.swing.*
import javax.swing.AbstractButton.MNEMONIC_CHANGED_PROPERTY
import javax.swing.AbstractButton.TEXT_CHANGED_PROPERTY
import javax.swing.JComponent.TOOL_TIP_TEXT_KEY
import javax.swing.SwingUtilities.replaceUIActionMap
import javax.swing.SwingUtilities.replaceUIInputMap
import javax.swing.event.ChangeListener
open class BasicOptionButtonUI : OptionButtonUI() {
private var _optionButton: JBOptionButton? = null
private var _mainButton: JButton? = null
private var _arrowButton: JButton? = null
protected val optionButton: JBOptionButton get() = _optionButton!!
protected val mainButton: JButton get() = _mainButton!!
protected val arrowButton: JButton get() = _arrowButton!!
protected var popup: ListPopup? = null
private var showPopupAction: AnAction? = null
protected var isPopupShowing: Boolean = false
protected var propertyChangeListener: PropertyChangeListener? = null
protected var changeListener: ChangeListener? = null
protected var focusListener: FocusListener? = null
private var arrowButtonActionListener: ActionListener? = null
private var arrowButtonMouseListener: MouseListener? = null
protected val isSimpleButton: Boolean get() = optionButton.isSimpleButton
override fun installUI(c: JComponent) {
_optionButton = c as JBOptionButton
installPopup()
installButtons()
installListeners()
installKeyboardActions()
}
override fun uninstallUI(c: JComponent) {
uninstallKeyboardActions()
uninstallListeners()
uninstallButtons()
uninstallPopup()
_optionButton = null
}
override fun getPreferredSize(c: JComponent): Dimension {
if (!arrowButton.isVisible) return mainButton.preferredSize
return Dimension(
mainButton.preferredSize.width + arrowButton.preferredSize.width,
maxOf(mainButton.preferredSize.height, arrowButton.preferredSize.height)
)
}
protected open fun installPopup() {
showPopupAction = DumbAwareAction.create { showPopup() }
showPopupAction?.registerCustomShortcutSet(CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)), optionButton)
}
protected open fun uninstallPopup() {
showPopupAction?.unregisterCustomShortcutSet(optionButton)
showPopupAction = null
popup?.let(Disposable::dispose)
popup = null
}
protected open fun installButtons() {
_mainButton = createMainButton()
optionButton.add(mainButton)
configureMainButton()
_arrowButton = createArrowButton()
optionButton.add(arrowButton)
configureArrowButton()
configureOptionButton()
updateTooltip()
}
protected open fun uninstallButtons() {
unconfigureMainButton()
unconfigureArrowButton()
unconfigureOptionButton()
_mainButton = null
_arrowButton = null
}
protected open fun configureOptionButton() {
optionButton.layout = createLayoutManager()
}
protected open fun unconfigureOptionButton() {
optionButton.layout = null
optionButton.removeAll()
}
protected open fun createMainButton(): JButton = MainButton()
protected open fun configureMainButton() {
mainButton.isFocusable = false
mainButton.action = optionButton.action
}
protected open fun unconfigureMainButton() {
mainButton.action = null
}
protected open fun createArrowButton(): JButton = ArrowButton().apply { icon = AllIcons.General.ArrowDown }
protected open fun configureArrowButton() {
arrowButton.isFocusable = false
arrowButton.preferredSize = arrowButtonPreferredSize
arrowButton.isVisible = !isSimpleButton
arrowButton.isEnabled = optionButton.isEnabled
arrowButtonActionListener = createArrowButtonActionListener()?.apply(arrowButton::addActionListener)
arrowButtonMouseListener = createArrowButtonMouseListener()?.apply(arrowButton::addMouseListener)
}
protected open fun unconfigureArrowButton() {
arrowButton.removeActionListener(arrowButtonActionListener)
arrowButton.removeMouseListener(arrowButtonMouseListener)
arrowButtonActionListener = null
arrowButtonMouseListener = null
}
protected open val arrowButtonPreferredSize: Dimension get() = JBUI.size(16)
protected open fun createLayoutManager(): LayoutManager = OptionButtonLayout()
protected open fun installListeners() {
propertyChangeListener = createPropertyChangeListener()?.apply(optionButton::addPropertyChangeListener)
changeListener = createChangeListener()?.apply(optionButton::addChangeListener)
focusListener = createFocusListener()?.apply(optionButton::addFocusListener)
}
protected open fun uninstallListeners() {
optionButton.removePropertyChangeListener(propertyChangeListener)
optionButton.removeChangeListener(changeListener)
optionButton.removeFocusListener(focusListener)
propertyChangeListener = null
changeListener = null
focusListener = null
}
protected open fun createPropertyChangeListener(): PropertyChangeListener? = PropertyChangeListener {
when (it.propertyName) {
"action" -> mainButton.action = optionButton.action
TEXT_CHANGED_PROPERTY -> mainButton.text = optionButton.text
MNEMONIC_CHANGED_PROPERTY -> mainButton.mnemonic = optionButton.mnemonic
TOOL_TIP_TEXT_KEY, PROP_OPTION_TOOLTIP -> updateTooltip()
PROP_OPTIONS -> {
closePopup()
updateTooltip()
updateOptions()
}
}
}
protected open fun createChangeListener(): ChangeListener? = ChangeListener {
arrowButton.isEnabled = optionButton.isEnabled // mainButton is updated from corresponding Action instance
}
protected open fun createFocusListener(): FocusListener? = object : FocusAdapter() {
override fun focusLost(e: FocusEvent?) {
repaint()
}
override fun focusGained(e: FocusEvent?) {
repaint()
}
private fun repaint() {
mainButton.repaint()
arrowButton.repaint()
}
}
protected open fun createArrowButtonActionListener(): ActionListener? = ActionListener { togglePopup() }
protected open fun createArrowButtonMouseListener(): MouseListener? = object : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
if (SwingUtilities.isLeftMouseButton(e)) {
e.consume()
arrowButton.doClick()
}
}
}
protected open fun installKeyboardActions() {
replaceUIActionMap(optionButton, mainButton.actionMap)
replaceUIInputMap(optionButton, JComponent.WHEN_FOCUSED, mainButton.inputMap)
}
protected open fun uninstallKeyboardActions() {
replaceUIActionMap(optionButton, null)
replaceUIInputMap(optionButton, JComponent.WHEN_FOCUSED, null)
}
override fun showPopup(toSelect: Action?, ensureSelection: Boolean) {
if (!isSimpleButton) {
isPopupShowing = true
popup = createPopup(toSelect, ensureSelection).apply {
// use invokeLater() to update flag "after" popup is auto-closed - to ensure correct togglePopup() behaviour on arrow button press
setFinalRunnable { getApplication().invokeLater { isPopupShowing = false } }
addListener(object : JBPopupListener {
override fun beforeShown(event: LightweightWindowEvent) {
val popup = event.asPopup()
val screen = ScreenUtil.getScreenRectangle(optionButton.locationOnScreen)
val above = screen.height < popup.size.height + showPopupBelowLocation.screenPoint.y
if (above) {
val point = Point(showPopupAboveLocation.screenPoint)
point.translate(0, -popup.size.height)
popup.setLocation(point)
}
optionButton.popupHandler?.invoke(popup)
}
override fun onClosed(event: LightweightWindowEvent) {
// final runnable is not called when some action is invoked - so we handle this case here separately
if (event.isOk) {
isPopupShowing = false
}
}
})
show(showPopupBelowLocation)
}
}
}
override fun closePopup() {
popup?.cancel()
}
override fun togglePopup() {
if (isPopupShowing) {
closePopup()
}
else {
showPopup()
}
}
protected open val showPopupXOffset: Int get() = 0
protected open val showPopupBelowLocation: RelativePoint
get() = RelativePoint(optionButton, Point(showPopupXOffset, optionButton.height + scale(optionButton.showPopupYOffset)))
protected open val showPopupAboveLocation: RelativePoint
get() = RelativePoint(optionButton, Point(showPopupXOffset, -scale(optionButton.showPopupYOffset)))
protected open fun createPopup(toSelect: Action?, ensureSelection: Boolean): ListPopup {
val (actionGroup, mapping) = createActionMapping()
val dataContext = createActionDataContext()
val place = ActionPlaces.getPopupPlace(optionButton.getClientProperty(JBOptionButton.PLACE) as? String)
val actionItems = ActionPopupStep.createActionItems(actionGroup, dataContext, false, false, true, true, place, null)
val defaultSelection = if (toSelect != null) Condition<AnAction> { mapping[it] == toSelect } else null
return OptionButtonPopup(OptionButtonPopupStep(actionItems, place, defaultSelection), dataContext, toSelect != null || ensureSelection)
}
protected open fun createActionDataContext(): DataContext = DataManager.getInstance().getDataContext(optionButton)
protected open fun createActionMapping(): Pair<ActionGroup, Map<AnAction, Action>> {
val mapping = optionButton.options?.associateBy(this@BasicOptionButtonUI::createAnAction) ?: emptyMap()
val actionGroup = DefaultActionGroup().apply {
mapping.keys.forEachIndexed { index, it ->
if (index > 0 && optionButton.addSeparator) addSeparator()
add(it)
}
}
return Pair(actionGroup, mapping)
}
protected open fun createAnAction(action: Action): AnAction = action.getValue(OptionAction.AN_ACTION) as? AnAction ?: ActionDelegate(action)
private fun updateTooltip() {
val toolTip = if (!isSimpleButton) optionButton.optionTooltipText else optionButton.toolTipText
mainButton.toolTipText = toolTip
arrowButton.toolTipText = toolTip
}
protected open fun updateOptions() {
arrowButton.isVisible = !isSimpleButton
}
open inner class BaseButton : JButton() {
override fun hasFocus(): Boolean = optionButton.hasFocus()
override fun isDefaultButton(): Boolean = optionButton.isDefaultButton
override fun getBackground(): Color? = optionButton.background
override fun paint(g: Graphics): Unit = if (isSimpleButton) super.paint(g) else cloneAndPaint(g) { paintNotSimple(it) }
open fun paintNotSimple(g: Graphics2D): Unit = super.paint(g)
override fun paintBorder(g: Graphics): Unit = if (isSimpleButton) super.paintBorder(g) else cloneAndPaint(g) { paintBorderNotSimple(it) }
open fun paintBorderNotSimple(g: Graphics2D): Unit = super.paintBorder(g)
}
open inner class MainButton : BaseButton()
open inner class ArrowButton : BaseButton()
open inner class OptionButtonLayout : AbstractLayoutManager() {
override fun layoutContainer(parent: Container) {
val mainButtonWidth = optionButton.width - if (arrowButton.isVisible) arrowButton.preferredSize.width else 0
mainButton.bounds = Rectangle(0, 0, mainButtonWidth, optionButton.height)
arrowButton.bounds = Rectangle(mainButtonWidth, 0, arrowButton.preferredSize.width, optionButton.height)
}
override fun preferredLayoutSize(parent: Container): Dimension = parent.preferredSize
override fun minimumLayoutSize(parent: Container): Dimension = parent.minimumSize
}
open inner class OptionButtonPopup(step: ActionPopupStep,
dataContext: DataContext,
private val ensureSelection: Boolean)
: PopupFactoryImpl.ActionGroupPopup(null, step, null, dataContext, -1) {
init {
list.background = background
}
override fun afterShow() {
if (ensureSelection) super.afterShow()
}
override fun afterShowSync() {
if (optionButton.selectFirstItem) {
super.afterShowSync()
}
else {
list.clearSelection()
}
}
protected val background: Color? get() = optionButton.popupBackgroundColor ?: mainButton.background
override fun createContent(): JComponent = super.createContent().also {
list.clearSelection() // prevents first action selection if all actions are disabled
list.border = JBUI.Borders.empty(2, 0)
}
override fun getListElementRenderer(): PopupListElementRenderer<Any> = object : PopupListElementRenderer<Any>(this) {
override fun getBackground() = [email protected]
override fun createSeparator() = super.createSeparator().apply { border = JBUI.Borders.empty(2, 6) }
override fun getDefaultItemComponentBorder() = JBUI.Borders.empty(6, 8)
}
}
open inner class OptionButtonPopupStep(actions: List<PopupFactoryImpl.ActionItem>, place: String, private val defaultSelection: Condition<AnAction>?)
: ActionPopupStep(actions, null,
Supplier<DataContext> { DataManager.getInstance().getDataContext(optionButton) },
place, true, defaultSelection, false, true, null) {
// if there is no default selection condition - -1 should be returned, this way first enabled action should be selected by
// OptionButtonPopup.afterShow() (if corresponding ensureSelection parameter is true)
override fun getDefaultOptionIndex(): Int = defaultSelection?.let { super.getDefaultOptionIndex() } ?: -1
override fun isSpeedSearchEnabled(): Boolean = false
}
open inner class ActionDelegate(val action: Action) : DumbAwareAction() {
init {
isEnabledInModalContext = true
templatePresentation.text = (action.getValue(Action.NAME) as? String).orEmpty()
}
override fun update(event: AnActionEvent) {
event.presentation.isEnabled = action.isEnabled
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT;
}
override fun actionPerformed(event: AnActionEvent) {
action.actionPerformed(ActionEvent(optionButton, ActionEvent.ACTION_PERFORMED, null))
}
}
companion object {
@Suppress("UNUSED_PARAMETER")
@JvmStatic
fun createUI(c: JComponent): BasicOptionButtonUI = BasicOptionButtonUI()
fun paintBackground(g: Graphics, c: JComponent) {
if (c.isOpaque) {
g.color = c.background
g.fillRect(0, 0, c.width, c.height)
}
}
fun cloneAndPaint(g: Graphics, block: (Graphics2D) -> Unit) {
val g2 = g.create() as Graphics2D
try {
block(g2)
}
finally {
g2.dispose()
}
}
}
} | apache-2.0 | 41f780f11da64959aa9316761098511b | 36.177829 | 151 | 0.732621 | 5.226299 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.