repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
inorichi/tachiyomi-extensions | src/en/timelessleaf/src/eu/kanade/tachiyomi/extension/en/timelessleaf/TimelessLeaf.kt | 1 | 5834 | package eu.kanade.tachiyomi.extension.en.timelessleaf
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import java.text.SimpleDateFormat
import java.util.Locale
/**
* @author Aria Moradi <[email protected]>
*/
class TimelessLeaf : HttpSource() {
override val name = "TimelessLeaf"
override val baseUrl = "https://timelessleaf.com"
override val lang = "en"
override val supportsLatest: Boolean = false
private val dateFormat: SimpleDateFormat = SimpleDateFormat("yyyy/MM/dd", Locale.US)
// popular manga
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/manga/")
}
override fun popularMangaParse(response: Response): MangasPage {
val document = response.asJsoup()
// scraping post links
val articleLinks = document.select(".site-main article a")
// scraping menus, ignore the ones that are not manga entries
val pagesWeDontWant = listOf(
"dropped",
"more manga",
"recent"
).joinToString(prefix = "(?i)", separator = "|").toRegex()
// all mangas are in sub menus, go straight for that to deal with less menu items
val menuLinks = document.select(".sub-menu a").filterNot { element ->
element.text().toLowerCase(Locale.ROOT).contains(pagesWeDontWant)
}
// combine the two lists
val combinedLinks = articleLinks.map { el ->
Pair(el.text(), el.attr("href"))
}.toMutableList().apply {
val titleList = this.map { it.first }
menuLinks.forEach { el ->
val title = el.text()
// ignore duplicates
if (titleList.none { str -> str.startsWith(title, ignoreCase = true) })
add(Pair(title, el.attr("href")))
}
}.sortedBy { pair -> pair.first }
return MangasPage(
combinedLinks.map { p ->
SManga.create().apply {
title = p.first
setUrlWithoutDomain(p.second)
}
},
false
)
}
// manga details
override fun mangaDetailsParse(response: Response): SManga {
val document = response.asJsoup()
return SManga.create().apply {
// prefer srcset for higher res images, if not available use src
thumbnail_url = document.select(".site-main img").attr("srcset").substringBefore(" ")
if (thumbnail_url == "")
thumbnail_url = document.select(".site-main img").attr("abs:src")
description = document.select(".page-content p:not(:has(a)):not(:contains(chapter)):not(:has(strong))")
.text().substringAfter("Summary: ")
}
}
// chapter list
override fun chapterListParse(response: Response): List<SChapter> {
// some chapters are not hosted at TimelessLeaf itself, so can't do anything about them -> ignore
val hostedHere = response.asJsoup().select(".site-main a").filter { el ->
el.attr("href").startsWith(baseUrl)
}
return hostedHere.map { el ->
SChapter.create().apply {
setUrlWithoutDomain(el.attr("href"))
// taking timeStamp from url
date_upload = parseChapterDate(el.attr("href").substringAfter("com/").substringAfter("php/"))
name = el.text()
}
}.asReversed()
}
private fun parseChapterDate(date: String): Long {
return try {
dateFormat.parse(date)?.time ?: 0
} catch (_: Exception) {
0L
}
}
private fun parseDate(date: String): Long {
return SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH).parse(date)?.time ?: 0L
}
// page list
override fun pageListParse(response: Response): List<Page> {
return response.asJsoup()
.let { document ->
document.select(".site-main article .gallery-item img")
.let { if (it.isNullOrEmpty()) document.select("div.entry-content img") else it }
}
.mapIndexed { index, el ->
Page(index, "", el.attr("abs:src"))
}
}
// search manga, implementing a local search
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = popularMangaRequest(1)
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return client.newCall(searchMangaRequest(page, query, filters))
.asObservableSuccess()
.map { response ->
val allManga = popularMangaParse(response)
val filtered = allManga.mangas.filter { manga -> manga.title.contains(query, ignoreCase = true) }
MangasPage(filtered, false)
}
}
override fun searchMangaParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used.")
override fun imageUrlParse(response: Response): String = throw UnsupportedOperationException("Not used.")
override fun latestUpdatesParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used.")
override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException("Not used.")
}
| apache-2.0 | f65b2b16363b54170a2aafca90963174 | 35.236025 | 118 | 0.619643 | 4.746949 | false | false | false | false |
JetBrains-Research/big | src/main/kotlin/org/jetbrains/bio/big/Bed.kt | 2 | 18393 | package org.jetbrains.bio.big
import com.google.common.base.MoreObjects
import com.google.common.base.Splitter
import com.google.common.collect.ComparisonChain
import com.google.common.primitives.Ints
import org.jetbrains.bio.bufferedReader
import java.awt.Color
import java.io.Closeable
import java.io.IOException
import java.nio.file.Path
import java.util.*
class BedFile(val path: Path) : Iterable<BedEntry>, Closeable {
private val reader = path.bufferedReader()
override fun iterator(): Iterator<BedEntry> {
return reader.lines().map { line ->
val chunks = line.split('\t', limit = 4)
BedEntry(chunks[0], chunks[1].toInt(), chunks[2].toInt(),
if (chunks.size == 3) "" else chunks[3])
}.iterator()
}
override fun close() {
reader.close()
}
companion object {
@Throws(IOException::class)
@JvmStatic fun read(path: Path) = BedFile(path)
}
}
/**
* A minimal representation of a BED file entry.
*
* The BED standard absolutely requires three fields: [chrom], [start] and [end]. The remaining line is
* stored in [rest]. It might or might not contain other, more optional BED fields, such as name, score or color.
* Use [unpack] to obtain an [ExtendedBedEntry] where these fields are properly parsed.
*/
data class BedEntry(
/** Chromosome name, e.g. `"chr9"`. */
val chrom: String,
/** 0-based start offset (inclusive). */
val start: Int,
/** 0-based end offset (exclusive). */
val end: Int,
/** Tab-separated string of additional BED values. */
val rest: String = ""): Comparable<BedEntry> {
override fun compareTo(other: BedEntry): Int = ComparisonChain.start()
.compare(chrom, other.chrom)
.compare(start, other.start)
.result()
/**
* Unpacks a basic bed3 [BedEntry] into a bedN+ [ExtendedBedEntry].
*
* Correctly parses the typed BED fields (such as score, color or blockSizes). Extra (non-standard) fields,
* if any (and if [parseExtraFields] is enabled) are stored in [ExtendedBedEntry.extraFields]
* property as a [String] array (null if no extra fields or [parseExtraFields] is disabled).
*
* @throws BedEntryUnpackException if this entry couldn't be parsed, either because there are too few fields
* or because the field values don't conform to the standard, e.g. score is not an integer number. The exception
* contains the BED entry and the index of the offending field.
*
* @param fieldsNumber Expected regular BED format fields number to parse (3..12)
* @param parseExtraFields Whether to parse or discard the BED+ format extra fields.
* @param delimiter Custom delimiter for malformed data
* @param omitEmptyStrings Treat several consecutive separators as one
*/
fun unpack(
fieldsNumber: Byte = 12,
parseExtraFields: Boolean = true,
delimiter: Char = '\t',
omitEmptyStrings: Boolean = false
): ExtendedBedEntry {
check(fieldsNumber in 3..12) { "Fields number expected in range 3..12, but was $fieldsNumber" }
val limit = if (parseExtraFields) 0 else fieldsNumber.toInt() - 3 + 1
val fields = when {
rest.isEmpty() -> emptyList<String>()
omitEmptyStrings -> Splitter.on(delimiter).trimResults().omitEmptyStrings().let {
if (limit == 0) it else it.limit(limit)
}.splitToList(rest)
else -> rest.split(delimiter, limit = limit)
}
if (fields.size < fieldsNumber - 3) {
throw BedEntryUnpackException(this, (fields.size + 3).toByte(), "field is missing")
}
val name = if (fieldsNumber >= 4) fields[0] else "."
val score = when {
fieldsNumber >= 5 -> {
val chunk = fields[1]
if (chunk == ".") {
0
} else {
chunk.toIntOrNull()
?: throw BedEntryUnpackException(this, 4, "score value $chunk is not an integer")
}
}
else -> 0
}
val strand = if (fieldsNumber >= 6) fields[2].firstOrNull() ?: '.' else '.'
val thickStart = when {
fieldsNumber >= 7 -> {
val chunk = fields[3]
if (chunk == ".") {
0
} else {
chunk.toIntOrNull()
?: throw BedEntryUnpackException(this, 6, "thickStart value $chunk is not an integer")
}
}
else -> 0
}
val thickEnd = when {
fieldsNumber >= 8 -> {
val chunk = fields[4]
if (chunk == ".") {
0
} else {
chunk.toIntOrNull()
?: throw BedEntryUnpackException(this, 7, "thickEnd value $chunk is not an integer")
}
}
else -> 0
}
val color = if (fieldsNumber >= 9) {
val value = fields[5]
if (value == "0" || value == ".") {
0
} else {
try {
val chunks = value.split(',', limit = 3)
Color(chunks[0].toInt(), chunks[1].toInt(), chunks[2].toInt()).rgb
} catch (e: Exception) {
throw BedEntryUnpackException(this, 8, "color value $value is not a comma-separated RGB", e)
}
}
} else {
0
}
val blockCount = when {
fieldsNumber >= 10 -> {
val chunk = fields[6]
if (chunk == ".") {
0
} else {
chunk.toIntOrNull()
?: throw BedEntryUnpackException(this, 9, "blockCount value $chunk is not an integer")
}
}
else -> 0
}
val blockSizes = if (fieldsNumber >= 11) {
val value = fields[7]
if (blockCount > 0) {
try {
value.splitToInts(blockCount)
} catch (e: Exception) {
throw BedEntryUnpackException(
this, 10,
"blockSizes value $value is not a comma-separated integer list of size $blockCount", e
)
}
} else null
} else null
val blockStarts = if (fieldsNumber >= 12) {
val value = fields[8]
if (blockCount > 0) {
try {
value.splitToInts(blockCount)
} catch (e: Exception) {
throw BedEntryUnpackException(
this, 11,
"blockStarts value $value is not a comma-separated integer list of size $blockCount", e
)
}
} else null
} else null
val actualExtraFieldsNumber = if (parseExtraFields) fields.size - fieldsNumber + 3 else 0
val extraFields = if (actualExtraFieldsNumber != 0) {
val parsedExtraFields = Array(actualExtraFieldsNumber) { i -> fields[fieldsNumber - 3 + i] }
// this specific check is intended to exactly replicate the original behaviour:
// extraFields are null if the bed entry tail is an empty string.
// see e.g. [BedEntryTest.unpackBedEmptyExtraFields2]
if (actualExtraFieldsNumber > 1 || parsedExtraFields[0] != "") parsedExtraFields else null
} else {
null
}
return ExtendedBedEntry(
chrom, start, end,
if (name == "") "." else name,
score, strand, thickStart, thickEnd, color,
blockCount, blockSizes, blockStarts, extraFields
)
}
@Deprecated(
"use parseExtraFields instead of extraFieldsNumber",
ReplaceWith("unpack(fieldsNumber, extraFieldsNumber != 0, delimiter, omitEmptyStrings)")
)
fun unpack(
fieldsNumber: Byte = 12,
extraFieldsNumber: Int?,
delimiter: Char = '\t',
omitEmptyStrings: Boolean = false
) = unpack(fieldsNumber, extraFieldsNumber != 0, delimiter, omitEmptyStrings)
private fun String.splitToInts(size: Int): IntArray {
val chunks = IntArray(size)
val s = Splitter.on(',').split(this).iterator()
var ptr = 0
while (ptr < size) {
chunks[ptr++] = s.next().toInt()
}
return chunks
}
}
/**
* An extended representation of a BED file entry.
*
* The BED standard allows 3 up to 12 regular fields (bed3 through bed12) and an arbitrary number
* of custom extra fields (bedN+K format). The first 12 properties represent the regular fields (default values
* are used to stand in for the missing data). [extraFields] property stores the extra fields as a [String] array.
*/
data class ExtendedBedEntry(
/** Chromosome name, e.g. `"chr9"`. */
val chrom: String,
/** 0-based start offset (inclusive). */
val start: Int,
/** 0-based end offset (exclusive). */
val end: Int,
/** Name of feature. */
val name: String = ".",
// UCSC defines score as an integer in range [0,1000], but almost everyone ignores the range.
/** Feature score */
val score: Int = 0,
/** + or – or . for unknown. */
val strand: Char = '.',
/** The starting position at which the feature is drawn thickly. **/
var thickStart: Int = 0,
/** The ending position at which the feature is drawn thickly. **/
var thickEnd: Int = 0,
/** The colour of entry in the form R,G,B (e.g. 255,0,0). **/
var itemRgb: Int = 0,
val blockCount: Int = 0,
val blockSizes: IntArray? = null,
val blockStarts: IntArray? = null,
/** Additional BED values. */
val extraFields: Array<String>? = null) {
init {
// Unfortunately MACS2 generates *.bed files with score > 1000
// let's ignore this check:
// require(score in 0..1000) {
// "Unexpected score: $score"
// }
require(strand == '+' || strand == '-' || strand == '.') {
"Unexpected strand value: $strand"
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ExtendedBedEntry) return false
if (chrom != other.chrom) return false
if (start != other.start) return false
if (end != other.end) return false
if (name != other.name) return false
if (score != other.score) return false
if (strand != other.strand) return false
if (thickStart != other.thickStart) return false
if (thickEnd != other.thickEnd) return false
if (itemRgb != other.itemRgb) return false
if (blockCount != other.blockCount) return false
if (!Arrays.equals(blockSizes, other.blockSizes)) return false
if (!Arrays.equals(blockStarts, other.blockStarts)) return false
if (!Arrays.equals(extraFields, other.extraFields)) return false
return true
}
override fun hashCode(): Int {
var result = chrom.hashCode()
result = 31 * result + start
result = 31 * result + end
result = 31 * result + name.hashCode()
result = 31 * result + score.hashCode()
result = 31 * result + strand.hashCode()
result = 31 * result + thickStart
result = 31 * result + thickEnd
result = 31 * result + itemRgb
result = 31 * result + blockCount
result = 31 * result + (blockSizes?.let { Arrays.hashCode(it) } ?: 0)
result = 31 * result + (blockStarts?.let { Arrays.hashCode(it) } ?: 0)
result = 31 * result + (extraFields?.let { Arrays.hashCode(it) } ?: 0)
return result
}
override fun toString() = MoreObjects.toStringHelper(this)
.add("chrom", chrom)
.add("start", start).add("end", end)
.add("name", name)
.add("score", score)
.add("strand", strand)
.add("thickStart", thickStart).add("thickEnd", thickEnd)
.add("itemRgb", itemRgb)
.add("blocks", when {
blockCount == 0 || blockSizes == null -> "[]"
blockStarts == null -> Arrays.toString(blockSizes)
else -> blockStarts.zip(blockSizes)
}).add("extra", extraFields?.joinToString("\t") ?: "")
.toString()
/**
* Convert to [BedEntry].
*
* Intended as an inverse for [BedEntry.unpack]. Packs the optional fields (every field except the obligatory
* first three ones, chrom, start and end) in [BedEntry.rest].
*
* @param fieldsNumber BED format fields number to serialize (3..12)
* @param extraFieldsNumber BED+ format extra fields number to serialize, if null serialize all extra fields
* @param delimiter Custom delimiter for malformed data
*/
fun pack(
fieldsNumber: Byte = 12,
extraFieldsNumber: Int? = null,
delimiter: Char = '\t'
): BedEntry {
check(fieldsNumber in 3..12) { "Expected fields number in range 3..12, but received $fieldsNumber" }
return BedEntry(
chrom, start, end,
rest(fieldsNumber, extraFieldsNumber).joinToString(delimiter.toString())
)
}
/**
* List of optional fields (all except the obligatory first three) for BED entry,
* same fields as in [BedEntry.rest] after [pack].
*
* Values in string differs from original values because converted to string.
*
* @param fieldsNumber BED format fields number to serialize (3..12)
* @param extraFieldsNumber BED+ format extra fields number to serialize, if null serialize all extra fields
*/
fun rest(fieldsNumber: Byte = 12, extraFieldsNumber: Int? = null): ArrayList<String> {
check(fieldsNumber in 3..12) { "Fields number expected 3..12, but was $fieldsNumber" }
val rest = ArrayList<String>()
if (fieldsNumber >= 4) {
// Empty string will lead to incorrect results
rest.add(if (name.isNotEmpty()) name else ".")
}
if (fieldsNumber >= 5) {
rest.add("$score")
}
if (fieldsNumber >= 6) {
rest.add("$strand")
}
if (fieldsNumber >= 7) {
rest.add("$thickStart")
}
if (fieldsNumber >= 8) {
rest.add("$thickEnd")
}
if (fieldsNumber >= 9) {
if (itemRgb == 0) {
rest.add("0")
} else {
val c = Color(itemRgb)
rest.add(Ints.join(",", c.red, c.green, c.blue))
}
}
if (fieldsNumber >= 10) {
rest.add("$blockCount")
}
if (fieldsNumber >= 11) {
if (blockCount == 0) {
rest.add(".")
} else {
val nBlockSizes = blockSizes?.size ?: 0
check(nBlockSizes == blockCount) {
"$chrom:$start-$end: Expected blocks number $blockCount != actual block sizes $nBlockSizes"
}
rest.add(blockSizes!!.joinToString(","))
}
}
if (fieldsNumber >= 12) {
if (blockCount == 0) {
rest.add(".")
} else {
val nBlockStarts = blockStarts?.size ?: 0
check(nBlockStarts == blockCount) {
"$chrom:$start-$end: Expected blocks number $blockCount != actual block starts $nBlockStarts"
}
rest.add(blockStarts!!.joinToString(","))
}
}
if (extraFields != null && extraFields.isNotEmpty()) {
if (extraFieldsNumber == null) {
rest.addAll(extraFields)
} else if (extraFieldsNumber > 0) {
check(extraFields.size >= extraFieldsNumber) {
"$chrom:$start-$end: Expected extra fields $extraFieldsNumber != actual" +
" number ${extraFields.size}"
}
(0 until extraFieldsNumber).mapTo(rest) { extraFields[it] }
}
}
return rest
}
/**
* Returns a i-th field of a Bed entry.
*
* Since [ExtendedBedEntry] is format-agnostic, it doesn't actually know which field is i-th,
* so we have to provide [fieldsNumber] and [extraFieldsNumber].
* Returns an instance of a correct type ([Int], [String] etc.) or null for missing and out of bounds fields.
* This method is useful for minimizing the number of conversions to and from [String].
*
* @param i the index of the field being queried (zero-based)
* @param fieldsNumber the number of regular BED fields (N in bedN+K notation)
* @param extraFieldsNumber the number of extra BED fields (0 for bedN, K for bedN+K, null for bedN+).
* The extra fields are always returned as [String].
*/
fun getField(i: Int, fieldsNumber: Int = 12, extraFieldsNumber: Int? = null): Any? {
val actualExtraFieldsNumber = extraFieldsNumber ?: extraFields?.size ?: 0
return when {
i >= fieldsNumber + actualExtraFieldsNumber -> null
i >= fieldsNumber -> extraFields?.let {
if (i - fieldsNumber < it.size) it[i - fieldsNumber] else null
}
else -> when (i) {
0 -> chrom
1 -> start
2 -> end
3 -> name
4 -> score
5 -> strand
6 -> thickStart
7 -> thickEnd
8 -> itemRgb
9 -> blockCount
10 -> blockSizes
11 -> blockStarts
else -> null
}
}
}
}
class BedEntryUnpackException(
val entry: BedEntry, val fieldIdx: Byte, reason: String, cause: Throwable? = null
) : Exception("Unpacking BED entry failed at field ${fieldIdx + 1}. Reason: $reason", cause)
| mit | 29bf824f5a982aaff912d792ee212aa6 | 37.555556 | 116 | 0.545321 | 4.384029 | false | false | false | false |
CypherCove/DoubleHelix | android/src/com/cyphercove/doublehelix/SettingsApplicator.kt | 1 | 4529 | /*******************************************************************************
* Copyright 2020 Cypher Cove, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.cyphercove.doublehelix
import android.content.Context
import android.content.SharedPreferences
import com.badlogic.gdx.graphics.Color
import com.cyphercove.coveprefs.utils.MultiColor
import com.cyphercove.coveprefs.utils.MultiColor.Definition
import com.cyphercove.covetools.android.utils.DevicePoller
import com.cyphercove.doublehelix.MainRenderer.SettingsAdapter
import com.cyphercove.doublehelix.R.string.*
import com.cyphercove.gdxtween.graphics.ColorSpace
import com.cyphercove.gdxtween.graphics.GtColor
class SettingsApplicator(
override val context: Context,
private val prefs: SharedPreferences
) : SharedPreferencesRetriever(), SettingsAdapter {
companion object {
var tripleTapSettings = true
private set
private val TMP0 = Color()
private val TMP1 = Color()
}
private val devicePoller = DevicePoller(context, 10f, 0.5f)
private val multiColorDefinition = Definition(context, R.array.multicolor_definition, null)
private lateinit var sceneColor: MultiColor
private var haveBatteryLevelColor = false
private var haveChargeStateColor = false
private var lastBatteryLevel = 0f
private var lastChargeState = false
override fun updateAllSettings() {
tripleTapSettings = prefs[key_triple_tap]
prepareColor()
updateColor(false)
Settings.speed = prefs.get<Int>(key_rotation_speed) / 9f + 0.05f
Settings.dof = prefs[key_depth_of_field]
Settings.bloom = prefs[key_bloom]
Settings.filmGrain = prefs[key_film_grain]
Settings.scanLines = prefs[key_scan_lines]
Settings.vignette = prefs[key_vignette]
Settings.chromaticAberration = prefs[key_chromatic_aberration]
Settings.numParticles = prefs.get<Int>(key_particle_count) * 100
Settings.flipH = prefs[key_flip_horizontal]
Settings.flipV = prefs[key_flip_vertical]
Settings.pseudoScrolling = prefs[key_psuedo_scrolling]
}
override fun updateInLoop(deltaTime: Float) {
devicePoller.update(deltaTime)
updateColor(true)
}
private fun prepareColor() {
sceneColor = MultiColor(multiColorDefinition, prefs[key_scene_color])
val type = sceneColor.type
haveBatteryLevelColor = type == 1
haveChargeStateColor = type == 2
}
private fun updateColor(powerBasedColorsOnly: Boolean) {
var batteryLevelChanged = false
var chargeStateChanged = false
if (haveBatteryLevelColor) {
val batteryLevel = devicePoller.batteryLevel
batteryLevelChanged = batteryLevel != lastBatteryLevel
lastBatteryLevel = batteryLevel
}
if (haveChargeStateColor) {
val chargeState = devicePoller.chargingState
chargeStateChanged = chargeState != lastChargeState
lastChargeState = chargeState
}
if (powerBasedColorsOnly) {
if (!batteryLevelChanged && !chargeStateChanged) return
}
val multiColor = sceneColor
val destination = Settings.frontHelixColor
when (multiColor.type) {
0 -> {
if (!powerBasedColorsOnly)
Color.argb8888ToColor(destination, multiColor.values[0])
}
1 -> {
Color.argb8888ToColor(TMP0, multiColor.values[0])
Color.argb8888ToColor(TMP1, multiColor.values[1])
GtColor.lerp(TMP0, TMP1, lastBatteryLevel, ColorSpace.DegammaLmsCompressed, false)
destination.set(TMP0)
}
2 -> Color.argb8888ToColor(destination, multiColor.values[if (lastChargeState) 1 else 0])
}
Settings.updateColorsFromFrontHelixColor()
}
} | apache-2.0 | 1f0f853a18e1b84a07dcaa7e6ac090cd | 39.446429 | 101 | 0.663723 | 4.466469 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/tufilm/KinoActivity.kt | 1 | 2154 | package de.tum.`in`.tumcampusapp.component.ui.tufilm
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.other.generic.activity.ProgressActivity
import de.tum.`in`.tumcampusapp.component.ui.tufilm.model.Kino
import de.tum.`in`.tumcampusapp.di.ViewModelFactory
import de.tum.`in`.tumcampusapp.utils.Const
import kotlinx.android.synthetic.main.activity_kino.*
import javax.inject.Inject
import javax.inject.Provider
/**
* Activity to show TU film movies
*/
class KinoActivity : ProgressActivity<Void>(R.layout.activity_kino) {
private var startPosition: Int = 0
@Inject
internal lateinit var viewModelProvider: Provider<KinoViewModel>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injector.kinoComponent().inject(this)
window.setBackgroundDrawableResource(R.color.secondary_window_background)
val factory = ViewModelFactory(viewModelProvider)
val kinoViewModel = ViewModelProviders.of(this, factory).get(KinoViewModel::class.java)
val movieDate = intent.getStringExtra(Const.KINO_DATE)
val movieId = intent.getIntExtra(Const.KINO_ID, -1)
startPosition = when {
movieDate != null -> kinoViewModel.getPositionByDate(movieDate)
movieId != -1 -> kinoViewModel.getPositionById("" + movieId)
else -> 0
}
val margin = resources.getDimensionPixelSize(R.dimen.material_default_padding)
kinoViewPager.pageMargin = margin
kinoViewModel.kinos.observe(this, Observer<List<Kino>> { this.showMoviesOrPlaceholder(it) })
kinoViewModel.error.observe(this, Observer<Int> { this.showError(it) })
}
private fun showMoviesOrPlaceholder(kinos: List<Kino>) {
if (kinos.isEmpty()) {
showEmptyResponseLayout(R.string.no_movies, R.drawable.no_movies)
return
}
kinoViewPager.adapter = KinoAdapter(supportFragmentManager, kinos)
kinoViewPager.currentItem = startPosition
}
}
| gpl-3.0 | 550d3d5d7f43ebf0cddf55b4547b1a8b | 35.508475 | 100 | 0.721448 | 4.325301 | false | false | false | false |
czyzby/ktx | assets-async/src/main/kotlin/ktx/assets/async/loaders.kt | 2 | 8363 | package ktx.assets.async
import com.badlogic.gdx.assets.AssetDescriptor
import com.badlogic.gdx.assets.AssetLoaderParameters
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.assets.loaders.AssetLoader
import com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader
import com.badlogic.gdx.assets.loaders.FileHandleResolver
import com.badlogic.gdx.assets.loaders.SynchronousAssetLoader
import com.badlogic.gdx.assets.loaders.resolvers.AbsoluteFileHandleResolver
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.PolygonRegion
import com.badlogic.gdx.graphics.g2d.PolygonRegionLoader
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.utils.ObjectMap
import com.badlogic.gdx.utils.Array as GdxArray
/**
* Stores [AssetLoader] instances mapped by loaded asset type. Internal [AssetStorage] utility.
*
* Implementation note: libGDX loaders are not thread-safe. Instead, they assume that only a single asset is loaded
* at a time and use internal, non-synchronized fields to store temporary variables like the dependencies. To avoid
* threading issues, we use a separate loader for each loaded asset instead of singleton instances - hence
* the functional loader providers.
*/
internal class AssetLoaderStorage {
private val loaders: ObjectMap<Class<*>, AssetLoaderContainer<*>> = ObjectMap()
/**
* Provides a [Loader] for the given asset [type]. Optionally, file [path] can be given,
* as depending on the file suffix, a different loader might be used for the same asset type.
*/
fun <Asset> getLoader(type: Class<Asset>, path: String? = null): Loader<Asset>? {
@Suppress("UNCHECKED_CAST")
val loadersForType = loaders[type] as AssetLoaderContainer<Asset>? ?: return null
if (path == null || loadersForType.loadersBySuffix.size == 0) {
return loadersForType.mainLoader?.invoke()
}
var maxMatchingSuffixLength = 0
var loaderProvider = loadersForType.mainLoader
loadersForType.loadersBySuffix.forEach {
val suffix = it.key
if (maxMatchingSuffixLength < suffix.length && path.endsWith(suffix)) {
maxMatchingSuffixLength = suffix.length
loaderProvider = it.value
}
}
return loaderProvider?.invoke()
}
/**
* Adds or replaces [Loader] for the given class. [loaderProvider] is invoked
* each time an instance of the selected loader is requested. The loader will be
* associated with the given asset [type]. Optionally, a [suffix] can be given
* to a associate the loader with specific file paths.
*/
fun <Asset> setLoaderProvider(type: Class<Asset>, suffix: String? = null, loaderProvider: () -> Loader<Asset>) {
validate(loaderProvider)
getOrCreateLoadersContainer(type).apply {
if (suffix.isNullOrEmpty()) {
mainLoader = loaderProvider
} else {
loadersBySuffix.put(suffix, loaderProvider)
}
}
}
private fun <Asset> validate(loaderProvider: () -> Loader<Asset>) {
val loader = loaderProvider()
if (loader !is SynchronousAssetLoader<*, *> && loader !is AsynchronousAssetLoader<*, *>) {
throw InvalidLoaderException(loader)
}
}
private fun <Asset> getOrCreateLoadersContainer(type: Class<Asset>): AssetLoaderContainer<Asset> {
val loadersForType = loaders[type]
if (loadersForType == null) {
val container = AssetLoaderContainer<Asset>()
loaders.put(type, container)
return container
}
@Suppress("UNCHECKED_CAST")
return loadersForType as AssetLoaderContainer<Asset>
}
override fun toString(): String = "AssetLoaderStorage[loaders=$loaders]"
private class AssetLoaderContainer<Asset> {
val loadersBySuffix: ObjectMap<String, () -> Loader<Asset>> = ObjectMap()
var mainLoader: (() -> Loader<Asset>)?
get() = loadersBySuffix[""]
set(value) {
loadersBySuffix.put("", value)
}
override fun toString(): String = loadersBySuffix.toString()
}
}
// Workarounds for libGDX generics API.
/** [AssetLoader] with improved generics. */
typealias Loader<Asset> = AssetLoader<Asset, out AssetLoaderParameters<Asset>>
/** [SynchronousAssetLoader] with improved generics. */
typealias SynchronousLoader<Asset> = SynchronousAssetLoader<Asset, out AssetLoaderParameters<Asset>>
/** [AsynchronousAssetLoader] with improved generics. */
typealias AsynchronousLoader<Asset> = AsynchronousAssetLoader<Asset, out AssetLoaderParameters<Asset>>
/** Casts [AssetDescriptor.params] stored with raw type. */
private val <Asset> AssetDescriptor<Asset>.parameters: AssetLoaderParameters<Asset>?
@Suppress("UNCHECKED_CAST")
get() = params as AssetLoaderParameters<Asset>?
/**
* Allows to use [AssetLoader.getDependencies] method with [AssetDescriptor].
* [assetDescriptor] contains asset data.
* Returns a [com.badlogic.gdx.utils.Array] with asset dependencies described
* with [AssetDescriptor] instances. Null if here are no dependencies.
*/
fun Loader<*>.getDependencies(assetDescriptor: AssetDescriptor<*>): GdxArray<AssetDescriptor<*>> =
@Suppress("UNCHECKED_CAST")
(this as AssetLoader<*, AssetLoaderParameters<*>>)
.getDependencies(assetDescriptor.fileName, assetDescriptor.file, assetDescriptor.parameters) ?: GdxArray(0)
/**
* Allows to use [SynchronousAssetLoader.load] method with [AssetDescriptor].
* [assetManager] provides asset dependencies for the loader.
* [assetDescriptor] contains asset data. Returns fully loaded [Asset] instance.
*/
fun <Asset> SynchronousLoader<Asset>.load(assetManager: AssetManager, assetDescriptor: AssetDescriptor<Asset>): Asset =
@Suppress("UNCHECKED_CAST")
(this as SynchronousAssetLoader<Asset, AssetLoaderParameters<Asset>>)
.load(assetManager, assetDescriptor.fileName, assetDescriptor.file, assetDescriptor.parameters)
/**
* Allows to use [AsynchronousAssetLoader.loadAsync] method with [AssetDescriptor].
* Performs the asynchronous asset loading part without yielding results.
* [assetManager] provides asset dependencies for the loader.
* [assetDescriptor] contains asset data.
*/
fun <Asset> AsynchronousLoader<Asset>.loadAsync(assetManager: AssetManager, assetDescriptor: AssetDescriptor<Asset>) =
@Suppress("UNCHECKED_CAST")
(this as AsynchronousAssetLoader<Asset, AssetLoaderParameters<Asset>>)
.loadAsync(assetManager, assetDescriptor.fileName, assetDescriptor.file, assetDescriptor.parameters)
/**
* Allows to use [AsynchronousAssetLoader.loadSync] method with [AssetDescriptor].
* Note that [loadAsync] must have been called first with the same asset data.
* [assetManager] provides asset dependencies for the loader.
* [assetDescriptor] contains asset data. Returns fully loaded [Asset] instance.
*/
fun <Asset> AsynchronousLoader<Asset>.loadSync(assetManager: AssetManager, assetDescriptor: AssetDescriptor<Asset>): Asset =
@Suppress("UNCHECKED_CAST")
(this as AsynchronousAssetLoader<Asset, AssetLoaderParameters<Asset>>)
.loadSync(assetManager, assetDescriptor.fileName, assetDescriptor.file, assetDescriptor.parameters)
/** Required for [ManualLoader] by libGDX API. */
internal class ManualLoadingParameters : AssetLoaderParameters<Any>()
/** Mocks [AssetLoader] API for assets manually added to the [AssetStorage]. See [AssetStorage.add]. */
internal object ManualLoader : AssetLoader<Any, ManualLoadingParameters>(AbsoluteFileHandleResolver()) {
private val emptyDependencies = GdxArray<AssetDescriptor<Any>>(0)
override fun getDependencies(
fileName: String?,
file: FileHandle?,
parameter: ManualLoadingParameters?
): GdxArray<AssetDescriptor<Any>> = emptyDependencies
}
/**
* Specialized [PolygonRegionLoader] extension compatible with [AssetStorage].
* Tested via the [AssetStorage] test suite.
*/
internal class AssetStoragePolygonRegionLoader(
fileHandleResolver: FileHandleResolver
) : PolygonRegionLoader(fileHandleResolver) {
override fun load(
manager: AssetManager,
fileName: String,
file: FileHandle,
parameter: PolygonRegionParameters?
): PolygonRegion {
val assetStorage = (manager as AssetManagerWrapper).assetStorage
val texturePath = assetStorage.getDependencies<PolygonRegion>(fileName).first().path
val texture = assetStorage.get<Texture>(texturePath)
return load(TextureRegion(texture), file)
}
}
| cc0-1.0 | 47dc95234168fd4111c6f11853c4b548 | 42.78534 | 124 | 0.755949 | 4.54758 | false | false | false | false |
HabitRPG/habitica-android | wearos/src/main/java/com/habitrpg/wearos/habitica/ui/activities/LevelupActivity.kt | 1 | 2697 | package com.habitrpg.wearos.habitica.ui.activities
import android.os.Bundle
import android.view.Gravity
import android.view.animation.AccelerateInterpolator
import android.widget.FrameLayout
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.ActivityLevelupBinding
import com.habitrpg.common.habitica.helpers.Animations
import com.habitrpg.wearos.habitica.ui.viewmodels.LevelupViewModel
import com.plattysoft.leonids.ParticleSystem
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch
@AndroidEntryPoint
class LevelupActivity: BaseActivity<ActivityLevelupBinding, LevelupViewModel>() {
override val viewModel: LevelupViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityLevelupBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
binding.continueButton.setOnClickListener {
binding.continueButton.isEnabled = false
startAnimatingProgress()
lifecycleScope.launch(CoroutineExceptionHandler { _, _ ->
stopAnimatingProgress()
binding.continueButton.isEnabled = true
}) {
finish()
}
}
viewModel.level.observe(this) {
binding.titleView.text = getString(R.string.user_level_long, it)
}
binding.iconView.startAnimation(Animations.bobbingAnimation(4f))
binding.expBar.setPercentageValues(100f, 100f)
val container = binding.confettiAnchor
container.postDelayed(
{
createParticles(container, R.drawable.confetti_blue)
createParticles(container, R.drawable.confetti_red)
createParticles(container, R.drawable.confetti_yellow)
createParticles(container, R.drawable.confetti_purple)
}, 500
)
}
private fun createParticles(container: FrameLayout, resource: Int) {
ParticleSystem(
container,
20,
ContextCompat.getDrawable(this, resource),
6000
)
.setRotationSpeed(144f)
.setScaleRange(1.0f, 1.6f)
.setSpeedByComponentsRange(-0.15f, 0.15f, 0.15f, 0.45f)
.setFadeOut(200, AccelerateInterpolator())
.emitWithGravity(binding.confettiAnchor, Gravity.TOP, 10, 2000)
}
override fun onResume() {
super.onResume()
binding.expBar.animateProgress(0f, 2000)
}
} | gpl-3.0 | 780fac677a4fa3e35c34dc2f2d58768d | 36.472222 | 81 | 0.690768 | 4.756614 | false | false | false | false |
google/private-compute-services | src/com/google/android/as/oss/assets/federatedcompute/LiveTranslatePolicy_FederatedCompute.kt | 1 | 7399 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.policies.federatedcompute
/** FederatedCompute policy. */
val LiveTranslatePolicy_FederatedCompute =
flavoredPolicies(
name = "LiveTranslatePolicy_FederatedCompute",
policyType = MonitorOrImproveUserExperienceWithFederatedCompute,
) {
description =
"""
To measure and improve the quality of Live Translate.
ALLOWED EGRESSES: FederatedCompute.
ALLOWED USAGES: Federated analytics, federated learning.
"""
.trimIndent()
flavors(Flavor.ASI_PROD) { minRoundSize(minRoundSize = 1000, minSecAggRoundSize = 0) }
consentRequiredForCollectionOrStorage(Consent.UsageAndDiagnosticsCheckbox)
presubmitReviewRequired(OwnersApprovalOnly)
checkpointMaxTtlDays(720)
target(PERSISTED_LIVE_TRANSLATE_CHIP_EVENT_GENERATED_DTD, maxAge = Duration.ofDays(28)) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
// ConversationId are randomly generated and just used to locally count unique threads
// translated.
"conversationId" { rawUsage(UsageType.ANY) }
"sourceLanguage" { rawUsage(UsageType.ANY) }
"targetLanguage" { rawUsage(UsageType.ANY) }
"type" { rawUsage(UsageType.ANY) }
"action" { rawUsage(UsageType.ANY) }
"packageName" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"systemInfoId" { rawUsage(UsageType.JOIN) }
}
target(
PERSISTED_LIVE_TRANSLATE_CONFIG_CHANGED_EVENT_GENERATED_DTD,
maxAge = Duration.ofDays(28)
) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"type" { rawUsage(UsageType.ANY) }
"language" { rawUsage(UsageType.ANY) }
"packageName" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"systemInfoId" { rawUsage(UsageType.JOIN) }
}
target(
PERSISTED_LIVE_TRANSLATE_COPY_TRANSLATE_EVENT_GENERATED_DTD,
maxAge = Duration.ofDays(28)
) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"conversationId" { rawUsage(UsageType.JOIN) }
"sourceLanguage" { rawUsage(UsageType.ANY) }
"targetLanguage" { rawUsage(UsageType.ANY) }
"messageId" { rawUsage(UsageType.JOIN) }
"packageName" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"systemInfoId" { rawUsage(UsageType.JOIN) }
}
target(PERSISTED_LIVE_TRANSLATE_MESSAGE_GENERATED_DTD, maxAge = Duration.ofDays(28)) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"messageId" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"length" { rawUsage(UsageType.ANY) }
"packageName" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"systemInfoId" { rawUsage(UsageType.JOIN) }
}
target(
PERSISTED_LIVE_TRANSLATE_PAGE_TRANSLATE_EVENT_GENERATED_DTD,
maxAge = Duration.ofDays(28)
) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"conversationId" { rawUsage(UsageType.JOIN) }
"sourceLanguage" { rawUsage(UsageType.ANY) }
"targetLanguage" { rawUsage(UsageType.ANY) }
"isAuto" { rawUsage(UsageType.ANY) }
"messageId" { rawUsage(UsageType.JOIN) }
"packageName" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"systemInfoId" { rawUsage(UsageType.JOIN) }
}
target(PERSISTED_LIVE_TRANSLATE_PREFERENCE_EVENT_GENERATED_DTD, maxAge = Duration.ofDays(28)) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"action" { rawUsage(UsageType.ANY) }
"packageName" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"systemInfoId" { rawUsage(UsageType.JOIN) }
}
target(PERSISTED_LIVE_TRANSLATE_DOWNLOAD_EVENT_GENERATED_DTD, maxAge = Duration.ofDays(28)) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"status" { rawUsage(UsageType.ANY) }
}
target(
PERSISTED_LIVE_TRANSLATE_TRANSLATOR_CREATION_EVENT_GENERATED_DTD,
maxAge = Duration.ofDays(28)
) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"status" { rawUsage(UsageType.ANY) }
}
target(PERSISTED_LIVE_TRANSLATE_SESSION_STATS_GENERATED_DTD, maxAge = Duration.ofDays(28)) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"packageName" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"downloadCount" { rawUsage(UsageType.ANY) }
"downloadFailureCount" { rawUsage(UsageType.ANY) }
"translatorCreationCount" { rawUsage(UsageType.ANY) }
"translatorCreationFailureCount" { rawUsage(UsageType.ANY) }
"uiTranslateMessageCount" { rawUsage(UsageType.ANY) }
"translationServiceRequestMessageCount" { rawUsage(UsageType.ANY) }
"translationServiceResponseMessageCount" { rawUsage(UsageType.ANY) }
}
}
| apache-2.0 | 64872a93f7b005ceffe1d441548f5319 | 33.900943 | 99 | 0.6832 | 4.240115 | false | false | false | false |
fredyw/leetcode | src/main/kotlin/leetcode/Problem2225.kt | 1 | 755 | package leetcode
/**
* https://leetcode.com/problems/find-players-with-zero-or-one-losses/
*/
class Problem2225 {
fun findWinners(matches: Array<IntArray>): List<List<Int>> {
val winners = mutableSetOf<Int>()
val losers = mutableMapOf<Int, Int>()
for (match in matches) {
winners += match[0]
losers[match[1]] = (losers[match[1]] ?: 0) + 1
}
val answer1 = mutableListOf<Int>()
for (winner in winners) {
if (winner !in losers) {
answer1 += winner
}
}
val answer2 = losers.filter { it.value == 1 }.map { it.key }.toMutableList()
answer1.sort()
answer2.sort()
return listOf(answer1, answer2)
}
}
| mit | 0e26bfa805b66662412c11d13807edc0 | 29.2 | 84 | 0.543046 | 3.737624 | false | false | false | false |
mitallast/netty-queue | src/main/java/org/mitallast/queue/node/InternalNode.kt | 1 | 3335 | package org.mitallast.queue.node
import com.google.inject.AbstractModule
import com.google.inject.Injector
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.apache.logging.log4j.MarkerManager
import org.mitallast.queue.common.component.AbstractLifecycleComponent
import org.mitallast.queue.common.component.ComponentModule
import org.mitallast.queue.common.component.LifecycleService
import org.mitallast.queue.common.component.ModulesBuilder
import org.mitallast.queue.common.events.EventBusModule
import org.mitallast.queue.common.file.FileModule
import org.mitallast.queue.common.json.JsonModule
import org.mitallast.queue.common.logging.LoggingModule
import org.mitallast.queue.common.logging.LoggingService
import org.mitallast.queue.common.netty.NettyModule
import org.mitallast.queue.crdt.CrdtModule
import org.mitallast.queue.crdt.rest.RestCrdtModule
import org.mitallast.queue.raft.RaftModule
import org.mitallast.queue.raft.rest.RaftRestModule
import org.mitallast.queue.rest.RestModule
import org.mitallast.queue.security.SecurityModule
import org.mitallast.queue.transport.TransportModule
class InternalNode constructor(conf: Config, logging: LoggingService, vararg plugins: AbstractModule) : AbstractLifecycleComponent(logging), Node {
private val config = conf.withFallback(ConfigFactory.defaultReference())
private val injector: Injector
init {
logger.info("initializing...")
val modules = ModulesBuilder()
modules.add(LoggingModule(logging))
modules.add(ComponentModule(config, logging))
modules.add(FileModule())
modules.add(JsonModule())
modules.add(EventBusModule())
modules.add(SecurityModule())
modules.add(NettyModule())
modules.add(TransportModule())
if (config.getBoolean("rest.enabled")) {
modules.add(RestModule())
}
if (config.getBoolean("raft.enabled")) {
modules.add(RaftModule())
if (config.getBoolean("rest.enabled")) {
modules.add(RaftRestModule())
}
if (config.getBoolean("crdt.enabled")) {
modules.add(CrdtModule())
if (config.getBoolean("rest.enabled")) {
modules.add(RestCrdtModule())
}
}
}
modules.add(*plugins)
injector = modules.createInjector()
logger.info("initialized")
}
override fun config(): Config = config
override fun injector(): Injector = injector
override fun doStart() {
injector.getInstance(LifecycleService::class.java).start()
}
override fun doStop() {
injector.getInstance(LifecycleService::class.java).stop()
}
override fun doClose() {
injector.getInstance(LifecycleService::class.java).close()
}
companion object {
fun build(config: Config, vararg plugins: AbstractModule): InternalNode {
val configWithFallback = config.withFallback(ConfigFactory.defaultReference())
val port = configWithFallback.getString("raft.discovery.port")
val marker = MarkerManager.getMarker(":$port")
val logging = LoggingService(marker)
return InternalNode(configWithFallback, logging, *plugins)
}
}
}
| mit | a33b8f176a48ed7facbe5d6944208ccd | 36.055556 | 147 | 0.703148 | 4.525102 | false | true | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/contributorlist/ContributorListFragment.kt | 1 | 5480 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.contributorlist
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import android.widget.Toast
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration
import es.dmoral.toasty.Toasty
import giuliolodi.gitnav.R
import giuliolodi.gitnav.ui.adapters.ContributorAdapter
import giuliolodi.gitnav.ui.base.BaseFragment
import giuliolodi.gitnav.ui.option.OptionActivity
import giuliolodi.gitnav.ui.user.UserActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.contributor_list_fragment.*
import org.eclipse.egit.github.core.Contributor
import javax.inject.Inject
/**
* Created by giulio on 30/08/2017.
*/
class ContributorListFragment: BaseFragment(), ContributorListContract.View {
@Inject lateinit var mPresenter: ContributorListContract.Presenter<ContributorListContract.View>
private var mOwner: String? = null
private var mName: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
getActivityComponent()?.inject(this)
mOwner = activity.intent.getStringExtra("owner")
mName = activity.intent.getStringExtra("name")
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.contributor_list_fragment, container, false)
}
override fun initLayout(view: View?, savedInstanceState: Bundle?) {
mPresenter.onAttach(this)
setHasOptionsMenu(true)
(activity as AppCompatActivity).setSupportActionBar(contributor_list_fragment_toolbar)
(activity as AppCompatActivity).supportActionBar?.title = getString(R.string.contributors)
(activity as AppCompatActivity).supportActionBar?.subtitle = mOwner + "/" + mName
(activity as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)
(activity as AppCompatActivity).supportActionBar?.setDisplayShowHomeEnabled(true)
contributor_list_fragment_toolbar.setNavigationOnClickListener { activity.onBackPressed() }
val llm = LinearLayoutManager(context)
llm.orientation = LinearLayoutManager.VERTICAL
contributor_list_fragment_rv.layoutManager = llm
contributor_list_fragment_rv.addItemDecoration(HorizontalDividerItemDecoration.Builder(context).showLastDivider().build())
contributor_list_fragment_rv.itemAnimator = DefaultItemAnimator()
contributor_list_fragment_rv.adapter = ContributorAdapter()
(contributor_list_fragment_rv.adapter as ContributorAdapter).getPositionClicks()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { username -> mPresenter.onUserClick(username) }
mPresenter.subscribe(isNetworkAvailable(), mOwner, mName)
}
override fun showContributorList(contributorList: List<Contributor>) {
(contributor_list_fragment_rv.adapter as ContributorAdapter).addContributorList(contributorList)
}
override fun showLoading() {
contributor_list_progress_bar.visibility = View.VISIBLE
}
override fun hideLoading() {
contributor_list_progress_bar.visibility = View.GONE
}
override fun showNoContributor() {
contributor_list_no_contributors.visibility = View.VISIBLE
}
override fun hideNoContributor() {
contributor_list_no_contributors.visibility = View.GONE
}
override fun showError(error: String) {
Toasty.error(context, error, Toast.LENGTH_LONG).show()
}
override fun showNoConnectionError() {
Toasty.warning(context, getString(R.string.network_error), Toast.LENGTH_LONG).show()
}
override fun intentToUserActivity(username: String) {
startActivity(UserActivity.getIntent(context).putExtra("username", username))
activity.overridePendingTransition(0,0)
}
override fun onDestroyView() {
mPresenter.onDetachView()
super.onDestroyView()
}
override fun onDestroy() {
mPresenter.onDetach()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.main, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == R.id.action_options) {
startActivity(OptionActivity.getIntent(context))
activity.overridePendingTransition(0,0)
}
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | 26922dc726cfcea3ec163f593029243f | 37.328671 | 130 | 0.733942 | 4.853853 | false | false | false | false |
ShadwLink/Shadow-Mapper | src/main/java/nl/shadowlink/tools/shadowlib/ipl/IplIII.kt | 1 | 4854 | package nl.shadowlink.tools.shadowlib.ipl
import nl.shadowlink.tools.shadowlib.utils.Constants
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import java.util.logging.Level
import java.util.logging.Logger
/**
* @author Shadow-Link
*/
class IplIII {
private var input: BufferedReader? = null
private var fileReader: FileReader? = null
private var readItem = -1
fun loadPlacement(ipl: Ipl) {
if (openIPL(ipl.fileName)) {
try {
var line: String? = null
while (input!!.readLine().also { line = it } != null) {
if (readItem == -1) {
if (line!!.startsWith("#")) {
} else if (line!!.startsWith("inst")) {
readItem = Constants.pINST
} else if (line!!.startsWith("cull")) {
readItem = Constants.pCULL
} else if (line!!.startsWith("path")) {
readItem = Constants.pPATH
} else if (line!!.startsWith("grge")) {
readItem = Constants.pGRGE
} else if (line!!.startsWith("enex")) {
readItem = Constants.pENEX
} else if (line!!.startsWith("pick")) {
readItem = Constants.pPICK
} else if (line!!.startsWith("jump")) {
readItem = Constants.pJUMP
} else if (line!!.startsWith("tcyc")) {
readItem = Constants.pTCYC
} else if (line!!.startsWith("auzo")) {
readItem = Constants.pAUZO
} else if (line!!.startsWith("mult")) {
readItem = Constants.pMULT
} else if (line!!.startsWith("cars")) {
readItem = Constants.pCARS
} else if (line!!.startsWith("occl")) {
readItem = Constants.pOCCL
} else if (line!!.startsWith("zone")) {
readItem = Constants.pZONE
}
} else {
if (line!!.startsWith("#")) {
// Commented line
} else if (line!!.startsWith("end")) {
readItem = -1
} else {
var item: IplItem?
when (readItem) {
Constants.pINST -> {
item = Item_INST(ipl.gameType)
ipl.itemsInst.add(item)
}
Constants.pAUZO -> item = Item_AUZO(ipl.gameType)
Constants.pCARS -> item = Item_CARS(ipl.gameType)
Constants.pCULL -> item = Item_CULL(ipl.gameType)
Constants.pENEX -> item = Item_ENEX(ipl.gameType)
Constants.pJUMP -> item = Item_JUMP(ipl.gameType)
Constants.pGRGE -> item = Item_GRGE(ipl.gameType)
Constants.pMULT -> item = Item_MULT(ipl.gameType)
Constants.pOCCL -> item = Item_OCCL(ipl.gameType)
Constants.pPATH -> item = Item_PATH(ipl.gameType)
Constants.pPICK -> item = Item_PICK(ipl.gameType)
Constants.pTCYC -> item = Item_TCYC(ipl.gameType)
Constants.pZONE -> item = Item_ZONE(ipl.gameType)
else -> throw IllegalArgumentException("Unknown type $readItem")
}
item.read(line!!)
}
}
}
} catch (ex: IOException) {
Logger.getLogger(IplIII::class.java.name).log(Level.SEVERE, null, ex)
}
closeIPL()
} else {
throw IllegalStateException("Unable to open IPL file")
}
ipl.loaded = true
}
fun openIPL(fileName: String?): Boolean {
try {
fileReader = FileReader(fileName)
input = BufferedReader(fileReader)
} catch (ex: IOException) {
return false
}
return true
}
fun closeIPL(): Boolean {
try {
input!!.close()
fileReader!!.close()
} catch (ex: IOException) {
return false
}
return true
}
fun save(ipl: Ipl?) {}
} | gpl-2.0 | f3862350ebce48517062a8e80ed7d43f | 41.587719 | 96 | 0.425834 | 5.050989 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android | common_converters/src/main/java/com/vmenon/mpo/common/converters/ConverterExtensions.kt | 1 | 482 | package com.vmenon.mpo.common.converters
import com.vmenon.mpo.downloads.domain.DownloadRequest
import com.vmenon.mpo.downloads.domain.DownloadRequestType
import com.vmenon.mpo.my_library.domain.EpisodeModel
fun EpisodeModel.toDownloadRequest(): DownloadRequest =
DownloadRequest(
name = name,
downloadRequestType = DownloadRequestType.EPISODE,
downloadUrl = downloadUrl,
imageUrl = artworkUrl ?: show.artworkUrl,
requesterId = id
) | apache-2.0 | a6be420eec6774cdd6b74e2675f56adc | 33.5 | 58 | 0.751037 | 4.679612 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/toolbar/ToolbarColorChangeDetector.kt | 1 | 756 | package org.walleth.toolbar
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.walleth.data.config.Settings
interface ToolbarColorChangeDetector {
val wallethSettings: Settings
var lastToolbarColor: Long
fun calcToolbarColorCombination() = wallethSettings.toolbarBackgroundColor.toLong() + wallethSettings.toolbarForegroundColor
fun didToolbarColorChange() = (lastToolbarColor != calcToolbarColorCombination()).also {
lastToolbarColor = calcToolbarColorCombination()
}
}
class DefaultToolbarChangeDetector : ToolbarColorChangeDetector, KoinComponent {
override val wallethSettings: Settings by inject()
override var lastToolbarColor: Long = calcToolbarColorCombination()
} | gpl-3.0 | 75f41efd4f1b8c9d72dae49bdb394a5d | 35.047619 | 128 | 0.805556 | 4.609756 | false | false | false | false |
k9mail/k-9 | app/core/src/test/java/com/fsck/k9/TestCoreResourceProvider.kt | 2 | 1665 | package com.fsck.k9
import com.fsck.k9.notification.PushNotificationState
class TestCoreResourceProvider : CoreResourceProvider {
override fun defaultSignature() = "\n--\nbrevity!"
override fun defaultIdentityDescription() = "initial identity"
override fun contactDisplayNamePrefix() = "To:"
override fun contactUnknownSender() = "<Unknown Sender>"
override fun contactUnknownRecipient() = "<Unknown Recipient>"
override fun messageHeaderFrom() = "From:"
override fun messageHeaderTo() = "To:"
override fun messageHeaderCc() = "Cc:"
override fun messageHeaderDate() = "Sent:"
override fun messageHeaderSubject() = "Subject:"
override fun messageHeaderSeparator() = "-------- Original Message --------"
override fun noSubject() = "(No subject)"
override fun userAgent(): String = "K-9 Mail for Android"
override fun encryptedSubject(): String = "Encrypted message"
override fun replyHeader(sender: String) = "$sender wrote:"
override fun replyHeader(sender: String, sentDate: String) = "On $sentDate, $sender wrote:"
override fun searchUnifiedInboxTitle() = "Unified Inbox"
override fun searchUnifiedInboxDetail() = "All messages in unified folders"
override fun outboxFolderName() = "Outbox"
override val iconPushNotification: Int
get() = throw UnsupportedOperationException("not implemented")
override fun pushNotificationText(notificationState: PushNotificationState): String {
throw UnsupportedOperationException("not implemented")
}
override fun pushNotificationInfoText(): String = throw UnsupportedOperationException("not implemented")
}
| apache-2.0 | de8a8c97ef5b4283300fe6e3791cff13 | 38.642857 | 108 | 0.726727 | 4.897059 | false | false | false | false |
r-ralph/Quartz | compiler/src/main/kotlin/ms/ralph/quartz/compiler/QuartzProcessor.kt | 1 | 1810 | /*
* Copyright 2016 Ralph
*
* 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 ms.ralph.quartz.compiler
import ms.ralph.quartz.Quartz
import ms.ralph.quartz.compiler.util.getPackageName
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
/**
* Main processor class
*/
class QuartzProcessor : AbstractProcessor() {
private lateinit var filer: Filer
private lateinit var messager: Messager
private lateinit var elements: Elements
override fun init(processingEnv: ProcessingEnvironment) {
super.init(processingEnv)
messager = processingEnv.messager
filer = processingEnv.filer
elements = processingEnv.elementUtils
}
override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latestSupported()
override fun getSupportedAnnotationTypes(): MutableSet<String> = hashSetOf(Quartz::class.java.canonicalName)
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
roundEnv.getElementsAnnotatedWith(Quartz::class.java).forEach {
QuartzGenerator.createJavaFile(it.getPackageName(elements), it, messager).writeTo(filer)
}
return true
}
} | apache-2.0 | ad6b5d96a637ae455e44060ccee6db9a | 34.509804 | 112 | 0.748066 | 4.652956 | false | false | false | false |
Appyx/AlexaHome | manager/src/main/kotlin/at/rgstoettner/alexahome/manager/controller/UserController.kt | 1 | 7663 | package at.rgstoettner.alexahome.manager.controller
import at.rgstoettner.alexahome.manager.*
import java.io.File
import java.util.*
class UserController : AbstractController() {
fun add() {
if (!isInstalled) handleFatalError(CliError.NOT_INSTALLED)
"Enter the Amazon Developer Account: [[email protected]]".println()
val account = requiredReadLine()
addUser(account)
}
/**
* Adds a new user:
*
* 1. create certificates for server and client and sign them with CA
* 2. copy certificates/key from client folder to lambda folder and zip a new package
* 3. copy truststore/keystore to executor and build it
* 4. copy truststore/keystore to skill and build it
* 5. create zip package of executor and skill
*/
private fun addUser(account: String) {
if (home.lambda.tls.users.dir(account).exists()) handleFatalError(CliError.USER_ALREADY_EXISTS)
"Enter the password for the Certificate Authority:".println()
val rootPass = requiredReadLine()
"Enter a password for the user keys: (optional)".println()
var tlsPass = safeReadLine()
if (tlsPass.isEmpty()) tlsPass = UUID.randomUUID().toString()
"Enter the local ip and the local port of the server: [X.X.X.X:YYYY]".println()
val local = requiredReadLine()
val localIP = local.split(":").getOrElse(0) { handleFatalError(CliError.UNKNOWN_ARGUMENTS);"" }
val localPort = local.split(":").getOrElse(1) { handleFatalError(CliError.UNKNOWN_ARGUMENTS);"" }.toIntOrNull()
if (localPort == null || localPort <= 1 || localPort > 65535) handleFatalError(CliError.ARGUMENTS_NOT_SUPPORTED)
"Enter the remote domain and the remote port of the server: [yourdomain.com:YYYY]".println()
val remote = requiredReadLine()
val remoteDomain = remote.split(":").getOrElse(0) { handleFatalError(CliError.UNKNOWN_ARGUMENTS); "" }
val remotePort = remote.split(":").getOrElse(1) { handleFatalError(CliError.UNKNOWN_ARGUMENTS); "" }.toIntOrNull()
if (remotePort == null || remotePort <= 1 || remotePort > 65535) handleFatalError(CliError.ARGUMENTS_NOT_SUPPORTED)
val settings = Settings()
settings.user = account
settings.role = "user"
settings.localIp = localIP
settings.localPort = localPort
settings.remoteDomain = remoteDomain
settings.remotePort = remotePort
settings.password = tlsPass
"Creating tls configuration...".println()
"chmod +x ${home.tls.file("gen_user.sh")}".runCommand()
var content = home.tls.file("openssl_nosan.cnf").readText()
content = content.plus("\n[SAN]\nsubjectAltName=DNS:localhost,DNS:$remoteDomain,IP:127.0.0.1,IP:$localIP")
home.tls.file("openssl.cnf").writeText(content)
"./gen_user.sh $tlsPass $localIP $remoteDomain $rootPass $account".runCommandInside(home.tls)
home.tls.file("openssl.cnf").delete()
if (logContainsError()) {
home.tls.server.deleteRecursively()
home.tls.client.deleteRecursively()
handleFatalError(CliError.TLS_CONFIG_FAILED)
}
"Building AWS lambda...".println()
val userDir = home.lambda.tls.users.dir(account)
home.tls.client.file("client-cert.pem").override(userDir.file("client-cert.pem"))
home.tls.client.file("client-key.pem").override(userDir.file("client-key.pem"))
userDir.file("settings.json").writeText(gson.toJson(settings))
"zip -r lambda.zip index.js tls".runCommandInside(home.lambda)
home.lambda.file("lambda.zip").override(File("lambda.zip"))
userTemp.mkdir()
"Building executor...".println()
home.tls.client.file("client-keystore.jks").override(home.executor.srcMainRes.tls.file("client-keystore.jks"))
home.tls.client.file("client-truststore.jks").override(home.executor.srcMainRes.tls.file("client-truststore.jks"))
home.executor.srcMainRes.file("settings.json").writeText(gson.toJson(settings))
"gradle fatJar".runCommandInside(home.executor, false)
"cp ${home.executor.buildLibs}/executor* ${userTemp}".runCommand() //wildcard copy
"Building skill...".println()
home.tls.server.file("server-keystore.jks").override(home.skill.srcMainRes.tls.file("server-keystore.jks"))
home.tls.server.file("server-truststore.jks").override(home.skill.srcMainRes.tls.file("server-truststore.jks"))
home.skill.srcMainRes.file("settings.json").writeText(gson.toJson(settings))
"gradle build".runCommandInside(home.skill, false)
"cp ${home.skill.buildLibs}/skill* ${userTemp}".runCommand() //wildcard copy
home.tls.server.deleteRecursively()
home.tls.client.deleteRecursively()
"zip $account.zip *".runCommandInside(userTemp)
userTemp.file("$account.zip").override(root.file("$account.zip"))
userTemp.deleteRecursively()
if (logContainsError()) {
removeUser(account, silent = true)
handleFatalError(CliError.BUILD_FAILED)
}
"Successfully created user!".println()
println()
"Created file: lambda.zip".println()
"Created file: $account.zip".println()
}
fun list() {
if (!isInstalled) handleFatalError(CliError.NOT_INSTALLED)
if (home.lambda.tls.users.exists()) {
val walk = home.lambda.tls.users.walkTopDown()
val users = walk
.maxDepth(1)
.asSequence()
.filter { it.isDirectory }
.map { it.name }
.filter { it != "users" }
.filter { !it.startsWith(".") }
.toList()
if (users.isNotEmpty()) {
"The following users are currently registered:".println()
users.forEach { account ->
val settings = home.lambda.tls.users.dir(account).file("settings.json").asClass(Settings::class.java)
"* Account: %-20s Remote: %-20s Local: %-20s".format(settings.user,
"${settings.remoteDomain}:${settings.remotePort}",
"${settings.localIp}:${settings.remotePort}")
.println()
}
} else {
"No users are registered.".println()
}
} else {
"No users are registered.".println()
}
}
fun remove() {
if (!isInstalled) handleFatalError(CliError.NOT_INSTALLED)
"Enter the account: [[email protected]]".println()
val account = requiredReadLine()
removeUser(account)
}
/**
* Removes the user folder from the lambda and creates a new zip
*/
private fun removeUser(account: String, silent: Boolean = false) {
val file = home.lambda.tls.users.dir(account)
if (file.exists()) {
file.deleteRecursively()
val zip = root.file("$account.zip")
if (zip.exists()) {
zip.delete()
}
if (!silent) "Successfully removed user $account!".println()
if (home.lambda.tls.users.walkTopDown().count() != 0) { //if directory is empty
"zip -r lambda.zip index.js tls".runCommandInside(home.lambda, !silent)
home.lambda.file("lambda.zip").override(File("lambda.zip"))
if (!silent) "Created dir: lambda.zip".println()
}
} else {
handleFatalError(CliError.UNKNOWN_USER)
}
}
} | apache-2.0 | e022d6f20fb0714080b1b4f740ee2077 | 43.818713 | 123 | 0.615947 | 4.164674 | false | false | false | false |
Maccimo/intellij-community | plugins/gradle/java/src/service/navigation/GradleVersionCatalogGotoDeclarationHandler.kt | 3 | 5067 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.service.navigation
import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.psi.PsiMethod
import com.intellij.psi.util.parentOfType
import com.intellij.util.castSafelyTo
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames
import org.jetbrains.plugins.gradle.service.resolve.GradleExtensionProperty
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.groovy.intentions.style.inference.resolve
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyConstantExpressionEvaluator
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils
import java.nio.file.Path
class GradleVersionCatalogGotoDeclarationHandler : GotoDeclarationHandler {
override fun getGotoDeclarationTargets(sourceElement: PsiElement?, offset: Int, editor: Editor?): Array<PsiElement>? {
if (sourceElement == null) {
return null
}
val resolved = sourceElement.parentOfType<GrReferenceExpression>()?.resolve() ?: return null
val settingsFile = getSettingsFile(sourceElement.project) ?: return null
val resolveVisitor = GroovySettingsFileResolveVisitor(resolved)
settingsFile.accept(resolveVisitor)
return resolveVisitor.resolveTarget?.let { arrayOf(it) }
}
}
private fun getSettingsFile(project: Project) : GroovyFileBase? {
val projectData = ProjectDataManager.getInstance().getExternalProjectsData(project,
GradleConstants.SYSTEM_ID).mapNotNull { it.externalProjectStructure }
for (projectDatum in projectData) {
val settings = Path.of(projectDatum.data.linkedExternalProjectPath).resolve(GradleConstants.SETTINGS_FILE_NAME).let {
VfsUtil.findFile(it, false)
}?.let { PsiManager.getInstance(project).findFile(it) }?.castSafelyTo<GroovyFileBase>()
return settings
}
return null
}
private class GroovySettingsFileResolveVisitor(val element : PsiElement) : GroovyRecursiveElementVisitor() {
var resolveTarget : PsiElement? = null
val accessorName = element.castSafelyTo<PsiMethod>()?.takeIf { it.returnType?.resolve()?.qualifiedName == GradleCommonClassNames.GRADLE_API_PROVIDER_PROVIDER }?.let(::getCapitalizedAccessorName)
override fun visitMethodCallExpression(methodCallExpression: GrMethodCallExpression) {
val method = methodCallExpression.resolveMethod()
if (element is GradleExtensionProperty && element.name == method?.name && method.returnType?.equalsToText(GradleCommonClassNames.GRADLE_API_VERSION_CATALOG_BUILDER) == true) {
resolveTarget = methodCallExpression
return
}
if (accessorName != null && method?.containingClass?.qualifiedName == GradleCommonClassNames.GRADLE_API_VERSION_CATALOG_BUILDER) {
val definedName = methodCallExpression.argumentList.expressionArguments.firstOrNull()
val definedNameValue = GroovyConstantExpressionEvaluator.evaluate(definedName).castSafelyTo<String>() ?: return super.visitMethodCallExpression(methodCallExpression)
val longName = definedNameValue.split("_", ".", "-").joinToString("", transform = GroovyPropertyUtils::capitalize)
if (longName == accessorName) {
resolveTarget = methodCallExpression
return
}
}
super.visitMethodCallExpression(methodCallExpression)
}
}
internal fun getCapitalizedAccessorName(method: PsiMethod): String? {
val propertyName = GroovyPropertyUtils.getPropertyName(method) ?: return null
val methodFinalPart = GroovyPropertyUtils.capitalize(propertyName)
val methodParts = method.containingClass?.takeUnless { it.name?.startsWith(LIBRARIES_FOR_PREFIX) == true }?.name?.trimAccessorName()
return (methodParts ?: "") + methodFinalPart
}
private fun String.trimAccessorName(): String {
for (suffix in listOf(BUNDLE_ACCESSORS_SUFFIX, LIBRARY_ACCESSORS_SUFFIX, PLUGIN_ACCESSORS_SUFFIX, VERSION_ACCESSORS_SUFFIX)) {
if (endsWith(suffix)) return substringBeforeLast(suffix)
}
return this
}
internal const val BUNDLE_ACCESSORS_SUFFIX = "BundleAccessors"
internal const val LIBRARY_ACCESSORS_SUFFIX = "LibraryAccessors"
internal const val PLUGIN_ACCESSORS_SUFFIX = "PluginAccessors"
internal const val VERSION_ACCESSORS_SUFFIX = "VersionAccessors"
internal const val LIBRARIES_FOR_PREFIX = "LibrariesFor"
| apache-2.0 | 405f0bc700299cf9fa527dedc773e38e | 52.904255 | 196 | 0.788238 | 4.780189 | false | false | false | false |
k9mail/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/ui/helper/SizeFormatter.kt | 2 | 890 | package com.fsck.k9.ui.helper
import android.content.res.Resources
import com.fsck.k9.ui.R
class SizeFormatter(private val resources: Resources) {
fun formatSize(size: Long): String {
return when {
size >= 999_950_000L -> {
val number = (size / 1_000_000L).toFloat() / 1000f
resources.getString(R.string.size_format_gigabytes, number)
}
size >= 999_950L -> {
val number = (size / 1000L).toFloat() / 1000f
resources.getString(R.string.size_format_megabytes, number)
}
size >= 1000L -> {
val number = size.toFloat() / 1000f
resources.getString(R.string.size_format_kilobytes, number)
}
else -> {
resources.getString(R.string.size_format_bytes, size)
}
}
}
}
| apache-2.0 | 708b5d4fe10980a9a19885f0271e031e | 33.230769 | 75 | 0.535955 | 3.973214 | false | false | false | false |
Maccimo/intellij-community | plugins/markdown/test/src/org/intellij/plugins/markdown/editor/tables/MarkdownTableTabTest.kt | 4 | 3587 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor.tables
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import com.intellij.ui.scale.TestScaleHelper
import org.intellij.plugins.markdown.editor.tables.TableTestUtils.runWithChangedSettings
class MarkdownTableTabTest: LightPlatformCodeInsightTestCase() {
override fun tearDown() {
try {
TestScaleHelper.restoreRegistryProperties()
}
catch (e: Throwable) {
addSuppressedException(e)
}
finally {
super.tearDown()
}
}
fun `test single tab forward`() {
// language=Markdown
val before = """
| none | none |
|------|------|
| some<caret> | some |
""".trimIndent()
// language=Markdown
val after = """
| none | none |
|------|------|
| some | <caret>some |
""".trimIndent()
doTest(before, after)
}
fun `test multiple tabs forward`() {
// language=Markdown
val before = """
| none | none | none |
|------|------|------|
| some<caret> | some | some |
""".trimIndent()
// language=Markdown
val after = """
| none | none | none |
|------|------|------|
| some | some | <caret>some |
""".trimIndent()
doTest(before, after, count = 2)
}
fun `test multiple tabs forward to next row`() {
// language=Markdown
val before = """
| none | none | none |
|------|------|------|
| some<caret> | some | some |
| some | some | some |
""".trimIndent()
// language=Markdown
val after = """
| none | none | none |
|------|------|------|
| some | some | some |
| some | some | <caret>some |
""".trimIndent()
doTest(before, after, count = 5)
}
fun `test single tab backward`() {
// language=Markdown
val before = """
| none | none |
|------|------|
| some | some<caret> |
""".trimIndent()
// language=Markdown
val after = """
| none | none |
|------|------|
| some<caret> | some |
""".trimIndent()
doTest(before, after, forward = false)
}
fun `test multiple tabs backward`() {
// language=Markdown
val before = """
| none | none | none |
|------|------|------|
| some | some | some<caret> |
""".trimIndent()
// language=Markdown
val after = """
| none | none | none |
|------|------|------|
| some<caret> | some | some |
""".trimIndent()
doTest(before, after, count = 2, forward = false)
}
fun `test multiple tabs backward to previous row`() {
// language=Markdown
val before = """
| none | none | none |
|------|------|------|
| some | some | some |
| some | some | some<caret> |
""".trimIndent()
// language=Markdown
val after = """
| none | none | none |
|------|------|------|
| some<caret> | some | some |
| some | some | some |
""".trimIndent()
doTest(before, after, count = 5, forward = false)
}
private fun doTest(content: String, expected: String, count: Int = 1, forward: Boolean = true) {
TestScaleHelper.setRegistryProperty("markdown.tables.editing.support.enable", "true")
runWithChangedSettings(project) {
configureFromFileText("some.md", content)
repeat(count) {
when {
forward -> executeAction("EditorTab")
else -> executeAction("EditorUnindentSelection")
}
}
checkResultByText(expected)
}
}
}
| apache-2.0 | 1a33bf914b85840a876d174f613a91d2 | 25.768657 | 158 | 0.545024 | 4.265161 | false | true | false | false |
shibafu528/SperMaster | app/src/main/kotlin/info/shibafu528/spermaster/model/Ejaculation.kt | 1 | 1966 | package info.shibafu528.spermaster.model
import android.provider.BaseColumns
import com.activeandroid.Model
import com.activeandroid.annotation.Column
import com.activeandroid.annotation.Table
import com.activeandroid.query.Select
import info.shibafu528.spermaster.util.MemoizeDelayed
import java.util.*
/**
* 射精記録1回分のデータモデル。
*
* Created by shibafu on 15/07/04.
*/
public @Table(name = "Ejaculations", id = BaseColumns._ID) class Ejaculation() : Model() {
/** 射精の記録日時。 */
@Column(name = "EjaculatedDate") public var ejaculatedDate: Date = Date()
/** ユーザが任意に利用できるフリーメモの内容。 */
@Column(name = "Note") public var note: String = ""
public val timeSpan: Long by MemoizeDelayed(0) {
ejaculatedDate.time - (before()?.ejaculatedDate?.time ?: ejaculatedDate.time)
}
/**
* 新規の射精記録を作成します。
* @param ejaculatedDate 記録日時
* @param note メモ
*/
constructor(ejaculatedDate: Date, note: String = "") : this() {
this.ejaculatedDate = ejaculatedDate
this.note = note
}
public fun tagMap() : List<TagMap> = id?.let { super.getMany(TagMap::class.java, "EjaculationId") } ?: emptyList()
/**
* この記録に紐付けられているタグのリストを取得します。
* @return 紐付いているタグ
*/
public fun tags() : List<Tag> = id?.let { super.getMany(TagMap::class.java, "EjaculationId").map { it.tag!! } } ?: emptyList()
/**
* この記録の1つ手前の記録を取得します。
* @return 直前の記録。存在しない場合は`null`。
*/
public fun before() : Ejaculation? =
Select().from(Ejaculation::class.java)
.where("EjaculatedDate < ?", ejaculatedDate.time.toString())
.orderBy("EjaculatedDate desc")
.executeSingle()
}
| mit | e55458775c80b7ea6eb19c7fc1923f8d | 30.592593 | 130 | 0.64068 | 3.024823 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/widgets/NestedWebView.kt | 1 | 6577 | package org.wordpress.android.widgets
import android.R.attr
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.core.view.NestedScrollingChild3
import androidx.core.view.NestedScrollingChildHelper
import androidx.core.view.ViewCompat
import org.wordpress.android.ui.WPWebView
/**
* To make WebView work with AppBar in Coordinator layout we need to put into a NestedScrollView
* Which leads to some issues related to scrolling, and while majority of them could be solved through modifying layout
* hierarchy, some are not so easily fixable.
*
* NestedWebView implements nested scroll properties and works well inside NestedScrollView.
*
* Variation of https://stackoverflow.com/a/45026679/569430 with NestedScrollingChild3
*/
class NestedWebView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = attr.webViewStyle
) : WPWebView(context, attrs, defStyleAttr), NestedScrollingChild3 {
private var lastY = 0
private val scrollOffset = IntArray(2)
private val scrollConsumed = IntArray(2)
private var nestedOffsetY = 0
private val nestedScrollingChildHelper: NestedScrollingChildHelper = NestedScrollingChildHelper(this)
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(ev: MotionEvent): Boolean {
var returnValue = false
val event = MotionEvent.obtain(ev)
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
nestedOffsetY = 0
}
val eventY = event.y.toInt()
event.offsetLocation(0f, nestedOffsetY.toFloat())
when (event.actionMasked) {
MotionEvent.ACTION_MOVE -> {
var totalScrollOffset = 0
var deltaY = lastY - eventY
// NestedPreScroll
if (dispatchNestedPreScroll(0, deltaY, scrollConsumed, scrollOffset)) {
totalScrollOffset += scrollOffset[1]
deltaY -= scrollConsumed[1]
event.offsetLocation(0f, (-scrollOffset[1]).toFloat())
nestedOffsetY += scrollOffset[1]
}
returnValue = super.onTouchEvent(event)
// NestedScroll
if (dispatchNestedScroll(0, scrollOffset[1], 0, deltaY, scrollOffset)) {
totalScrollOffset += scrollOffset[1]
event.offsetLocation(0f, scrollOffset[1].toFloat())
nestedOffsetY += scrollOffset[1]
lastY -= scrollOffset[1]
}
lastY = eventY - totalScrollOffset
}
MotionEvent.ACTION_DOWN -> {
returnValue = super.onTouchEvent(event)
lastY = eventY
// start NestedScroll
startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL)
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
// end NestedScroll
stopNestedScroll()
returnValue = super.onTouchEvent(event)
}
}
return returnValue
}
override fun setNestedScrollingEnabled(enabled: Boolean) {
nestedScrollingChildHelper.isNestedScrollingEnabled = enabled
}
override fun isNestedScrollingEnabled(): Boolean {
return nestedScrollingChildHelper.isNestedScrollingEnabled
}
override fun startNestedScroll(axes: Int, type: Int): Boolean {
return nestedScrollingChildHelper.startNestedScroll(axes, type)
}
override fun startNestedScroll(axes: Int): Boolean {
return nestedScrollingChildHelper.startNestedScroll(axes)
}
override fun stopNestedScroll(type: Int) {
nestedScrollingChildHelper.stopNestedScroll(type)
}
override fun stopNestedScroll() {
nestedScrollingChildHelper.stopNestedScroll()
}
override fun hasNestedScrollingParent(type: Int): Boolean {
return nestedScrollingChildHelper.hasNestedScrollingParent(type)
}
override fun hasNestedScrollingParent(): Boolean {
return nestedScrollingChildHelper.hasNestedScrollingParent()
}
override fun dispatchNestedScroll(
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
offsetInWindow: IntArray?,
type: Int,
consumed: IntArray
) {
nestedScrollingChildHelper.dispatchNestedScroll(
dxConsumed,
dyConsumed,
dxUnconsumed,
dyUnconsumed,
offsetInWindow,
type,
consumed
)
}
override fun dispatchNestedScroll(
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
offsetInWindow: IntArray?,
type: Int
): Boolean {
return nestedScrollingChildHelper.dispatchNestedScroll(
dxConsumed,
dyConsumed,
dxUnconsumed,
dyUnconsumed,
offsetInWindow,
type
)
}
override fun dispatchNestedScroll(
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
offsetInWindow: IntArray?
): Boolean {
return nestedScrollingChildHelper.dispatchNestedScroll(
dxConsumed,
dyConsumed,
dxUnconsumed,
dyUnconsumed,
offsetInWindow
)
}
override fun dispatchNestedPreScroll(
dx: Int,
dy: Int,
consumed: IntArray?,
offsetInWindow: IntArray?,
type: Int
): Boolean {
return nestedScrollingChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type)
}
override fun dispatchNestedPreScroll(dx: Int, dy: Int, consumed: IntArray?, offsetInWindow: IntArray?): Boolean {
return nestedScrollingChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow)
}
override fun dispatchNestedFling(velocityX: Float, velocityY: Float, consumed: Boolean): Boolean {
return nestedScrollingChildHelper.dispatchNestedFling(velocityX, velocityY, consumed)
}
override fun dispatchNestedPreFling(velocityX: Float, velocityY: Float): Boolean {
return nestedScrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY)
}
init {
isNestedScrollingEnabled = true
}
}
| gpl-2.0 | 9e7e02e8790e7c9ae056910d12599abd | 33.615789 | 119 | 0.639805 | 5.540859 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/CodeFragmentAnalyzer.kt | 3 | 10373 | // 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.caches.resolve
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.util.analyzeControlFlow
import org.jetbrains.kotlin.idea.project.ResolveElementCache
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.codeFragmentUtil.suppressDiagnosticsInDebugMode
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypes3
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.utils.addImportingScopes
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.idea.core.util.externalDescriptors
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
import org.jetbrains.kotlin.resolve.BindingContext.USED_AS_EXPRESSION
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
import javax.inject.Inject
class CodeFragmentAnalyzer(
private val resolveSession: ResolveSession,
private val qualifierResolver: QualifiedExpressionResolver,
private val typeResolver: TypeResolver,
private val expressionTypingServices: ExpressionTypingServices
) {
@set:Inject // component dependency cycle
lateinit var resolveElementCache: ResolveElementCache
fun analyzeCodeFragment(codeFragment: KtCodeFragment, bodyResolveMode: BodyResolveMode): BindingTrace {
val contextAnalysisResult = analyzeCodeFragmentContext(codeFragment, bodyResolveMode)
return doAnalyzeCodeFragment(codeFragment, contextAnalysisResult)
}
private fun doAnalyzeCodeFragment(codeFragment: KtCodeFragment, contextInfo: ContextInfo): BindingTrace {
val (bindingContext, scope, dataFlowInfo) = contextInfo
val bindingTrace = DelegatingBindingTrace(bindingContext, "For code fragment analysis")
when (val contentElement = codeFragment.getContentElement()) {
is KtExpression -> {
val expectedType = codeFragment.getUserData(EXPECTED_TYPE_KEY) ?: TypeUtils.NO_EXPECTED_TYPE
contentElement.analyzeInContext(
scope,
trace = bindingTrace,
dataFlowInfo = dataFlowInfo,
expectedType = expectedType,
expressionTypingServices = expressionTypingServices
)
analyzeControlFlow(resolveSession, contentElement, bindingTrace)
bindingTrace.record(USED_AS_EXPRESSION, contentElement.lastBlockStatementOrThis())
}
is KtTypeReference -> {
val context = TypeResolutionContext(
scope, bindingTrace,
true, true, codeFragment.suppressDiagnosticsInDebugMode()
).noBareTypes()
typeResolver.resolvePossiblyBareType(context, contentElement)
}
}
return bindingTrace
}
private data class ContextInfo(val bindingContext: BindingContext, val scope: LexicalScope, val dataFlowInfo: DataFlowInfo)
private fun analyzeCodeFragmentContext(codeFragment: KtCodeFragment, bodyResolveMode: BodyResolveMode): ContextInfo {
fun resolutionFactory(element: KtElement): BindingContext {
return resolveElementCache.resolveToElement(element, bodyResolveMode)
}
val context = refineContextElement(codeFragment.context)
val info = getContextInfo(context, ::resolutionFactory)
return info.copy(scope = enrichScopeWithImports(info.scope, codeFragment))
}
private tailrec fun getContextInfo(context: PsiElement?, resolutionFactory: (KtElement) -> BindingContext): ContextInfo {
var bindingContext: BindingContext = BindingContext.EMPTY
var dataFlowInfo: DataFlowInfo = DataFlowInfo.EMPTY
var scope: LexicalScope? = null
when (context) {
is KtPrimaryConstructor -> {
val containingClass = context.getContainingClassOrObject()
val resolutionResult = getClassDescriptor(containingClass, resolutionFactory)
if (resolutionResult != null) {
bindingContext = resolutionResult.bindingContext
scope = resolutionResult.descriptor.scopeForInitializerResolution
}
}
is KtSecondaryConstructor -> {
val expression = (context.bodyExpression ?: context.getDelegationCall().calleeExpression) as? KtExpression
if (expression != null) {
bindingContext = resolutionFactory(expression)
scope = bindingContext[BindingContext.LEXICAL_SCOPE, expression]
}
}
is KtClassOrObject -> {
val resolutionResult = getClassDescriptor(context, resolutionFactory)
if (resolutionResult != null) {
bindingContext = resolutionResult.bindingContext
scope = resolutionResult.descriptor.scopeForMemberDeclarationResolution
}
}
is KtFunction -> {
val bindingContextForFunction = resolutionFactory(context)
val functionDescriptor = bindingContextForFunction[BindingContext.FUNCTION, context]
if (functionDescriptor != null) {
bindingContext = bindingContextForFunction
@Suppress("NON_TAIL_RECURSIVE_CALL")
val outerScope = getContextInfo(context.getParentOfType<KtDeclaration>(true), resolutionFactory).scope
val localRedeclarationChecker = LocalRedeclarationChecker.DO_NOTHING
scope = FunctionDescriptorUtil.getFunctionInnerScope(outerScope, functionDescriptor, localRedeclarationChecker)
}
}
is KtFile -> {
bindingContext = resolveSession.bindingContext
scope = resolveSession.fileScopeProvider.getFileResolutionScope(context)
}
is KtElement -> {
bindingContext = resolutionFactory(context)
scope = context.getResolutionScope(bindingContext)
dataFlowInfo = bindingContext.getDataFlowInfoAfter(context)
}
}
if (scope == null) {
val parentDeclaration = context?.getParentOfTypes3<KtDeclaration, KtFile, KtExpression>()
if (parentDeclaration != null) {
return getContextInfo(parentDeclaration, resolutionFactory)
}
}
return ContextInfo(bindingContext, scope ?: createEmptyScope(resolveSession.moduleDescriptor), dataFlowInfo)
}
private data class ClassResolutionResult(val bindingContext: BindingContext, val descriptor: ClassDescriptorWithResolutionScopes)
private fun getClassDescriptor(
classOrObject: KtClassOrObject,
resolutionFactory: (KtElement) -> BindingContext
): ClassResolutionResult? {
val bindingContext: BindingContext
val classDescriptor: ClassDescriptor?
if (!KtPsiUtil.isLocal(classOrObject)) {
bindingContext = resolveSession.bindingContext
classDescriptor = resolveSession.getClassDescriptor(classOrObject, NoLookupLocation.FROM_IDE)
} else {
bindingContext = resolutionFactory(classOrObject)
classDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, classOrObject] as ClassDescriptor?
}
return (classDescriptor as? ClassDescriptorWithResolutionScopes)?.let { ClassResolutionResult(bindingContext, it) }
}
private fun refineContextElement(context: PsiElement?): KtElement? {
return when (context) {
is KtParameter -> context.getParentOfType<KtFunction>(true)
is KtProperty -> context.delegateExpressionOrInitializer
is KtConstructor<*> -> context
is KtFunctionLiteral -> context.bodyExpression?.statements?.lastOrNull()
is KtDeclarationWithBody -> context.bodyExpression
is KtBlockExpression -> context.statements.lastOrNull()
else -> null
} ?: context as? KtElement
}
private fun enrichScopeWithImports(scope: LexicalScope, codeFragment: KtCodeFragment): LexicalScope {
val additionalImportingScopes = mutableListOf<ImportingScope>()
val externalDescriptors = codeFragment.externalDescriptors ?: emptyList()
if (externalDescriptors.isNotEmpty()) {
additionalImportingScopes += ExplicitImportsScope(externalDescriptors)
}
val importList = codeFragment.importsAsImportList()
if (importList != null && importList.imports.isNotEmpty()) {
additionalImportingScopes += createImportScopes(importList)
}
if (additionalImportingScopes.isNotEmpty()) {
return scope.addImportingScopes(additionalImportingScopes)
}
return scope
}
private fun createImportScopes(importList: KtImportList): List<ImportingScope> {
return importList.imports.mapNotNull {
qualifierResolver.processImportReference(
it, resolveSession.moduleDescriptor, resolveSession.trace,
excludedImportNames = emptyList(), packageFragmentForVisibilityCheck = null
)
}
}
private fun createEmptyScope(moduleDescriptor: ModuleDescriptor): LexicalScope {
return LexicalScope.Base(ImportingScope.Empty, moduleDescriptor)
}
companion object {
val EXPECTED_TYPE_KEY = Key<KotlinType>("EXPECTED_TYPE")
}
}
| apache-2.0 | e1ad12bfb17e72dacbdfd134cbbeca52 | 46.365297 | 158 | 0.697677 | 6.016821 | false | false | false | false |
andrewoma/kommon | src/main/kotlin/com/github/andrewoma/kommon/io/LineReaderWithPosition.kt | 1 | 5243 | /*
* Copyright (c) 2014 Andrew O'Malley
*
* 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 com.github.andrewoma.kommon.io
import java.io.InputStream
import java.io.PushbackInputStream
import java.nio.charset.Charset
data class LineWithPosition(val start: Int, val end: Int, val line: String, val delimiter: String)
/**
* LineReaderWithPosition is a line reader that records the byte positions of the line in the stream
* as well as the delimiters for line endings.
*
* Delimiters allow the file to be faithfully reconstructed.
*
* Byte positions allows for resuming reading a stream from a given position. e.g. tailing logs as they are written
*
* LineReaderWithPosition assumes the input stream is buffered.
*/
class LineReaderWithPosition(inputStream: InputStream, val lineBufferSize: Int = 8192, val charSet: Charset = Charsets.UTF_8) {
private enum class Eof { NotFound, Found, Reported }
private companion object {
const val CR = '\r'.toInt()
const val LF = '\n'.toInt()
const val CR_DELIM = "\r"
const val LF_DELIM = "\n"
const val CR_LF_DELIM = "\r\n"
}
private val buffer = ByteArray(lineBufferSize)
private var result: ByteArray? = null
private var start = 0
private var end = 0
private var bufferPos = 0
private var eof = Eof.NotFound
private val inputStream = PushbackInputStream(inputStream)
fun readLine(): LineWithPosition? {
check(eof != Eof.Reported) { "Attempt to read past EOF" }
if (eof == Eof.Found) {
eof = Eof.Reported
return null
}
while (true) {
val char = inputStream.read()
// EOF
if (char == -1) {
return if (start == end) {
eof = Eof.Reported
null
} else {
eof = Eof.Found
result("")
}
}
// Character read
end++
// EOL
if (char == CR || char == LF) {
val delimiter = if (char == CR) {
val next = inputStream.read()
if (next == LF) {
end++
CR_LF_DELIM
} else {
if (next != -1) {
inputStream.unread(next)
}
CR_DELIM
}
} else {
LF_DELIM
}
return result(delimiter)
} else {
// Append the character to temporary buffers
append(char.toByte())
}
}
}
private fun append(byte: Byte) {
if (bufferPos == lineBufferSize) {
// Buffer full
if (result != null) {
val newResult = ByteArray(result!!.size + lineBufferSize)
System.arraycopy(result!!, 0, newResult, 0, result!!.size)
System.arraycopy(buffer, 0, newResult, result!!.size, lineBufferSize)
result = newResult
} else {
result = ByteArray(lineBufferSize)
System.arraycopy(buffer, 0, result!!, 0, lineBufferSize)
}
bufferPos = 0
}
buffer[bufferPos] = byte
bufferPos++
}
private fun result(delimiter: String): LineWithPosition? {
val string = when {
result == null -> String(buffer, 0, bufferPos, charSet)
bufferPos == 0 -> String(result!!, charSet)
else -> {
val newResult = ByteArray(result!!.size + bufferPos)
System.arraycopy(result!!, 0, newResult, 0, result!!.size)
System.arraycopy(buffer, 0, newResult, result!!.size, bufferPos)
String(newResult, charSet)
}
}
val line = LineWithPosition(start, end, string, delimiter)
start = end
bufferPos = 0
result = null
return line
}
fun asSequence(): Sequence<LineWithPosition> {
return generateSequence { this.readLine() }
}
}
| mit | 266b2d30db916568bcfd6de53a0e9d5e | 33.267974 | 127 | 0.571619 | 4.64805 | false | false | false | false |
ingokegel/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GrNamedVariantLabelsInspection.kt | 12 | 2384 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInspection.bugs
import com.intellij.psi.CommonClassNames
import com.intellij.psi.util.InheritanceUtil
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnnotationUtil
import org.jetbrains.plugins.groovy.transformations.impl.namedVariant.GROOVY_TRANSFORM_NAMED_DELEGATE
import org.jetbrains.plugins.groovy.transformations.impl.namedVariant.GROOVY_TRANSFORM_NAMED_PARAM
import org.jetbrains.plugins.groovy.transformations.impl.namedVariant.NamedVariantTransformationSupport
class GrNamedVariantLabelsInspection : BaseInspection() {
override fun buildErrorString(vararg args: Any?): String {
return GroovyBundle.message("inspection.message.label.name.ref.not.supported.by.0", args[0])
}
override fun buildVisitor(): BaseInspectionVisitor = object : BaseInspectionVisitor() {
override fun visitCallExpression(callExpression: GrCallExpression) {
val namedArguments = callExpression.namedArguments.takeIf { it.isNotEmpty() } ?: return
val resolvedMethod = callExpression.resolveMethod() as? GrMethod ?: return
val mapParameter = resolvedMethod.parameters.singleOrNull { InheritanceUtil.isInheritor(it.type, CommonClassNames.JAVA_UTIL_MAP) } ?: return
val definedNames =
mapParameter.annotations
.filter { it.hasQualifiedName(GROOVY_TRANSFORM_NAMED_PARAM) || it.hasQualifiedName(GROOVY_TRANSFORM_NAMED_DELEGATE) }
.mapNotNullTo(HashSet()) { GrAnnotationUtil.inferStringAttribute(it, "value") }.takeIf { it.size > 0 } ?: return
for (namedArg in namedArguments) {
val label = namedArg.label ?: continue
if (namedArg?.labelName in definedNames) continue
val reason = if (resolvedMethod is NamedVariantTransformationSupport.NamedVariantGeneratedMethod) "@NamedVariant" else "@NamedParam"
registerError(label, reason)
}
}
}
} | apache-2.0 | 53098ae70a3f00c47fb4b30d50f4e881 | 60.153846 | 146 | 0.788171 | 4.629126 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/utils.kt | 4 | 1461 | // 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.gradleTooling
import java.util.*
fun Class<*>.getMethodOrNull(name: String, vararg parameterTypes: Class<*>) =
try {
getMethod(name, *parameterTypes)
} catch (e: Exception) {
null
}
fun Class<*>.getDeclaredMethodOrNull(name: String, vararg parameterTypes: Class<*>) =
try {
getDeclaredMethod(name, *parameterTypes)?.also { it.isAccessible = true }
} catch (e: Exception) {
null
}
fun ClassLoader.loadClassOrNull(name: String): Class<*>? {
return try {
loadClass(name)
} catch (e: LinkageError) {
return null
} catch (e: ClassNotFoundException) {
return null
}
}
fun compilationFullName(simpleName: String, classifier: String?) =
if (classifier != null) classifier + simpleName.capitalize() else simpleName
fun String.capitalize(): String {
/* Default implementation as suggested by 'capitalize' deprecation */
if (KotlinVersion.CURRENT.isAtLeast(1, 5)) {
return this.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
}
/* Fallback implementation for older Kotlin versions */
if (this.isEmpty()) return this
@Suppress("DEPRECATION")
return this[0].toUpperCase() + this.drop(1)
}
| apache-2.0 | bed092cf24afcb6f3e4a7ce765b1db1c | 32.204545 | 158 | 0.676934 | 4.348214 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/CollectionEntity.kt | 2 | 1952 | // 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.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
interface CollectionFieldEntity : WorkspaceEntity {
val versions: Set<Int>
val names: List<String>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : CollectionFieldEntity, ModifiableWorkspaceEntity<CollectionFieldEntity>, ObjBuilder<CollectionFieldEntity> {
override var entitySource: EntitySource
override var versions: MutableSet<Int>
override var names: MutableList<String>
}
companion object : Type<CollectionFieldEntity, Builder>() {
operator fun invoke(versions: Set<Int>,
names: List<String>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): CollectionFieldEntity {
val builder = builder()
builder.versions = versions.toMutableWorkspaceSet()
builder.names = names.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: CollectionFieldEntity, modification: CollectionFieldEntity.Builder.() -> Unit) = modifyEntity(
CollectionFieldEntity.Builder::class.java, entity, modification)
//endregion
| apache-2.0 | fbbd1b7bdb0683ac598f0f3c0ecf2bbc | 39.666667 | 140 | 0.769467 | 5.318801 | false | false | false | false |
rubengees/ktask | sample/src/main/kotlin/com/rubengees/ktask/sample/Main.kt | 1 | 1397 | @file:JvmName("Main")
package com.rubengees.ktask.sample
import com.rubengees.ktask.retrofit.asyncRetrofitTask
import com.rubengees.ktask.util.TaskBuilder
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
/**
* The main function. It loads the trending Kotlin repositories asynchronously and prints them on the console.
*/
fun main(args: Array<String>) {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
val api = retrofit.create(GitHubApi::class.java)
TaskBuilder.asyncRetrofitTask<RepositoryInfo>()
.onStart {
println("Asynchronous loading started!\n")
}
.onSuccess {
println(it.repositories.map {
"${it.name} by ${it.owner.name} with ${it.stars} ${if (it.stars == 1) "star" else "stars"}."
}.joinToString(separator = "\n", prefix = "These are the trending Kotlin repositories of the week:\n\n"))
}
.onError {
println("Error retrieving: ${it.message}")
}
.onFinish {
print("\nAsynchronous loading finished!")
System.exit(0)
}
.build()
.execute(api.mostStarredRepositories(Utils.query()))
}
| mit | c04d30ada76c1e9711120867ad084c87 | 33.925 | 121 | 0.599857 | 4.449045 | false | false | false | false |
komunumo/komunumo-backend | src/main/kotlin/ch/komunumo/server/business/event/control/EventService.kt | 1 | 2004 | /*
* Komunumo – Open Source Community Manager
* Copyright (C) 2017 Java User Group Switzerland
*
* 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 ch.komunumo.server.business.event.control
import ch.komunumo.server.PersistenceManager
import ch.komunumo.server.business.event.entity.Event
import ch.komunumo.server.business.generateNewUniqueId
import java.util.ConcurrentModificationException
object EventService {
private val events: MutableMap<String, Event> = PersistenceManager.createPersistedMap("events")
fun create(event: Event): String {
val id = generateNewUniqueId(events.keys)
val version = event.hashCode()
events[id] = event.copy(id = id, version = version)
return id
}
fun readAll(): List<Event> {
return events.values.toList()
}
fun readById(id: String): Event {
return events.getValue(id)
}
fun update(event: Event): Event {
val id = event.id ?: throw IllegalStateException("The event has no id!")
val oldEvent = readById(id)
if (oldEvent.version != event.version) {
throw ConcurrentModificationException("The event with id '$id' was modified concurrently!")
}
val version = event.hashCode()
val newEvent = event.copy(id = id, version = version)
events[id] = newEvent
return newEvent
}
}
| agpl-3.0 | d9ac81ee814cf2618856fcced9bc393f | 34.122807 | 103 | 0.700799 | 4.342733 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/waikato/WaikatoCardData.kt | 1 | 5834 | /*
* WaikatoCardTransitData.kt
*
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.waikato
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.classic.ClassicCard
import au.id.micolous.metrodroid.card.classic.ClassicCardTransitFactory
import au.id.micolous.metrodroid.card.classic.ClassicSector
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.Daystamp
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.transit.*
import au.id.micolous.metrodroid.util.ImmutableByteArray
private val ROTORUA_CARD_INFO = CardInfo(
name = "SmartRide (Rotorua)",
locationId = R.string.location_rotorua,
cardType = CardType.MifareClassic,
imageId = R.drawable.rotorua,
imageAlphaId = R.drawable.iso7810_id1_alpha,
region = TransitRegion.NEW_ZEALAND,
preview = true)
private val BUSIT_CARD_INFO = CardInfo(name = "BUSIT",
locationId = R.string.location_waikato,
cardType = CardType.MifareClassic,
imageId = R.drawable.busitcard,
imageAlphaId = R.drawable.iso7810_id1_alpha,
region = TransitRegion.NEW_ZEALAND,
preview = true)
private fun formatSerial(serial: Long) = serial.toString(16)
private fun getSerial(card: ClassicCard) = card[1, 0].data.byteArrayToLong(4, 4)
private fun getName(card: ClassicCard) =
when {
card[0, 1].data.sliceArray(0..4) == ImmutableByteArray.fromASCII("Panda") -> BUSIT_CARD_INFO.name
else -> ROTORUA_CARD_INFO.name
}
private fun parseTimestamp(input: ImmutableByteArray, off: Int): TimestampFull {
val d = input.getBitsFromBuffer(off * 8, 5)
val m = input.getBitsFromBuffer(off * 8 + 5, 4)
val y = input.getBitsFromBuffer(off * 8 + 9, 4) + 2007
val hm = input.getBitsFromBuffer(off * 8 + 13, 11)
return TimestampFull(tz = MetroTimeZone.AUCKLAND, year = y, month = m - 1, day = d, hour = hm / 60,
min = hm % 60)
}
private fun parseDate(input: ImmutableByteArray, off: Int): Daystamp {
val d = input.getBitsFromBuffer(off * 8, 5)
val m = input.getBitsFromBuffer(off * 8 + 5, 4)
val y = input.getBitsFromBuffer(off * 8 + 9, 7) + 1991
return Daystamp(year = y, month = m - 1, day = d)
}
@Parcelize
private data class WaikatoCardTrip(override val startTimestamp: TimestampFull,
private val mCost: Int, private val mA: Int, private val mB: Int,
override val mode: Mode) : Trip() {
override val fare get() = if (mCost == 0 && mode == Mode.TICKET_MACHINE) null else TransitCurrency.NZD(mCost)
override fun getRawFields(level: TransitData.RawLevel): String? = "${mA.toString(16)}/${mB.toString(16)}"
companion object {
fun parse(sector: ImmutableByteArray, mode: Mode): WaikatoCardTrip? {
if (sector.isAllZero() || sector.isAllFF())
return null
val timestamp = parseTimestamp(sector, 1)
val cost = sector.byteArrayToIntReversed(5, 2)
val a = sector[0].toInt() and 0xff
val b = sector[4].toInt() and 0xff
return WaikatoCardTrip(startTimestamp = timestamp, mCost = cost, mA = a, mB = b, mode = mode)
}
}
}
@Parcelize
private data class WaikatoCardTransitData internal constructor(
private val mSerial: Long,
private val mBalance: Int,
override val trips: List<WaikatoCardTrip>,
override val cardName: String,
private val mLastTransactionDate: Daystamp) : TransitData() {
override val serialNumber get() = formatSerial(mSerial)
override val balance get() = TransitCurrency.NZD(mBalance)
}
object WaikatoCardTransitFactory : ClassicCardTransitFactory {
override val allCards get() = listOf(ROTORUA_CARD_INFO, BUSIT_CARD_INFO)
override fun parseTransitIdentity(card: ClassicCard) = TransitIdentity(
getName(card), formatSerial(getSerial(card)))
override fun parseTransitData(card: ClassicCard): TransitData {
val balSec = if (card[0][1].data[5].toInt() and 0x10 == 0) 1 else 5
val lastTrip = WaikatoCardTrip.parse(card[balSec + 2, 0].data.sliceOffLen(0, 7), Trip.Mode.BUS)
val lastRefill = WaikatoCardTrip.parse(card[balSec + 2, 0].data.sliceOffLen(7, 7), Trip.Mode.TICKET_MACHINE)
return WaikatoCardTransitData(
mSerial = getSerial(card),
mBalance = card[balSec + 1, 1].data.byteArrayToIntReversed(9, 2),
trips = listOfNotNull(lastRefill, lastTrip),
cardName = getName(card),
mLastTransactionDate = parseDate(card[balSec + 1, 1].data, 7)
)
}
override fun earlyCheck(sectors: List<ClassicSector>) =
sectors[0][1].data.sliceArray(0..4) in listOf(ImmutableByteArray.fromASCII("Valid"),
ImmutableByteArray.fromASCII("Panda")) &&
sectors[1][0].data.byteArrayToInt(2, 2) == 0x4850
override val earlySectors get() = 2
}
| gpl-3.0 | 849bc4b9368e459b74b005822e98bf1e | 42.537313 | 116 | 0.676208 | 3.891928 | false | false | false | false |
GunoH/intellij-community | plugins/eclipse/src/org/jetbrains/idea/eclipse/importer/EclipseCodeStyleSchemeImporter.kt | 8 | 4612 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.eclipse.importer
import com.intellij.application.options.ImportSchemeChooserDialog
import com.intellij.openapi.options.SchemeFactory
import com.intellij.openapi.options.SchemeImportException
import com.intellij.openapi.options.SchemeImporter
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.codeStyle.CodeStyleScheme
import com.intellij.psi.codeStyle.CodeStyleSettings
import org.jetbrains.idea.eclipse.codeStyleMapping.buildEclipseCodeStyleMappingTo
import org.jetbrains.idea.eclipse.importer.EclipseXmlProfileReader.OptionHandler
import java.io.IOException
import java.io.InputStream
class EclipseCodeStyleSchemeImporter : SchemeImporter<CodeStyleScheme>, EclipseXmlProfileElements {
override fun getSourceExtensions(): Array<String> = arrayOf("xml")
override fun importScheme(project: Project,
selectedFile: VirtualFile,
currentScheme: CodeStyleScheme,
schemeFactory: SchemeFactory<out CodeStyleScheme>): CodeStyleScheme? {
val (selectedName, selectedScheme) = ImportSchemeChooserDialog.selectOrCreateTargetScheme(project, currentScheme, schemeFactory,
*selectedFile.readEclipseXmlProfileNames())
?: return null
importCodeStyleSettings(selectedFile, selectedName, selectedScheme.codeStyleSettings)
return selectedScheme
}
companion object {
@JvmStatic
@Throws(SchemeImportException::class)
fun importCodeStyleSettings(external: Map<String, String>, codeStyleSettings: CodeStyleSettings) {
val mapping = buildEclipseCodeStyleMappingTo(codeStyleSettings)
mapping.importSettings(external)
}
@JvmStatic
@Throws(SchemeImportException::class)
fun importCodeStyleSettings(file: VirtualFile, profileName: String?, codeStyleSettings: CodeStyleSettings) {
val external = file.readEclipseXmlProfileOptions(profileName)
importCodeStyleSettings(external, codeStyleSettings)
}
@JvmStatic
@Throws(SchemeImportException::class)
fun VirtualFile.readEclipseXmlProfileNames() : Array<String> {
val names: MutableSet<String> = mutableSetOf()
this.readEclipseXmlProfile(object : OptionHandler {
override fun handleOption(eclipseKey: String, value: String) {}
override fun handleName(name: String?) {
if (name != null) {
names.add(name)
}
}
})
return names.toTypedArray()
}
/**
* @param selectedProfileName Only read settings under this profile. Reads every setting in the file if null.
*/
@JvmStatic
@Throws(SchemeImportException::class)
fun VirtualFile.readEclipseXmlProfileOptions(selectedProfileName: String? = null): Map<String, String> =
this.getInputStreamAndWrapIOException().readEclipseXmlProfileOptions(selectedProfileName)
@JvmStatic
@Throws(SchemeImportException::class)
fun InputStream.readEclipseXmlProfileOptions(selectedProfileName: String? = null): Map<String, String> {
val settings = mutableMapOf<String, String>()
this.readEclipseXmlProfile(object : OptionHandler {
var currentProfileName: String? = null
override fun handleOption(eclipseKey: String, value: String) {
if (selectedProfileName == null || currentProfileName != null && currentProfileName == selectedProfileName) {
settings[eclipseKey] = value
}
}
override fun handleName(name: String?) {
currentProfileName = name
}
})
return settings
}
/**
* @throws SchemeImportException
*/
@JvmStatic
@Throws(SchemeImportException::class)
fun VirtualFile.readEclipseXmlProfile(handler: OptionHandler) {
this.getInputStreamAndWrapIOException().readEclipseXmlProfile(handler)
}
@JvmStatic
@Throws(SchemeImportException::class)
fun InputStream.readEclipseXmlProfile(handler: OptionHandler) {
this.use { EclipseXmlProfileReader(handler).readSettings(it) }
}
private fun VirtualFile.getInputStreamAndWrapIOException() =
try {
this.inputStream
}
catch (e: IOException) {
throw SchemeImportException(e)
}
}
} | apache-2.0 | c916bda366294115a349ae29c836d72e | 39.823009 | 137 | 0.711188 | 4.964478 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/kdoc/AbstractKDocTypingTest.kt | 4 | 1077 | // 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.kdoc
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import java.io.File
abstract class AbstractKDocTypingTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor() = KotlinLightProjectDescriptor.INSTANCE
protected fun doTest(fileName: String) {
val file = File(fileName).relativeTo(File(testDataPath))
myFixture.configureByFile(file.path)
val textToType = InTextDirectivesUtils.findStringWithPrefixes(myFixture.file.text, "// TYPE:")
if (textToType == null) {
throw IllegalArgumentException("Cannot find directive TYPE in input file")
}
myFixture.type(textToType)
myFixture.checkResultByFile(file.path + ".after")
}
}
| apache-2.0 | f1dd74743e4b24021f3a026749cbcc3c | 45.826087 | 158 | 0.761374 | 4.963134 | false | true | false | false |
KotlinBy/bkug.by | data/src/main/kotlin/by/bkug/data/Meetup4.kt | 1 | 5960 | package by.bkug.data
import org.intellij.lang.annotations.Language
@Language("markdown")
val meetup4 = """
Новая встреча нашего сообщества состоится 13 июня, как обычно в [Space](http://eventspace.by).
## Java Day 2017
Совсем скоро, 3 июня, пройдет [Java Day 2017](http://javaday.by/), и у нас есть три хорошие новости по этому поводу:
1. На JavaDay будет два доклада про Kotlin;
2. Мы будем организовывать стенд BKUG и разыгрывать призы, [начать зарабатывать баллы](https://github.com/BelarusKUG/JavaDay-2017) можно уже сейчас;
3. У нас есть промокод для сообщества на скидку 15%: `BKUG_JAVADAY_15`
## Программа:
### Приветственный кофе (18:40 - 19:00)
Вас ждут печеньки, чай и кофе.
### Kotlin in Action - Евгений Ковалев (19:00 - 19:50)
Доклад ориентирован на разработчиков, которые уже знакомы с синтаксисом языка, но до сих пор не пробовали писать реальный код на нем. Евгений расскажет о преимуществах от перехода на Котлин, поделится собственным опытом миграции проекта с джавы с примерами из кода, а также расскажет, как убедить своих коллег и заказчиков на проекте перейти на новый язык.
 Android-разработчик с 5+ лет продакшен-опыта, написавший приложения с суммарной аудиторией более 500K активных пользователей в месяц.
### DSL in Kotlin - Александр Сальников (20:00 - 20:50)
Александр рассмотрит особенности языка, которые позволяют написать [DSL](https://en.wikipedia.org/wiki/Domain-specific_language) на Kotlin. А также, напишет свой DSL, который облегчит подготовку данных для тестов.

* **Дата проведения**: 13 июня
* **Время**: 19:00–21:00
* **Место проведения**: ул. Октябрьская, 16А – EventSpace. Парковка и вход через ул. Октябрьскую, 10б.
[Добавить в Google Calendar](http://www.google.com/calendar/event?action=TEMPLATE&dates=20170613T160000Z%2F20170613T180000Z&text=BKUG%20%234&location=%D0%9C%D0%B8%D0%BD%D1%81%D0%BA%2C%20%D1%83%D0%BB.%20%D0%9E%D0%BA%D1%82%D1%8F%D0%B1%D1%80%D1%8C%D1%81%D0%BA%D0%B0%D1%8F%2016%D0%B0%2C%20EventSpace&details=%D0%90%D0%BD%D0%BE%D0%BD%D1%81%20%D0%BD%D0%B0%20%D1%81%D0%B0%D0%B9%D1%82%D0%B5%20%D1%81%D0%BE%D0%BE%D0%B1%D1%89%D0%B5%D1%81%D1%82%D0%B2%D0%B0%20https%3A%2F%2Fbkug.by%2F2017%2F05%2F30%2Fanons-bkug-4%2F)
Для участия во встрече необходима предварительная [регистрация](https://goo.gl/forms/VZ2YwzVoONxWrmif1).
Все участники митапа которые зарегистрировались и отметились на входе (на ресепшене) участвуют в розыгрыше книги "Kotlin in Action" которая пройдет после последнего доклада. Не уходите, книгу можно получить только лично во время митапа! :)
`[huge_it_maps id="2"]`
""".trimIndent()
@Language("markdown")
val meetup4Report = """
Наш четвертый митап собрал примерно 90 участников при 160 регистрациях. Мы рады такой большой аудитории и уже планируем июльский митап. А пока видео и фото с прошедшего митапа:
## Kotlin in Action – Евгений Ковалев
https://www.youtube.com/watch?v=9zIfl_HT49A
[slides google docs](https://docs.google.com/presentation/d/16UX7LY5hx0odMm2gvcm3LnjAWJbchTgysYsLMhXgkis/edit)
[slides pdf](https://bkug.by/wp-content/uploads/2017/06/Kotlin-in-action-BKUG.pdf)
## DSL in Kotlin – Александр Сальников
https://www.youtube.com/watch?v=xIoHJlXziXk
[slides google docs](https://docs.google.com/presentation/d/1X2QAGV_xjcEWgQkABcu-_IztR6OO48s-fJs37Hv2Cso/edit)
[slides pdf](https://bkug.by/wp-content/uploads/2017/06/DSL-BKUG.pdf)
## Kotlin Future Features
На [BKUG #3](https://bkug.by/2017/03/25/otchet-o-bkug-3/) который по совместительству был Kotlin 1.1 Event у вас была возможность проголосовать за фичи, которые вы бы хотели видеть в будущих версиях Kotlin. И вот, буквально через час после окончания митапа стали доступны результаты голосования: [https://blog.jetbrains.com/kotlin/2017/06/kotlin-future-features-survey-results/](https://blog.jetbrains.com/kotlin/2017/06/kotlin-future-features-survey-results/). Пожалуй аналитику результатов оставим вам, как нам кажется это отличная тема за чашечкой кофе или чего покрепче! :)
## Фотоотчет
[gallery link="file" ids="307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329"]
""".trimIndent()
| gpl-3.0 | 0f195c8b2819335d00d48ea79810ce7f | 56.932432 | 579 | 0.770236 | 2.02695 | false | false | false | false |
ktorio/ktor | ktor-network/jvm/src/io/ktor/network/selector/SelectorManagerSupport.kt | 1 | 5587 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.network.selector
import io.ktor.utils.io.errors.*
import kotlinx.coroutines.*
import java.nio.channels.*
import java.nio.channels.spi.*
import kotlin.coroutines.*
/**
* Base class for NIO selector managers
*/
public abstract class SelectorManagerSupport internal constructor() : SelectorManager {
public final override val provider: SelectorProvider = SelectorProvider.provider()
/**
* Number of pending selectable.
*/
protected var pending: Int = 0
/**
* Number of cancelled keys.
*/
protected var cancelled: Int = 0
/**
* Publish current [selectable] interest, any thread
*/
protected abstract fun publishInterest(selectable: Selectable)
public final override suspend fun select(selectable: Selectable, interest: SelectInterest) {
val interestedOps = selectable.interestedOps
val flag = interest.flag
if (selectable.isClosed) selectableIsClosed()
if (interestedOps and flag == 0) selectableIsInvalid(interestedOps, flag)
suspendCancellableCoroutine<Unit> { continuation ->
continuation.invokeOnCancellation {
// TODO: We've got a race here (and exception erasure)!
}
selectable.suspensions.addSuspension(interest, continuation)
if (!continuation.isCancelled) {
publishInterest(selectable)
}
}
}
/**
* Handle selected keys clearing [selectedKeys] set
*/
protected fun handleSelectedKeys(selectedKeys: MutableSet<SelectionKey>, keys: Set<SelectionKey>) {
val selectedCount = selectedKeys.size
pending = keys.size - selectedCount
cancelled = 0
if (selectedCount > 0) {
val iter = selectedKeys.iterator()
while (iter.hasNext()) {
val k = iter.next()
handleSelectedKey(k)
iter.remove()
}
}
}
/**
* Handles particular selected key
*/
protected fun handleSelectedKey(key: SelectionKey) {
try {
val readyOps = key.readyOps()
val interestOps = key.interestOps()
val subject = key.subject
if (subject == null) {
key.cancel()
cancelled++
} else {
subject.suspensions.invokeForEachPresent(readyOps) { resume(Unit) }
val newOps = interestOps and readyOps.inv()
if (newOps != interestOps) {
key.interestOps(newOps)
}
if (newOps != 0) {
pending++
}
}
} catch (cause: Throwable) {
// cancelled or rejected on resume?
key.cancel()
cancelled++
key.subject?.let { subject ->
cancelAllSuspensions(subject, cause)
key.subject = null
}
}
}
/**
* Applies selectable's current interest (should be invoked in selection thread)
*/
protected fun applyInterest(selector: Selector, selectable: Selectable) {
try {
val channel = selectable.channel
val key = channel.keyFor(selector)
val ops = selectable.interestedOps
if (key == null) {
if (ops != 0) {
channel.register(selector, ops, selectable)
}
} else {
if (key.interestOps() != ops) {
key.interestOps(ops)
}
}
if (ops != 0) {
pending++
}
} catch (cause: Throwable) {
selectable.channel.keyFor(selector)?.cancel()
cancelAllSuspensions(selectable, cause)
}
}
/**
* Notify selectable's closure
*/
protected fun notifyClosedImpl(selector: Selector, key: SelectionKey, attachment: Selectable) {
cancelAllSuspensions(attachment, ClosedChannelException())
key.subject = null
selector.wakeup()
}
/**
* Cancel all selectable's suspensions with the specified exception
*/
protected fun cancelAllSuspensions(attachment: Selectable, cause: Throwable) {
attachment.suspensions.invokeForEachPresent {
resumeWithException(cause)
}
}
/**
* Cancel all suspensions with the specified exception, reset all interests
*/
protected fun cancelAllSuspensions(selector: Selector, cause: Throwable?) {
val currentCause = cause ?: ClosedSelectorCancellationException()
selector.keys().forEach { key ->
try {
if (key.isValid) key.interestOps(0)
} catch (ignore: CancelledKeyException) {
}
(key.attachment() as? Selectable)?.let { cancelAllSuspensions(it, currentCause) }
key.cancel()
}
}
private var SelectionKey.subject: Selectable?
get() = attachment() as? Selectable
set(newValue) {
attach(newValue)
}
public class ClosedSelectorCancellationException : CancellationException("Closed selector")
}
private fun selectableIsClosed(): Nothing {
throw IOException("Selectable is already closed")
}
private fun selectableIsInvalid(interestedOps: Int, flag: Int): Nothing {
error("Selectable is invalid state: $interestedOps, $flag")
}
| apache-2.0 | e58e6253a6ca1a2061cd7aae3bacc593 | 29.36413 | 118 | 0.583855 | 4.992851 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/platform/gui/AndroidCanvas.kt | 1 | 5244 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.platform.gui
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.text.TextPaint
import org.isoron.uhabits.utils.InterfaceUtils.getFontAwesome
class AndroidCanvas : Canvas {
lateinit var context: Context
lateinit var innerCanvas: android.graphics.Canvas
var innerBitmap: Bitmap? = null
var innerDensity = 1.0
var innerWidth = 0
var innerHeight = 0
var mHeight = 15
var paint = Paint().apply {
isAntiAlias = true
}
var textPaint = TextPaint().apply {
isAntiAlias = true
textAlign = Paint.Align.CENTER
}
var textBounds = Rect()
private fun Double.toDp() = (this * innerDensity).toFloat()
override fun setColor(color: Color) {
paint.color = color.toInt()
textPaint.color = color.toInt()
}
override fun drawLine(x1: Double, y1: Double, x2: Double, y2: Double) {
innerCanvas.drawLine(
x1.toDp(),
y1.toDp(),
x2.toDp(),
y2.toDp(),
paint,
)
}
override fun drawText(text: String, x: Double, y: Double) {
innerCanvas.drawText(
text,
x.toDp(),
y.toDp() + 0.6f * mHeight,
textPaint,
)
}
override fun fillRect(x: Double, y: Double, width: Double, height: Double) {
paint.style = Paint.Style.FILL
rect(x, y, width, height)
}
override fun fillRoundRect(
x: Double,
y: Double,
width: Double,
height: Double,
cornerRadius: Double,
) {
paint.style = Paint.Style.FILL
innerCanvas.drawRoundRect(
x.toDp(),
y.toDp(),
(x + width).toDp(),
(y + height).toDp(),
cornerRadius.toDp(),
cornerRadius.toDp(),
paint,
)
}
override fun drawRect(x: Double, y: Double, width: Double, height: Double) {
paint.style = Paint.Style.STROKE
rect(x, y, width, height)
}
private fun rect(x: Double, y: Double, width: Double, height: Double) {
innerCanvas.drawRect(
x.toDp(),
y.toDp(),
(x + width).toDp(),
(y + height).toDp(),
paint,
)
}
override fun getHeight(): Double {
return innerHeight / innerDensity
}
override fun getWidth(): Double {
return innerWidth / innerDensity
}
override fun setFont(font: Font) {
textPaint.typeface = when (font) {
Font.REGULAR -> Typeface.DEFAULT
Font.BOLD -> Typeface.DEFAULT_BOLD
Font.FONT_AWESOME -> getFontAwesome(context)
}
updateMHeight()
}
override fun setFontSize(size: Double) {
textPaint.textSize = size.toDp()
updateMHeight()
}
private fun updateMHeight() {
textPaint.getTextBounds("m", 0, 1, textBounds)
mHeight = textBounds.height()
}
override fun setStrokeWidth(size: Double) {
paint.strokeWidth = size.toDp()
}
override fun fillArc(
centerX: Double,
centerY: Double,
radius: Double,
startAngle: Double,
swipeAngle: Double,
) {
paint.style = Paint.Style.FILL
innerCanvas.drawArc(
(centerX - radius).toDp(),
(centerY - radius).toDp(),
(centerX + radius).toDp(),
(centerY + radius).toDp(),
-startAngle.toFloat(),
-swipeAngle.toFloat(),
true,
paint,
)
}
override fun fillCircle(
centerX: Double,
centerY: Double,
radius: Double,
) {
paint.style = Paint.Style.FILL
innerCanvas.drawCircle(centerX.toDp(), centerY.toDp(), radius.toDp(), paint)
}
override fun setTextAlign(align: TextAlign) {
textPaint.textAlign = when (align) {
TextAlign.LEFT -> Paint.Align.LEFT
TextAlign.CENTER -> Paint.Align.CENTER
TextAlign.RIGHT -> Paint.Align.RIGHT
}
}
override fun toImage(): Image {
val bmp = innerBitmap ?: throw UnsupportedOperationException()
return AndroidImage(bmp)
}
override fun measureText(text: String): Double {
return textPaint.measureText(text) / innerDensity
}
}
| gpl-3.0 | 77a61545fcbdf2c06f976e26b4e50317 | 26.450262 | 84 | 0.590502 | 4.351037 | false | false | false | false |
dahlstrom-g/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ShowEditorDiffPreviewActionProvider.kt | 2 | 1231 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes
import com.intellij.idea.ActionsBundle.message
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionExtensionProvider
import com.intellij.openapi.vcs.changes.EditorTabDiffPreviewManager.Companion.EDITOR_TAB_DIFF_PREVIEW
open class ShowEditorDiffPreviewActionProvider : AnActionExtensionProvider {
override fun isActive(e: AnActionEvent): Boolean {
val project = e.project
return project != null &&
getDiffPreview(e) != null &&
EditorTabDiffPreviewManager.getInstance(project).isEditorDiffPreviewAvailable()
}
override fun update(e: AnActionEvent) {
val diffPreview = getDiffPreview(e)!!
e.presentation.description += " " + message("action.Diff.ShowDiffPreview.description")
diffPreview.updateDiffAction(e)
}
override fun actionPerformed(e: AnActionEvent) {
val diffPreview = getDiffPreview(e)!!
diffPreview.performDiffAction()
}
open fun getDiffPreview(e: AnActionEvent) = e.getData(EDITOR_TAB_DIFF_PREVIEW)
}
| apache-2.0 | 75d0fd16d1926cb3c834c351f1de375b | 40.033333 | 158 | 0.77173 | 4.460145 | false | false | false | false |
dahlstrom-g/intellij-community | jvm/jvm-analysis-kotlin-tests/testData/codeInspection/missingDeprecatedAnnotationOnScheduledForRemovalApi/missingDeprecatedAnnotations.kt | 13 | 772 | package test;
import org.jetbrains.annotations.ApiStatus
@ApiStatus.ScheduledForRemoval
class <error descr="Scheduled for removal API must also be marked with '@Deprecated' annotation">Warnings</error> {
@ApiStatus.ScheduledForRemoval
val <error descr="Scheduled for removal API must also be marked with '@Deprecated' annotation">field</error>: Int = 0
@ApiStatus.ScheduledForRemoval
fun <error descr="Scheduled for removal API must also be marked with '@Deprecated' annotation">method</error>() {
}
}
//No warnings.
@ApiStatus.ScheduledForRemoval
@Deprecated("reason")
class NoWarnings {
@ApiStatus.ScheduledForRemoval
@Deprecated("reason")
val field: Int = 0;
@ApiStatus.ScheduledForRemoval
@Deprecated("reason")
public fun method() {
}
} | apache-2.0 | ac0442d02cc8cfcbf23c953383977b12 | 24.766667 | 119 | 0.753886 | 4.462428 | false | false | false | false |
danbrough/Android-SearchView-Demo | app/src/main/java/danbroid/searchview/CheeseData.kt | 1 | 950 | package danbroid.searchview
import android.content.Context
import android.text.TextUtils
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*
class CheeseData(context: Context) {
val cheeses: Array<String> by lazy {
val cheeseList = mutableListOf<String>()
val reader = BufferedReader(InputStreamReader(context.assets.open("cheeselist.txt")))
try {
reader.forEachLine {
if (!TextUtils.isEmpty(it))
cheeseList.add(it)
}
} finally {
reader.close()
}
cheeseList.toTypedArray();
}
private val RANDOM = Random(System.currentTimeMillis())
fun randomCheese(): String = cheeses[RANDOM.nextInt(cheeses.size)]
companion object {
@Volatile
private var instance: CheeseData? = null
fun getInstance(context: Context) = instance ?: synchronized(this) {
instance ?: CheeseData(context).also {
instance = it
}
}
}
}
| apache-2.0 | 54cbbf8953ef04ed153354f918cd86e0 | 20.111111 | 89 | 0.676842 | 4.185022 | false | false | false | false |
paplorinc/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ModuleChangesGroupingPolicy.kt | 2 | 2255 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.NotNullLazyKey
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder.*
import javax.swing.tree.DefaultTreeModel
class ModuleChangesGroupingPolicy(val project: Project, val model: DefaultTreeModel) : BaseChangesGroupingPolicy() {
private val myIndex = ProjectFileIndex.getInstance(project)
override fun getParentNodeFor(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? {
val file = resolveVirtualFile(nodePath)
val nextPolicyParent = nextPolicy?.getParentNodeFor(nodePath, subtreeRoot)
file?.let { myIndex.getModuleForFile(file, HIDE_EXCLUDED_FILES) }?.let { module ->
val grandParent = nextPolicyParent ?: subtreeRoot
val cachingRoot = getCachingRoot(grandParent, subtreeRoot)
MODULE_CACHE.getValue(cachingRoot)[module]?.let { return it }
ChangesBrowserModuleNode(module).let {
it.markAsHelperNode()
model.insertNodeInto(it, grandParent, grandParent.childCount)
MODULE_CACHE.getValue(cachingRoot)[module] = it
DIRECTORY_CACHE.getValue(cachingRoot)[staticFrom(it.moduleRoot).key] = it
IS_CACHING_ROOT.set(it, true)
MODULE_CACHE.getValue(it)[module] = it
DIRECTORY_CACHE.getValue(it)[staticFrom(it.moduleRoot).key] = it
return it
}
}
return nextPolicyParent
}
class Factory(val project: Project) : ChangesGroupingPolicyFactory() {
override fun createGroupingPolicy(model: DefaultTreeModel): ModuleChangesGroupingPolicy = ModuleChangesGroupingPolicy(project, model)
}
companion object {
private val MODULE_CACHE: NotNullLazyKey<MutableMap<Module?, ChangesBrowserNode<*>>, ChangesBrowserNode<*>> =
NotNullLazyKey.create("ChangesTree.ModuleCache") { mutableMapOf() }
private val HIDE_EXCLUDED_FILES: Boolean = Registry.`is`("ide.hide.excluded.files")
}
} | apache-2.0 | 92aaa83f039b35a16af233ddb4de244e | 43.235294 | 140 | 0.756984 | 4.430255 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/util/moduleChooserUtil.kt | 6 | 3313 | // 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.
@file:JvmName("ModuleChooserUtil")
package org.jetbrains.plugins.groovy.util
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ui.configuration.ModulesAlphaComparator
import com.intellij.openapi.ui.popup.ListPopup
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.util.Condition
import com.intellij.ui.popup.list.ListPopupImpl
import com.intellij.util.Consumer
import com.intellij.util.Function
private const val GROOVY_LAST_MODULE = "Groovy.Last.Module.Chosen"
fun selectModule(project: Project,
modules: List<Module>,
version: Function<Module, String>,
consumer: Consumer<Module>) {
modules.singleOrNull()?.let {
consumer.consume(it)
return
}
createSelectModulePopup(project, modules, version::`fun`, consumer::consume).showCenteredInCurrentWindow(project)
}
fun createSelectModulePopup(project: Project,
modules: List<Module>,
version: (Module) -> String,
consumer: (Module) -> Unit): ListPopup {
val step = createSelectModulePopupStep(project, modules.sortedWith(ModulesAlphaComparator.INSTANCE), consumer)
return object : ListPopupImpl(step) {
override fun getListElementRenderer() = RightTextCellRenderer(super.getListElementRenderer(), version)
}
}
private fun createSelectModulePopupStep(project: Project, modules: List<Module>, consumer: (Module) -> Unit): ListPopupStep<Module> {
val propertiesComponent = PropertiesComponent.getInstance(project)
val step = GroovySelectModuleStep(modules) {
propertiesComponent.setValue(GROOVY_LAST_MODULE, it.name)
consumer(it)
}
propertiesComponent.getValue(GROOVY_LAST_MODULE)?.let { lastModuleName ->
step.defaultOptionIndex = modules.indexOfFirst { it.name == lastModuleName }
}
return step
}
fun formatModuleVersion(module: Module, version: String): String = "${module.name} (${version})"
fun filterGroovyCompatibleModules(modules: Collection<Module>, condition: Condition<Module>): List<Module> {
return filterGroovyCompatibleModules(modules, condition.toPredicate())
}
fun filterGroovyCompatibleModules(modules: Collection<Module>, condition: (Module) -> Boolean): List<Module> {
return modules.filter(isGroovyCompatibleModule(condition))
}
fun hasGroovyCompatibleModules(modules: Collection<Module>, condition: Condition<Module>): Boolean {
return hasGroovyCompatibleModules(modules, condition.toPredicate())
}
fun hasGroovyCompatibleModules(modules: Collection<Module>, condition: (Module) -> Boolean): Boolean {
return modules.any(isGroovyCompatibleModule(condition))
}
private inline fun isGroovyCompatibleModule(crossinline condition: (Module) -> Boolean): (Module) -> Boolean {
val sdkTypeCheck = { it: Module ->
val sdk = ModuleRootManager.getInstance(it).sdk
sdk != null && sdk.sdkType is JavaSdkType
}
return sdkTypeCheck and condition
}
| apache-2.0 | a544c06f8e86bf49c44069d4886d9d1c | 39.901235 | 140 | 0.755509 | 4.393899 | false | false | false | false |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/file/InputObjectAdapterBuilder.kt | 1 | 1498 | package com.apollographql.apollo3.compiler.codegen.kotlin.file
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext
import com.apollographql.apollo3.compiler.codegen.kotlin.CgFile
import com.apollographql.apollo3.compiler.codegen.kotlin.CgFileBuilder
import com.apollographql.apollo3.compiler.codegen.kotlin.CgOutputFileBuilder
import com.apollographql.apollo3.compiler.codegen.kotlin.adapter.inputAdapterTypeSpec
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.toNamedType
import com.apollographql.apollo3.compiler.ir.IrInputObject
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.TypeSpec
class InputObjectAdapterBuilder(
val context: KotlinContext,
val inputObject: IrInputObject,
): CgOutputFileBuilder {
val packageName = context.layout.typeAdapterPackageName()
val simpleName = context.layout.inputObjectAdapterName(inputObject.name)
override fun prepare() {
context.resolver.registerInputObjectAdapter(
inputObject.name,
ClassName(packageName, simpleName)
)
}
override fun build(): CgFile {
return CgFile(
packageName = packageName,
fileName = simpleName,
typeSpecs = listOf(inputObject.adapterTypeSpec())
)
}
private fun IrInputObject.adapterTypeSpec(): TypeSpec {
return fields.map {
it.toNamedType()
}.inputAdapterTypeSpec(
context,
simpleName,
context.resolver.resolveSchemaType(inputObject.name)
)
}
} | mit | 2dbdedc6efcd4803916ee09eb2391a17 | 33.068182 | 85 | 0.775701 | 4.380117 | false | false | false | false |
StepicOrg/stepik-android | app/src/test/java/org/stepic/droid/testUtils/generators/FakeProfileGenerator.kt | 2 | 595 | package org.stepic.droid.testUtils.generators
import org.stepik.android.model.user.Profile
object FakeProfileGenerator {
@JvmOverloads
fun generate(id: Long = 0,
firstName: String = "John",
lastName: String = "Doe",
avatar: String? = null,
shortBio: String = "",
details: String = ""
): Profile {
return Profile(id = id,
avatar = avatar,
fullName = "$firstName $lastName",
shortBio = shortBio,
details = details)
}
}
| apache-2.0 | e6af77be92f86a407571f621593324ee | 24.869565 | 50 | 0.510924 | 4.798387 | false | false | false | false |
oryanm/TrelloWidget | app/src/main/kotlin/com/github/oryanmat/trellowidget/util/TrelloAPIUtil.kt | 1 | 2915 | package com.github.oryanmat.trellowidget.util
import android.content.Context
import android.util.Log
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.RequestFuture
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.github.oryanmat.trellowidget.T_WIDGET
import com.github.oryanmat.trellowidget.model.BoardList
import java.util.concurrent.ExecutionException
const val TOKEN_PREF_KEY = "com.oryanmat.trellowidget.usertoken"
const val APP_KEY = "b250ef70ccf79ea5e107279a91045e6e"
const val BASE_URL = "https://api.trello.com/"
const val API_VERSION = "1/"
const val KEY = "&key=$APP_KEY"
const val AUTH_URL = "https://trello.com/1/authorize" +
"?name=TrelloWidget" +
KEY +
"&expiration=never" +
"&callback_method=fragment" +
"&return_url=trello-widget://callback"
const val USER = "members/me?fields=fullName,username"
const val BOARDS = "members/me/boards?filter=open&fields=id,name,url&lists=open"
const val LIST_CARDS = "lists/%s?cards=open&card_fields=name,badges,labels,url"
const val ERROR_MESSAGE = "HTTP request to Trello failed: %s"
class TrelloAPIUtil private constructor(context: Context) {
private val queue: RequestQueue by lazy { Volley.newRequestQueue(context) }
private val preferences = context.preferences()
companion object {
lateinit var instance: TrelloAPIUtil
fun init(context: Context) {
instance = TrelloAPIUtil(context.applicationContext)
}
}
fun buildURL(query: String) = "$BASE_URL$API_VERSION$query$KEY&${preferences.getString(TOKEN_PREF_KEY, "")}"
fun user() = buildURL(USER)
fun boards() = buildURL(BOARDS)
fun getCards(list: BoardList): BoardList {
val json = get(buildURL(LIST_CARDS.format(list.id)))
return Json.tryParseJson(json, BoardList::class.java, BoardList.error(json))
}
fun getUserAsync(listener: Response.Listener<String>, errorListener: Response.ErrorListener) {
getAsync(user(), listener, errorListener)
}
fun getAsync(url: String, listener: Response.Listener<String>, errorListener: Response.ErrorListener) {
queue.add(StringRequest(Request.Method.GET, url, listener, errorListener))
}
private fun get(url: String): String {
val future = RequestFuture.newFuture<String>()
queue.add(StringRequest(Request.Method.GET, url, future, future))
return get(future)
}
private fun get(future: RequestFuture<String>) = try {
future.get()
} catch (e: ExecutionException) {
logException(e)
} catch (e: InterruptedException) {
logException(e)
}
private fun logException(e: Exception): String {
val msg = ERROR_MESSAGE.format(e)
Log.e(T_WIDGET, msg)
return msg
}
} | mit | eb43f47985115f07a8c605f213fa4043 | 33.305882 | 112 | 0.706003 | 3.675914 | false | false | false | false |
glodanif/BluetoothChat | app/src/main/kotlin/com/glodanif/bluetoothchat/ui/util/ScrollAwareBehavior.kt | 1 | 3460 | package com.glodanif.bluetoothchat.ui.util
import android.content.Context
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import com.glodanif.bluetoothchat.R
import com.glodanif.bluetoothchat.ui.widget.GoDownButton
class ScrollAwareBehavior(val context: Context) : CoordinatorLayout.Behavior<GoDownButton>() {
private var childView: GoDownButton? = null
private var isAnimationRunning = false
private var isOpened = false
private var scrollRange = 0
var onHideListener: (() -> Unit)? = null
private val openAnimation: Animation by lazy {
AnimationUtils.loadAnimation(context, R.anim.switcher_scale_in).apply {
setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
isAnimationRunning = true
childView?.visibility = View.VISIBLE
}
override fun onAnimationEnd(animation: Animation) {
isAnimationRunning = false
isOpened = true
}
override fun onAnimationRepeat(animation: Animation) {
}
})
}
}
private val closeAnimation: Animation by lazy {
AnimationUtils.loadAnimation(context, R.anim.switcher_scale_out).apply {
setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
isAnimationRunning = true
}
override fun onAnimationEnd(animation: Animation) {
isAnimationRunning = false
isOpened = false
childView?.visibility = View.INVISIBLE
}
override fun onAnimationRepeat(animation: Animation) {
}
})
}
}
fun isChildShown() = isOpened
fun hideChild() {
childView?.startAnimation(closeAnimation)
scrollRange = 0
}
override fun onLayoutChild(parent: CoordinatorLayout, child: GoDownButton, layoutDirection: Int): Boolean {
childView = child
return super.onLayoutChild(parent, child, layoutDirection)
}
override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: GoDownButton, directTargetChild: View,
target: View, nestedScrollAxes: Int, @ViewCompat.NestedScrollType type: Int) = true
override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: GoDownButton, target: View,
dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, @ViewCompat.NestedScrollType type: Int) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type)
scrollRange += -dyConsumed
val showLimit = coordinatorLayout.height * 1.5
if (!isAnimationRunning) {
if (scrollRange > showLimit && !isOpened) {
childView?.startAnimation(openAnimation)
} else if (scrollRange < showLimit && isOpened) {
childView?.startAnimation(closeAnimation)
onHideListener?.invoke()
}
}
}
}
| apache-2.0 | f9d3a73e985b325cc2160e7a40a161a3 | 33.257426 | 145 | 0.63526 | 5.690789 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-debug/test/WithContextUndispatchedTest.kt | 1 | 1536 | /*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.debug
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import org.junit.*
// Test four our internal optimization "withContextUndispatched"
class WithContextUndispatchedTest : DebugTestBase() {
@Test
fun testZip() = runTest {
val f1 = flowOf("a")
val f2 = flow {
nestedEmit()
yield()
}
f1.zip(f2) { i, j -> i + j }.collect {
bar(false)
}
}
private suspend fun FlowCollector<Int>.nestedEmit() {
emit(1)
emit(2)
}
@Test
fun testUndispatchedFlowOn() = runTest {
val flow = flowOf(1, 2, 3).flowOn(CoroutineName("..."))
flow.collect {
bar(true)
}
}
@Test
fun testUndispatchedFlowOnWithNestedCaller() = runTest {
val flow = flow {
nestedEmit()
}.flowOn(CoroutineName("..."))
flow.collect {
bar(true)
}
}
private suspend fun bar(forFlowOn: Boolean) {
yield()
if (forFlowOn) {
verifyFlowOn()
} else {
verifyZip()
}
yield()
}
private suspend fun verifyFlowOn() {
yield() // suspend
verifyPartialDump(1, "verifyFlowOn", "bar")
}
private suspend fun verifyZip() {
yield() // suspend
verifyPartialDump(2, "verifyZip", "bar", "nestedEmit")
}
}
| apache-2.0 | 28a18547fdebd35b68837cb9070fd77b | 21.925373 | 102 | 0.546224 | 4.231405 | false | true | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/test/TestBase.common.kt | 1 | 4149 | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("unused")
package kotlinx.coroutines
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.internal.*
import kotlin.coroutines.*
import kotlin.test.*
public expect val isStressTest: Boolean
public expect val stressTestMultiplier: Int
public expect val stressTestMultiplierSqrt: Int
/**
* The result of a multiplatform asynchronous test.
* Aliases into Unit on K/JVM and K/N, and into Promise on K/JS.
*/
@Suppress("NO_ACTUAL_FOR_EXPECT")
public expect class TestResult
public expect val isNative: Boolean
public expect open class TestBase constructor() {
/*
* In common tests we emulate parameterized tests
* by iterating over parameters space in the single @Test method.
* This kind of tests is too slow for JS and does not fit into
* the default Mocha timeout, so we're using this flag to bail-out
* and run such tests only on JVM and K/N.
*/
public val isBoundByJsTestTimeout: Boolean
public fun error(message: Any, cause: Throwable? = null): Nothing
public fun expect(index: Int)
public fun expectUnreached()
public fun finish(index: Int)
public fun ensureFinished() // Ensures that 'finish' was invoked
public fun reset() // Resets counter and finish flag. Workaround for parametrized tests absence in common
public fun runTest(
expected: ((Throwable) -> Boolean)? = null,
unhandled: List<(Throwable) -> Boolean> = emptyList(),
block: suspend CoroutineScope.() -> Unit
): TestResult
}
public suspend inline fun hang(onCancellation: () -> Unit) {
try {
suspendCancellableCoroutine<Unit> { }
} finally {
onCancellation()
}
}
public inline fun <reified T : Throwable> assertFailsWith(block: () -> Unit) {
try {
block()
error("Should not be reached")
} catch (e: Throwable) {
assertTrue(e is T)
}
}
public suspend inline fun <reified T : Throwable> assertFailsWith(flow: Flow<*>) {
try {
flow.collect()
fail("Should be unreached")
} catch (e: Throwable) {
assertTrue(e is T, "Expected exception ${T::class}, but had $e instead")
}
}
public suspend fun Flow<Int>.sum() = fold(0) { acc, value -> acc + value }
public suspend fun Flow<Long>.longSum() = fold(0L) { acc, value -> acc + value }
// data is added to avoid stacktrace recovery because CopyableThrowable is not accessible from common modules
public class TestException(message: String? = null, private val data: Any? = null) : Throwable(message)
public class TestException1(message: String? = null, private val data: Any? = null) : Throwable(message)
public class TestException2(message: String? = null, private val data: Any? = null) : Throwable(message)
public class TestException3(message: String? = null, private val data: Any? = null) : Throwable(message)
public class TestCancellationException(message: String? = null, private val data: Any? = null) : CancellationException(message)
public class TestRuntimeException(message: String? = null, private val data: Any? = null) : RuntimeException(message)
public class RecoverableTestException(message: String? = null) : RuntimeException(message)
public class RecoverableTestCancellationException(message: String? = null) : CancellationException(message)
public fun wrapperDispatcher(context: CoroutineContext): CoroutineContext {
val dispatcher = context[ContinuationInterceptor] as CoroutineDispatcher
return object : CoroutineDispatcher() {
override fun isDispatchNeeded(context: CoroutineContext): Boolean =
dispatcher.isDispatchNeeded(context)
override fun dispatch(context: CoroutineContext, block: Runnable) =
dispatcher.dispatch(context, block)
}
}
public suspend fun wrapperDispatcher(): CoroutineContext = wrapperDispatcher(coroutineContext)
class BadClass {
override fun equals(other: Any?): Boolean = error("equals")
override fun hashCode(): Int = error("hashCode")
override fun toString(): String = error("toString")
}
| apache-2.0 | a19ec730e388646bd3406bbde092d2bb | 38.141509 | 127 | 0.713425 | 4.432692 | false | true | false | false |
Raizlabs/DBFlow | lib/src/main/kotlin/com/dbflow5/query/list/FlowQueryList.kt | 1 | 7481 | package com.dbflow5.query.list
import android.os.Handler
import android.os.Looper
import com.dbflow5.adapter.RetrievalAdapter
import com.dbflow5.database.DatabaseWrapper
import com.dbflow5.database.FlowCursor
import com.dbflow5.query.ModelQueriable
/**
* Description: A query-backed immutable [List]. Represents the results of a cursor without loading
* the full query out into an actual [List]. Avoid keeping this class around without calling [close] as
* it leaves a [FlowCursor] object active.
*/
class FlowQueryList<T : Any>(
/**
* Holds the table cursor
*/
val internalCursorList: FlowCursorList<T>,
private val refreshHandler: Handler = globalRefreshHandler)
: List<T>, IFlowCursorIterator<T> by internalCursorList {
private var pendingRefresh = false
/**
* @return a mutable list that does not reflect changes on the underlying DB.
*/
val copy: List<T>
get() = internalCursorList.all
internal val retrievalAdapter: RetrievalAdapter<T>
get() = internalCursorList.instanceAdapter
override val size: Int
get() = internalCursorList.count.toInt()
private val refreshRunnable = object : Runnable {
override fun run() {
synchronized(this) {
pendingRefresh = false
}
refresh()
}
}
internal constructor(builder: Builder<T>) : this(
internalCursorList = FlowCursorList.Builder(builder.modelQueriable, builder.databaseWrapper)
.cursor(builder.cursor)
.build(),
refreshHandler = builder.refreshHandler
)
fun addOnCursorRefreshListener(onCursorRefreshListener: OnCursorRefreshListener<T>) {
internalCursorList.addOnCursorRefreshListener(onCursorRefreshListener)
}
fun removeOnCursorRefreshListener(onCursorRefreshListener: OnCursorRefreshListener<T>) {
internalCursorList.removeOnCursorRefreshListener(onCursorRefreshListener)
}
val cursorList: FlowCursorList<T>
get() = internalCursorList
/**
* @return Constructs a new [Builder] that reuses the underlying [FlowCursor],
* callbacks, and other properties.
*/
fun newBuilder(): Builder<T> = Builder(internalCursorList)
/**
* Refreshes the content backing this list.
*/
fun refresh() {
internalCursorList.refresh()
}
/**
* Will refresh content at a slightly later time, and multiple subsequent calls to this method within
* a short period of time will be combined into one call.
*/
fun refreshAsync() {
synchronized(this) {
if (pendingRefresh) {
return
}
pendingRefresh = true
}
refreshHandler.post(refreshRunnable)
}
/**
* Checks to see if the table contains the object only if its a [T]
*
* @param element A model class. For interface purposes, this must be an Object.
* @return always false if its anything other than the current table. True if [com.dbflow5.structure.Model.exists] passes.
*/
override operator fun contains(element: T): Boolean {
return internalCursorList.instanceAdapter.exists(element, internalCursorList.databaseWrapper)
}
/**
* If the collection is null or empty, we return false.
*
* @param elements The collection to check if all exist within the table.
* @return true if all items exist in table, false if at least one fails.
*/
override fun containsAll(elements: Collection<T>): Boolean {
var contains = !elements.isEmpty()
if (contains) {
contains = elements.all { it in this }
}
return contains
}
/**
* Returns the item from the backing [FlowCursorList]. First call
* will load the model from the cursor, while subsequent calls will use the cache.
*
* @param index the row from the internal [FlowCursorList] query that we use.
* @return A model converted from the internal [FlowCursorList]. For
* performance improvements, ensure caching is turned on.
*/
override fun get(index: Long): T = internalCursorList[index]
override operator fun get(index: Int): T = internalCursorList[index.toLong()]
override fun indexOf(element: T): Int {
throw UnsupportedOperationException(
"We cannot determine which index in the table this item exists at efficiently")
}
override fun isEmpty(): Boolean {
return internalCursorList.isEmpty
}
/**
* @return An iterator that loops through all items in the list.
* Be careful as this method will convert all data under this table into a list of [T] in the UI thread.
*/
override fun iterator(): FlowCursorIterator<T> {
return FlowCursorIterator(internalCursorList.databaseWrapper, this)
}
override fun iterator(startingLocation: Long, limit: Long): FlowCursorIterator<T> {
return FlowCursorIterator(internalCursorList.databaseWrapper, this, startingLocation, limit)
}
override fun lastIndexOf(element: T): Int {
throw UnsupportedOperationException(
"We cannot determine which index in the table this item exists at efficiently")
}
/**
* @return A list iterator that loops through all items in the list.
* Be careful as this method will convert all data under this table into a list of [T] in the UI thread.
*/
override fun listIterator(): ListIterator<T> {
return FlowCursorIterator(internalCursorList.databaseWrapper, this)
}
/**
* @param index The index to start the iterator.
* @return A list iterator that loops through all items in the list.
* Be careful as this method will convert all data under this table into a list of [T] in the UI thread.
*/
override fun listIterator(index: Int): ListIterator<T> {
return FlowCursorIterator(internalCursorList.databaseWrapper, this, index.toLong())
}
override fun subList(fromIndex: Int, toIndex: Int): List<T> {
val tableList = internalCursorList.all
return tableList.subList(fromIndex, toIndex)
}
class Builder<T : Any> {
internal val table: Class<T>
internal var cursor: FlowCursor? = null
internal var modelQueriable: ModelQueriable<T>
internal val databaseWrapper: DatabaseWrapper
internal val refreshHandler: Handler
internal constructor(cursorList: FlowCursorList<T>,
refreshHandler: Handler = globalRefreshHandler) {
this.databaseWrapper = cursorList.databaseWrapper
table = cursorList.table
cursor = cursorList.cursor
modelQueriable = cursorList.modelQueriable
this.refreshHandler = refreshHandler
}
constructor(modelQueriable: ModelQueriable<T>,
databaseWrapper: DatabaseWrapper,
refreshHandler: Handler = globalRefreshHandler
) {
this.databaseWrapper = databaseWrapper
this.table = modelQueriable.table
this.modelQueriable = modelQueriable
this.refreshHandler = refreshHandler
}
fun cursor(cursor: FlowCursor) = apply {
this.cursor = cursor
}
fun build() = FlowQueryList(this)
}
companion object {
private val globalRefreshHandler = Handler(Looper.myLooper())
}
}
| mit | 15ea8553a47c969287347d0efb373d6d | 33.316514 | 126 | 0.665553 | 4.915243 | false | false | false | false |
zdary/intellij-community | plugins/ide-features-trainer/src/training/lang/LangManager.kt | 1 | 3600 | // 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 training.lang
import com.intellij.lang.Language
import com.intellij.lang.LanguageExtensionPoint
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import training.ui.LearnToolWindowFactory
import training.util.WeakReferenceDelegator
import training.util.courseCanBeUsed
import training.util.findLanguageByID
import training.util.trainerPluginConfigName
@State(name = "LangManager", storages = [
Storage(value = StoragePathMacros.NON_ROAMABLE_FILE),
Storage(value = trainerPluginConfigName, deprecated = true)
])
internal class LangManager : SimplePersistentStateComponent<LangManager.State>(State()) {
val supportedLanguagesExtensions: List<LanguageExtensionPoint<LangSupport>>
get() {
return ExtensionPointName<LanguageExtensionPoint<LangSupport>>(LangSupport.EP_NAME).extensionList
.filter { courseCanBeUsed(it.language) }
}
val languages: List<LanguageExtensionPoint<LangSupport>>
get() = supportedLanguagesExtensions.filter { Language.findLanguageByID(it.language) != null }
private var langSupportRef: LangSupport? by WeakReferenceDelegator()
init {
val productName = ApplicationNamesInfo.getInstance().productName
val onlyLang =
languages.singleOrNull() ?:
languages.singleOrNull { it.instance.defaultProductName == productName } ?:
languages.firstOrNull()?.also {
if (!ApplicationManager.getApplication().isUnitTestMode) {
logger<LangManager>().warn("No default language for $productName. Selected ${it.language}.")
}
}
if (onlyLang != null) {
langSupportRef = onlyLang.instance
state.languageName = onlyLang.language
}
}
companion object {
fun getInstance() = service<LangManager>()
}
fun getLearningProjectPath(langSupport: LangSupport): String? = state.languageToProjectMap[langSupport.primaryLanguage]
fun setLearningProjectPath(langSupport: LangSupport, path: String) {
state.languageToProjectMap[langSupport.primaryLanguage] = path
}
fun getLangSupportById(languageId: String): LangSupport? {
return supportedLanguagesExtensions.singleOrNull { it.language == languageId }?.instance
}
// do not call this if LearnToolWindow with modules or learn views due to reinitViews
fun updateLangSupport(langSupport: LangSupport) {
this.langSupportRef = langSupport
state.languageName = supportedLanguagesExtensions.find { it.instance == langSupport }?.language
?: throw Exception("Unable to get language.")
LearnToolWindowFactory.learnWindowPerProject.values.forEach { it.reinitViews() }
}
fun getLangSupport(): LangSupport? = langSupportRef
override fun loadState(state: State) {
super.loadState(state)
langSupportRef = supportedLanguagesExtensions.find { langExt -> langExt.language == state.languageName }?.instance ?: return
}
fun getLanguageDisplayName(): String {
val default = "default"
val languageName = state.languageName ?: return default
return (findLanguageByID(languageName) ?: return default).displayName
}
// Note: languageName - it is language Id actually
class State : BaseState() {
var languageName by string()
val languageToProjectMap by linkedMap<String, String>()
}
} | apache-2.0 | 107cbad71e06f117d7cafa7b0cc7d9ae | 39.011111 | 140 | 0.758333 | 4.938272 | false | false | false | false |
leafclick/intellij-community | platform/workspaceModel-ide/src/com/intellij/workspace/legacyBridge/facet/ModifiableFacetModelViaWorkspaceModel.kt | 1 | 4056 | // 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.workspace.legacyBridge.facet
import com.intellij.facet.Facet
import com.intellij.facet.ModifiableFacetModel
import com.intellij.facet.impl.FacetUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.workspace.api.*
import com.intellij.workspace.ide.WorkspaceModel
import com.intellij.workspace.ide.toEntitySource
import com.intellij.workspace.legacyBridge.intellij.LegacyBridgeModule
internal class ModifiableFacetModelViaWorkspaceModel(private val initialStorage: TypedEntityStorage,
private val diff: TypedEntityStorageDiffBuilder,
legacyBridgeModule: LegacyBridgeModule,
private val facetManager: FacetManagerViaWorkspaceModel)
: FacetModelViaWorkspaceModel(legacyBridgeModule), ModifiableFacetModel {
private val listeners: MutableList<ModifiableFacetModel.Listener> = ContainerUtil.createLockFreeCopyOnWriteList()
init {
populateFrom(facetManager.model)
}
private fun getModuleEntity() = initialStorage.resolve(legacyBridgeModule.moduleEntityId)!!
override fun addFacet(facet: Facet<*>) {
addFacet(facet, null)
}
override fun addFacet(facet: Facet<*>, externalSource: ProjectModelExternalSource?) {
val moduleEntity = getModuleEntity()
val source = externalSource?.toEntitySource() ?: moduleEntity.entitySource
val facetConfigurationXml = FacetUtil.saveFacetConfiguration(facet)?.let { JDOMUtil.write(it) }
val underlyingEntity = facet.underlyingFacet?.let { entityToFacet.inverse()[it]!! }
val entity = diff.addFacetEntity(facet.name, facet.type.stringId, facetConfigurationXml, moduleEntity, underlyingEntity, source)
entityToFacet[entity] = facet
facetsChanged()
}
override fun removeFacet(facet: Facet<*>?) {
val facetEntity = entityToFacet.inverse()[facet] ?: return
removeFacetEntityWithSubFacets(facetEntity)
facetsChanged()
}
override fun replaceFacet(original: Facet<*>, replacement: Facet<*>) {
removeFacet(original)
addFacet(replacement)
}
private fun removeFacetEntityWithSubFacets(entity: FacetEntity) {
if (entity !in entityToFacet) return
entity.subFacets.forEach {
removeFacetEntityWithSubFacets(it)
}
entityToFacet.remove(entity)
diff.removeEntity(entity)
}
override fun rename(facet: Facet<*>, newName: String) {
val entity = entityToFacet.inverse()[facet]!!
val newEntity = diff.modifyEntity(ModifiableFacetEntity::class.java, entity) {
this.name = newName
}
entityToFacet.inverse()[facet] = newEntity
facetsChanged()
}
override fun getNewName(facet: Facet<*>): String? {
val entity = entityToFacet.inverse()[facet]!!
return entity.name
}
override fun commit() {
facetManager.model.populateFrom(entityToFacet)
val moduleDiff = legacyBridgeModule.diff
if (moduleDiff != null) {
moduleDiff.addDiff(diff)
}
else {
WorkspaceModel.getInstance(legacyBridgeModule.project).updateProjectModel {
it.addDiff(diff)
}
}
}
override fun isModified(): Boolean {
return !diff.isEmpty()
}
override fun isNewFacet(facet: Facet<*>): Boolean {
val entity = entityToFacet.inverse()[facet]
return entity != null && initialStorage.resolve(entity.persistentId()) == null
}
override fun addListener(listener: ModifiableFacetModel.Listener, parentDisposable: Disposable) {
listeners += listener
Disposer.register(parentDisposable, Disposable { listeners -= listener })
}
override fun facetsChanged() {
super.facetsChanged()
listeners.forEach { it.onChanged() }
}
} | apache-2.0 | 2b5af59ad5d121510e8be117c7832c8e | 35.881818 | 140 | 0.726578 | 4.958435 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/log/LogEntry.kt | 1 | 607 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common.log
import slatekit.common.DateTime
data class LogEntry(
val name: String = "",
val level: LogLevel,
val msg: String = "",
val ex: Throwable? = null,
val tag: String? = null,
val time: DateTime = DateTime.now()
) | apache-2.0 | dd324216ba9dabe677081276cddd0cfb | 23.32 | 56 | 0.680395 | 3.549708 | false | false | false | false |
leafclick/intellij-community | java/java-impl/src/com/intellij/lang/java/request/createFromUsageUtils.kt | 1 | 3525 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.java.request
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmClassKind
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.codeStyle.JavaCodeStyleSettings
import com.intellij.psi.util.*
import java.util.*
import kotlin.collections.ArrayList
internal fun PsiExpression.isInStaticContext(): Boolean {
return isWithinStaticMember() || isWithinConstructorCall()
}
internal fun PsiExpression.isWithinStaticMemberOf(clazz: PsiClass): Boolean {
var currentPlace: PsiElement = this
while (true) {
val enclosingMember = currentPlace.parentOfType<PsiMember>() ?: return false
val enclosingClass = enclosingMember.containingClass ?: return false
if (enclosingClass == clazz) {
return enclosingMember.hasModifierProperty(PsiModifier.STATIC)
}
else {
currentPlace = enclosingClass.parent ?: return false
}
}
}
internal fun PsiExpression.isWithinStaticMember(): Boolean {
return parentOfType<PsiMember>()?.hasModifierProperty(PsiModifier.STATIC) ?: false
}
//usages inside delegating constructor call
internal fun PsiExpression.isWithinConstructorCall(): Boolean {
val owner = parentOfType<PsiModifierListOwner>() as? PsiMethod ?: return false
if (!owner.isConstructor) return false
val parent = parentsWithSelf.firstOrNull { it !is PsiExpression } as? PsiExpressionList ?: return false
val grandParent = parent.parent as? PsiMethodCallExpression ?: return false
val calleText = grandParent.methodExpression.text
return calleText == PsiKeyword.SUPER || calleText == PsiKeyword.THIS
}
internal fun computeVisibility(project: Project, ownerClass: PsiClass?, targetClass: JvmClass): JvmModifier? {
if (targetClass.classKind == JvmClassKind.INTERFACE || targetClass.classKind == JvmClassKind.ANNOTATION) return JvmModifier.PUBLIC
if (ownerClass != null) {
(targetClass as? PsiClass)?.let { target ->
if (target.isEquivalentTo(ownerClass) || PsiTreeUtil.isAncestor(target, ownerClass, false)) {
return JvmModifier.PRIVATE
}
if (InheritanceUtil.isInheritorOrSelf(ownerClass, target, true)) {
return JvmModifier.PROTECTED
}
}
}
val setting = CodeStyleSettingsManager.getSettings(project).getCustomSettings(JavaCodeStyleSettings::class.java).VISIBILITY
return when (setting) {
PsiModifier.PUBLIC -> JvmModifier.PUBLIC
PsiModifier.PROTECTED -> JvmModifier.PROTECTED
PsiModifier.PACKAGE_LOCAL -> JvmModifier.PACKAGE_LOCAL
PsiModifier.PRIVATE -> JvmModifier.PRIVATE
else -> null // TODO escalate visibility
}
}
internal fun collectOuterClasses(place: PsiElement): List<PsiClass> {
val result = ArrayList<PsiClass>()
for (clazz in place.parentsOfType<PsiClass>()) {
result.add(clazz)
if (clazz.hasModifierProperty(PsiModifier.STATIC)) break
}
return result
}
internal fun hierarchy(clazz: PsiClass): List<PsiClass> { // TODO implementation based on JvmClasses
val result = LinkedHashSet<PsiClass>()
val queue = LinkedList<PsiClass>()
queue.add(clazz)
while (queue.isNotEmpty()) {
val current = queue.removeFirst()
if (result.add(current)) {
queue.addAll(current.supers)
}
}
return result.filter { it !is PsiTypeParameter }
}
| apache-2.0 | f60acba275728cd92ae694685d05dedc | 37.315217 | 140 | 0.756312 | 4.6875 | false | false | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/store/AccountsStore.kt | 1 | 5320 | package au.com.codeka.warworlds.server.store
import au.com.codeka.warworlds.common.proto.Account
import au.com.codeka.warworlds.server.store.base.BaseStore
import au.com.codeka.warworlds.server.util.Pair
import java.io.IOException
import java.util.*
/**
* Stores information about [Account]s, indexed by cookie.
*/
class AccountsStore internal constructor(fileName: String) : BaseStore(fileName) {
operator fun get(cookie: String): Account? {
newReader()
.stmt("SELECT account FROM accounts WHERE cookie = ?")
.param(0, cookie)
.query().use { res ->
if (res.next()) {
return Account.ADAPTER.decode(res.getBytes(0))
}
}
return null
}
fun getByVerifiedEmailAddr(emailAddr: String): Account? {
newReader()
.stmt("SELECT account FROM accounts WHERE email = ?")
.param(0, emailAddr)
.query().use { res ->
while (res.next()) {
val acct = Account.ADAPTER.decode(res.getBytes(0))
if (acct.email_status == Account.EmailStatus.VERIFIED) {
return acct
}
}
}
return null
}
fun getByEmpireId(empireId: Long): Pair<String, Account>? {
newReader()
.stmt("SELECT cookie, account FROM accounts WHERE empire_id = ?")
.param(0, empireId)
.query().use { res ->
if (res.next()) {
return Pair(res.getString(0), Account.ADAPTER.decode(res.getBytes(1)))
}
}
return null
}
fun search( /* TODO: search string, pagination etc */): ArrayList<Account> {
val accounts = ArrayList<Account>()
newReader()
.stmt("SELECT account FROM accounts")
.query().use { res ->
while (res.next()) {
accounts.add(Account.ADAPTER.decode(res.getBytes(0)))
}
}
return accounts
}
fun put(cookie: String, account: Account) {
newTransaction().use {
val query = newReader(it)
.stmt("SELECT COUNT(*) FROM accounts WHERE empire_id = ?")
.param(0, account.empire_id)
.query()
query.next()
if (query.getInt(0) == 1) {
newWriter(it)
.stmt("UPDATE accounts SET email=?, cookie=?, account=? WHERE empire_id=?")
.param(0,
if (account.email_status == Account.EmailStatus.VERIFIED) account.email else null)
.param(1, cookie)
.param(2, account.encode())
.param(3, account.empire_id)
.execute()
} else {
newWriter(it)
.stmt("INSERT INTO accounts ("
+ " email, cookie, empire_id, account"
+ ") VALUES (?, ?, ?, ?)")
.param(0,
if (account.email_status == Account.EmailStatus.VERIFIED) account.email else null)
.param(1, cookie)
.param(2, account.empire_id)
.param(3, account.encode())
.execute()
}
it.commit()
}
}
override fun onOpen(diskVersion: Int): Int {
var version = diskVersion
if (version == 0) {
newWriter()
.stmt("CREATE TABLE accounts (email STRING, cookie STRING, account BLOB)")
.execute()
newWriter()
.stmt("CREATE INDEX IX_accounts_cookie ON accounts (cookie)")
.execute()
newWriter()
.stmt("CREATE UNIQUE INDEX UIX_accounts_email ON accounts (email)")
.execute()
version++
}
if (version == 1) {
newWriter()
.stmt("DROP INDEX IX_accounts_cookie")
.execute()
newWriter()
.stmt("CREATE UNIQUE INDEX IX_accounts_cookie ON accounts (cookie)")
.execute()
version++
}
if (version == 2) {
newWriter()
.stmt("ALTER TABLE accounts ADD COLUMN empire_id INTEGER")
.execute()
updateAllAccounts()
version++
}
if (version == 3) {
newWriter()
.stmt("ALTER TABLE accounts ADD COLUMN email_verification_code STRING")
.execute()
newWriter()
.stmt("CREATE UNIQUE INDEX IX_accounts_empire_id ON accounts (empire_id)")
.execute()
newWriter()
.stmt("CREATE UNIQUE INDEX IX_accounts_email_verification_code ON accounts (email_verification_code)")
.execute()
version++
}
if (version == 4) {
// Email account needs to be non-unique (we could have unverified emails associated with
// multiple accounts). Email + email_status=VERIFIED needs to be unique, but we can't really
// do that with a simple index.
newWriter()
.stmt("DROP INDEX UIX_accounts_email")
.execute()
newWriter()
.stmt("CREATE INDEX IX_accounts_email ON accounts (email)")
.execute()
version++
}
return version
}
/** Called by [.onOpen] when we need to re-save the accounts (after adding a column) */
private fun updateAllAccounts() {
val res = newReader()
.stmt("SELECT cookie, account FROM accounts")
.query()
while (res.next()) {
try {
val cookie = res.getString(0)
val account = Account.ADAPTER.decode(res.getBytes(1))
put(cookie, account)
} catch (e: IOException) {
throw StoreException(e)
}
}
}
} | mit | 5d1cd9570a759c9dcf3998101b41b1d6 | 30.485207 | 112 | 0.567481 | 4.185681 | false | false | false | false |
AndroidX/androidx | emoji2/integration-tests/init-disabled-macrobenchmark/src/androidTest/java/androidx/emoji2/integration/macrobenchmark/disabled/EmojiStartupBenchmark.kt | 3 | 1712 | /*
* 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.emoji2.integration.macrobenchmark.disabled
import android.os.Build
import androidx.benchmark.macro.CompilationMode
import androidx.benchmark.macro.StartupMode
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.testutils.measureStartup
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class EmojiStartupBenchmark {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
@Test
fun emojiCompatInitDisabledStartup() {
benchmarkRule.measureStartup(
compilationMode = if (Build.VERSION.SDK_INT >= 24) {
CompilationMode.None()
} else {
CompilationMode.Full()
},
startupMode = StartupMode.COLD,
packageName = "androidx.emoji2.integration.macrobenchmark.disabled.target"
) {
action = "androidx.emoji2.integration.macrobenchmark.disabled.target.MAIN"
}
}
}
| apache-2.0 | 7970078961a244c1cc360cac6a1b433e | 33.24 | 86 | 0.724883 | 4.469974 | false | true | false | false |
zielu/GitToolBox | src/main/kotlin/zielu/gittoolbox/config/AppConfig.kt | 1 | 1907 | package zielu.gittoolbox.config
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.Logger
import com.intellij.serviceContainer.NonInjectable
import zielu.gittoolbox.util.AppUtil
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
@State(name = "GitToolBoxAppSettings2", storages = [Storage("git_toolbox_2.xml")])
internal class AppConfig
@NonInjectable
constructor(
private val facade: AppConfigFacade
) : PersistentStateComponent<GitToolBoxConfig2> {
constructor() : this(AppConfigFacade())
private val lock = ReentrantLock()
private var state: GitToolBoxConfig2 = GitToolBoxConfig2()
override fun getState(): GitToolBoxConfig2 {
lock.withLock {
return state
}
}
override fun loadState(state: GitToolBoxConfig2) {
lock.withLock {
log.debug("App config state loaded: ", state)
migrate(state)
this.state = state
}
}
private fun migrate(state: GitToolBoxConfig2) {
val migrated = facade.migrate(state)
if (migrated) {
log.info("Migration done")
} else {
log.info("Already migrated")
}
}
override fun noStateLoaded() {
log.info("No persisted state of app configuration")
}
fun stateUpdated(before: GitToolBoxConfig2) {
lock.withLock {
log.info("Config updated")
if (before != state) {
log.info("Current different than previous")
facade.publishUpdated(before, state)
}
}
}
companion object {
private val log = Logger.getInstance(AppConfig::class.java)
@JvmStatic
fun getConfig(): GitToolBoxConfig2 {
return getInstance().getState()
}
@JvmStatic
fun getInstance(): AppConfig {
return AppUtil.getServiceInstance(AppConfig::class.java)
}
}
}
| apache-2.0 | 89d964efc9b2cdd7ae170bf1fd41e2e2 | 24.77027 | 82 | 0.711589 | 4.334091 | false | true | false | false |
charlesng/SampleAppArch | app/src/main/java/com/cn29/aac/ui/masterdetail/SimpleDetailActivity.kt | 1 | 2812 | package com.cn29.aac.ui.masterdetail
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.core.app.NavUtils
import com.cn29.aac.R
import com.cn29.aac.ui.masterdetail.vm.SimpleMasterDetailShareViewModel
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import dagger.android.support.DaggerAppCompatActivity
import javax.inject.Inject
/**
* An activity representing a single FeedEntry detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a [SimpleListActivity].
*/
class SimpleDetailActivity : DaggerAppCompatActivity() {
@Inject
lateinit var masterDetailShareViewModel: SimpleMasterDetailShareViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_simple_detail)
val toolbar = findViewById<Toolbar>(
R.id.detail_toolbar)
setSupportActionBar(toolbar)
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setOnClickListener { view: View? ->
Snackbar.make(view!!,
"Replace with your own detail action",
Snackbar.LENGTH_LONG)
.setAction("Action",
null)
.show()
}
// Show the Up button in the action bar.
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
val arguments = Bundle()
arguments.putString(SimpleDetailFragment.OWNER_NAME,
intent.getStringExtra(SimpleDetailFragment.OWNER_NAME))
arguments.putString(SimpleDetailFragment.REPO_NAME,
intent.getStringExtra(SimpleDetailFragment.REPO_NAME))
val fragment = SimpleDetailFragment()
fragment.arguments = arguments
supportFragmentManager.beginTransaction()
.add(R.id.feedentry_detail_container, fragment)
.commit()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
NavUtils.navigateUpTo(this,
Intent(this, SimpleListActivity::class.java))
return true
}
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | e27abbab96615879252b013a7d5fb68f | 39.768116 | 87 | 0.652205 | 5.178637 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/MutableState.kt | 1 | 3545 | package de.fabmax.kool.modules.ui2
fun <T> mutableStateOf(value: T) = MutableStateValue(value)
fun <T: Any> mutableStateListOf(vararg elements: T) = MutableStateList<T>().apply { addAll(elements) }
fun MutableStateValue<Boolean>.toggle() { value = !value }
abstract class MutableState {
var isStateChanged = true
private set
private val usedBy = mutableListOf<UiSurface>()
protected fun stateChanged() {
if (!isStateChanged) {
isStateChanged = true
for (i in usedBy.indices) {
usedBy[i].triggerUpdate()
}
}
}
protected fun usedBy(surface: UiSurface) {
if (surface !in usedBy) {
usedBy += surface
surface.registerState(this)
if (isStateChanged) {
surface.triggerUpdate()
}
}
}
open fun clearUsage(surface: UiSurface) {
usedBy -= surface
isStateChanged = false
}
}
open class MutableStateValue<T: Any?>(initValue: T) : MutableState() {
private val stateListeners = mutableListOf<(T) -> Unit>()
var value: T = initValue
set(value) {
if (value != field) {
stateChanged()
notifyListeners(value)
}
field = value
}
private fun notifyListeners(newState: T) {
if (stateListeners.isNotEmpty()) {
for (i in stateListeners.indices) {
stateListeners[i](newState)
}
}
}
fun set(value: T) {
this.value = value
}
fun use(surface: UiSurface): T {
usedBy(surface)
return value
}
fun onChange(block: (T) -> Unit): MutableStateValue<T> {
stateListeners += block
return this
}
override fun toString(): String {
return "mutableStateOf($value)"
}
}
class MutableStateList<T>(private val values: MutableList<T> = mutableListOf()) :
MutableState(), MutableList<T> by values
{
fun use(surface: UiSurface): MutableStateList<T> {
usedBy(surface)
return this
}
override fun add(element: T): Boolean {
stateChanged()
return values.add(element)
}
override fun add(index: Int, element: T) {
stateChanged()
values.add(index, element)
}
override fun addAll(index: Int, elements: Collection<T>): Boolean {
stateChanged()
return values.addAll(index, elements)
}
override fun addAll(elements: Collection<T>): Boolean {
stateChanged()
return values.addAll(elements)
}
override fun clear() {
if (isNotEmpty()) {
stateChanged()
}
values.clear()
}
override fun remove(element: T): Boolean {
val result = values.remove(element)
if (result) {
stateChanged()
}
return result
}
override fun removeAll(elements: Collection<T>): Boolean {
val result = values.removeAll(elements)
if (result) {
stateChanged()
}
return result
}
override fun removeAt(index: Int): T {
stateChanged()
return values.removeAt(index)
}
override fun retainAll(elements: Collection<T>): Boolean {
val result = values.retainAll(elements)
if (result) {
stateChanged()
}
return result
}
override fun set(index: Int, element: T): T {
stateChanged()
return values.set(index, element)
}
} | apache-2.0 | 6400267bc4651417daf1a41f2d7d522b | 23.455172 | 102 | 0.565585 | 4.556555 | false | false | false | false |
kohesive/kohesive-iac | cloudtrail-tool/src/main/kotlin/uy/kohesive/iac/model/aws/cloudtrail/postprocessing/CreateBucketProcessor.kt | 1 | 852 | package uy.kohesive.iac.model.aws.cloudtrail.postprocessing
import com.amazonaws.codegen.model.intermediate.IntermediateModel
import uy.kohesive.iac.model.aws.cloudtrail.RequestMapNode
class CreateBucketProcessor : RequestNodePostProcessor {
override val shapeNames = listOf("CreateBucketInput")
override fun process(requestMapNode: RequestMapNode, awsModel: IntermediateModel): RequestMapNode = requestMapNode.members.firstOrNull {
it.memberModel.c2jName == "BucketName"
}?.let { bucketNameMember ->
requestMapNode.copy(
members = (requestMapNode.members - bucketNameMember).toMutableList(),
constructorArgs = (requestMapNode.constructorArgs + bucketNameMember).toMutableList()
)
} ?: throw IllegalStateException("CreateBucketRequest request does not contain bucket name")
} | mit | 8b6a52a3241ece6626977191424ba40d | 43.894737 | 140 | 0.758216 | 4.953488 | false | false | false | false |
kickstarter/android-oss | app/src/test/java/com/kickstarter/models/MessageThreadTest.kt | 1 | 2490 | package com.kickstarter.models
import com.kickstarter.mock.factories.BackingFactory
import com.kickstarter.mock.factories.MessageThreadFactory
import com.kickstarter.mock.factories.ProjectFactory
import junit.framework.TestCase
import org.joda.time.DateTime
import org.junit.Test
class MessageThreadTest : TestCase() {
@Test
fun testDefaultInit() {
val dateTime: DateTime = DateTime.now().plusMillis(300)
val message = Message.builder().createdAt(dateTime).build()
val project = ProjectFactory.allTheWayProject()
val user = User.builder().build()
val backing = BackingFactory.backing(user)
val messageThread = MessageThread.builder()
.lastMessage(message)
.unreadMessagesCount(0)
.participant(user)
.backing(backing)
.project(project)
.build()
assertEquals(messageThread.id(), 0L)
assertEquals(messageThread.closed(), false)
assertEquals(messageThread.lastMessage(), message)
assertEquals(messageThread.backing(), backing)
assertEquals(messageThread.participant(), user)
assertEquals(messageThread.project(), project)
assertEquals(messageThread.unreadMessagesCount(), 0)
}
@Test
fun testMessageThread_equalFalse() {
val messageThread = MessageThread.builder().build()
val messageThread2 = MessageThread.builder().project(ProjectFactory.backedProject()).build()
val messageThread3 = MessageThread.builder().project(ProjectFactory.allTheWayProject()).id(5678L).build()
val messageThread4 = MessageThread.builder().project(ProjectFactory.allTheWayProject()).build()
assertFalse(messageThread == messageThread2)
assertFalse(messageThread == messageThread3)
assertFalse(messageThread == messageThread4)
assertFalse(messageThread3 == messageThread2)
assertFalse(messageThread3 == messageThread4)
}
@Test
fun testMessageThread_equalTrue() {
val messageThread1 = MessageThread.builder().build()
val messageThread2 = MessageThread.builder().build()
assertEquals(messageThread1, messageThread2)
}
@Test
fun testMessageThreadToBuilder() {
val project = ProjectFactory.allTheWayProject()
val messageThread = MessageThreadFactory.messageThread().toBuilder()
.project(project).build()
assertEquals(messageThread.project(), project)
}
}
| apache-2.0 | 5aa3fd29852beccbab87624050fb6e1e | 35.617647 | 113 | 0.695181 | 4.797688 | false | true | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/helpers/RecyclerViewEmptySupport.kt | 1 | 1645 | package com.habitrpg.android.habitica.ui.helpers
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.RecyclerView
//http://stackoverflow.com/a/27801394/1315039
class RecyclerViewEmptySupport : RecyclerView {
private var emptyView: View? = null
private val observer = object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
checkIfEmpty()
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
checkIfEmpty()
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
checkIfEmpty()
}
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
internal fun checkIfEmpty() {
if (emptyView != null && adapter != null) {
val emptyViewVisible = adapter?.itemCount == 0
emptyView?.visibility = if (emptyViewVisible) View.VISIBLE else View.GONE
visibility = if (emptyViewVisible) View.GONE else View.VISIBLE
}
}
override fun setAdapter(adapter: Adapter<*>?) {
val oldAdapter = getAdapter()
oldAdapter?.unregisterAdapterDataObserver(observer)
super.setAdapter(adapter)
adapter?.registerAdapterDataObserver(observer)
checkIfEmpty()
}
fun setEmptyView(emptyView: View?) {
this.emptyView = emptyView
checkIfEmpty()
}
}
| gpl-3.0 | 7f579e978aa53aa9ce98297c4f9c7dea | 30.634615 | 103 | 0.67234 | 4.910448 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/AppearanceOptionsTopHitProvider.kt | 1 | 3443 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.ui
import com.intellij.application.options.editor.CheckboxDescriptor
import com.intellij.ide.IdeBundle.message
import com.intellij.ide.ui.search.BooleanOptionDescription
import com.intellij.notification.impl.NotificationsConfigurationImpl
import com.intellij.openapi.util.NlsContexts.Label
import com.intellij.openapi.util.text.Strings
import java.util.function.Supplier
// @formatter:off
internal val uiOptionGroupName get() = message("appearance.ui.option.group")
internal val windowOptionGroupName get() = message("appearance.window.option.group")
internal val viewOptionGroupName get() = message("appearance.view.option.group")
private val settings get() = UISettings.instance
private val notificationSettings get() = NotificationsConfigurationImpl.getInstanceImpl()
private val cdShowMainToolbar get() = CheckboxDescriptor(message("show.main.toolbar"), settings::showMainToolbar, groupName = viewOptionGroupName)
private val cdShowStatusBar get() = CheckboxDescriptor(message("show.status.bar"), settings::showStatusBar, groupName = viewOptionGroupName)
private val cdShowNavigationBar get() = CheckboxDescriptor(message("show.navigation.bar"), settings::showNavigationBar, groupName = viewOptionGroupName)
private val cdShowMembersInNavigationBar get() = CheckboxDescriptor(message("show.members.in.navigation.bar"), settings::showMembersInNavigationBar, groupName = viewOptionGroupName)
private val cdUseSmallTabLabels get() = CheckboxDescriptor(message("small.labels.in.editor.tabs"), settings::useSmallLabelsOnTabs, groupName = windowOptionGroupName)
private val cdShowEditorPreview get() = CheckboxDescriptor(OptionsTopHitProvider.messageIde("checkbox.show.editor.preview.popup"), settings::showEditorToolTip, groupName = windowOptionGroupName)
private val cdShowBalloons get() = CheckboxDescriptor(message("display.balloon.notifications"), notificationSettings::SHOW_BALLOONS, groupName = uiOptionGroupName)
// @formatter:on
private val optionDescriptors
get() = listOf(
cdShowMainToolbar,
cdShowStatusBar,
cdShowNavigationBar,
cdShowMembersInNavigationBar,
cdUseSmallTabLabels,
cdShowEditorPreview,
cdShowBalloons
).map(CheckboxDescriptor::asUiOptionDescriptor)
class AppearanceOptionsTopHitProvider : OptionsSearchTopHitProvider.ApplicationLevelProvider {
override fun getId() = ID
override fun getOptions() = appearanceOptionDescriptors + optionDescriptors
companion object {
const val ID = "appearance"
@JvmStatic
fun option(@Label option: String, propertyName: String, configurableId: String): BooleanOptionDescription {
return object : PublicMethodBasedOptionDescription(option, configurableId,
"get" + Strings.capitalize(propertyName),
"set" + Strings.capitalize(propertyName), Supplier { UISettings.instance.state }) {
override fun fireUpdated() = UISettings.instance.fireUISettingsChanged()
}
}
@JvmStatic
fun appearance(@Label option: String, propertyName: String) = option(option, propertyName, "preferences.lookFeel")
}
} | apache-2.0 | 93bb2bdbb86d469e6bf547785de86b03 | 56.4 | 209 | 0.753413 | 5.131148 | false | true | false | false |
jwren/intellij-community | tools/intellij.ide.starter/src/com/intellij/ide/starter/path/IDEDataPaths.kt | 1 | 2954 | package com.intellij.ide.starter.path
import com.intellij.ide.starter.ci.CIServer
import com.intellij.ide.starter.di.di
import com.intellij.ide.starter.utils.FileSystem.getFileOrDirectoryPresentableSize
import com.intellij.ide.starter.utils.createInMemoryDirectory
import com.intellij.ide.starter.utils.logOutput
import org.kodein.di.direct
import org.kodein.di.instance
import java.io.Closeable
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.createDirectories
import kotlin.io.path.div
import kotlin.io.path.exists
import kotlin.streams.toList
class IDEDataPaths(
private val testHome: Path,
private val inMemoryRoot: Path?
) : Closeable {
companion object {
fun createPaths(testName: String, testHome: Path, useInMemoryFs: Boolean): IDEDataPaths {
testHome.toFile().deleteRecursively()
testHome.createDirectories()
val inMemoryRoot = if (useInMemoryFs) {
createInMemoryDirectory("ide-integration-test-$testName")
}
else {
null
}
return IDEDataPaths(testHome = testHome, inMemoryRoot = inMemoryRoot)
}
}
val logsDir = (testHome / "log").createDirectories()
val reportsDir = (testHome / "reports").createDirectories()
val snapshotsDir = (testHome / "snapshots").createDirectories()
val tempDir = (testHome / "temp").createDirectories()
// Directory used to store TeamCity artifacts. To make sure the TeamCity publishes all artifacts
// files added to this directory must not be removed until the end of the tests execution .
val teamCityArtifacts = (testHome / "team-city-artifacts").createDirectories()
val configDir = ((inMemoryRoot ?: testHome) / "config").createDirectories()
val systemDir = ((inMemoryRoot ?: testHome) / "system").createDirectories()
val pluginsDir = (testHome / "plugins").createDirectories()
override fun close() {
if (inMemoryRoot != null) {
try {
inMemoryRoot.toFile().deleteRecursively()
}
catch (e: Exception) {
logOutput("! Failed to unmount in-memory FS at $inMemoryRoot")
e.stackTraceToString().lines().forEach { logOutput(" $it") }
}
}
if (di.direct.instance<CIServer>().isBuildRunningOnCI) {
deleteDirectories()
}
}
private fun deleteDirectories() {
val toDelete = getDirectoriesToDeleteAfterTest().filter { it.exists() }
if (toDelete.isNotEmpty()) {
logOutput(buildString {
appendLine("Removing directories of $testHome")
toDelete.forEach { path ->
appendLine(" $path: ${path.getFileOrDirectoryPresentableSize()}")
}
})
}
toDelete.forEach { runCatching { it.toFile().deleteRecursively() } }
}
private fun getDirectoriesToDeleteAfterTest() = if (testHome.exists()) {
Files.list(testHome).use { it.toList() } - listOf(teamCityArtifacts)
}
else {
emptyList()
}
override fun toString(): String = "IDE Test Paths at $testHome"
} | apache-2.0 | 24a092c07837c9b1f8f233165bd5c12c | 32.202247 | 98 | 0.703114 | 4.262626 | false | true | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddForLoopIndicesIntention.kt | 1 | 4849 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.utils.ChooseStringExpression
class AddForLoopIndicesIntention : SelfTargetingRangeIntention<KtForExpression>(
KtForExpression::class.java,
KotlinBundle.lazyMessage("add.indices.to.for.loop"),
), LowPriorityAction {
override fun applicabilityRange(element: KtForExpression): TextRange? {
if (element.loopParameter == null) return null
if (element.loopParameter?.destructuringDeclaration != null) return null
val loopRange = element.loopRange ?: return null
val bindingContext = element.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val resolvedCall = loopRange.getResolvedCall(bindingContext)
if (resolvedCall?.resultingDescriptor?.fqNameUnsafe?.asString() in WITH_INDEX_FQ_NAMES) return null // already withIndex() call
val potentialExpression = createWithIndexExpression(loopRange, reformat = false)
val newBindingContext = potentialExpression.analyzeAsReplacement(loopRange, bindingContext)
val newResolvedCall = potentialExpression.getResolvedCall(newBindingContext) ?: return null
if (newResolvedCall.resultingDescriptor.fqNameUnsafe.asString() !in WITH_INDEX_FQ_NAMES) return null
return TextRange(element.startOffset, element.body?.startOffset ?: element.endOffset)
}
override fun applyTo(element: KtForExpression, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val loopRange = element.loopRange!!
val loopParameter = element.loopParameter!!
val psiFactory = KtPsiFactory(element.project)
loopRange.replace(createWithIndexExpression(loopRange, reformat = true))
var multiParameter = (psiFactory.createExpressionByPattern(
"for((index, $0) in x){}",
loopParameter.text
) as KtForExpression).destructuringDeclaration!!
multiParameter = loopParameter.replaced(multiParameter)
val indexVariable = multiParameter.entries[0]
editor.caretModel.moveToOffset(indexVariable.startOffset)
runTemplate(editor, element, indexVariable)
}
private fun runTemplate(editor: Editor, forExpression: KtForExpression, indexVariable: KtDestructuringDeclarationEntry) {
PsiDocumentManager.getInstance(forExpression.project).doPostponedOperationsAndUnblockDocument(editor.document)
val templateBuilder = TemplateBuilderImpl(forExpression)
templateBuilder.replaceElement(indexVariable, ChooseStringExpression(listOf("index", "i")))
when (val body = forExpression.body) {
is KtBlockExpression -> {
val statement = body.statements.firstOrNull()
if (statement != null) {
templateBuilder.setEndVariableBefore(statement)
} else {
templateBuilder.setEndVariableAfter(body.lBrace)
}
}
null -> forExpression.rightParenthesis.let { templateBuilder.setEndVariableAfter(it) }
else -> templateBuilder.setEndVariableBefore(body)
}
templateBuilder.run(editor, true)
}
private fun createWithIndexExpression(originalExpression: KtExpression, reformat: Boolean): KtExpression =
KtPsiFactory(originalExpression.project).createExpressionByPattern(
"$0.$WITH_INDEX_NAME()", originalExpression,
reformat = reformat
)
companion object {
private val WITH_INDEX_NAME = "withIndex"
private val WITH_INDEX_FQ_NAMES: Set<String> by lazy {
sequenceOf("collections", "sequences", "text", "ranges").map { "kotlin.$it.$WITH_INDEX_NAME" }.toSet()
}
}
}
| apache-2.0 | 7403baa7f4c42d4846f9a9251e1a5c79 | 46.07767 | 158 | 0.737472 | 5.180556 | false | false | false | false |
androidx/androidx | compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/ChipSamples.kt | 3 | 7087 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.AssistChip
import androidx.compose.material3.AssistChipDefaults
import androidx.compose.material3.ElevatedAssistChip
import androidx.compose.material3.ElevatedFilterChip
import androidx.compose.material3.ElevatedSuggestionChip
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.InputChip
import androidx.compose.material3.InputChipDefaults
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun AssistChipSample() {
AssistChip(
onClick = { /* Do something! */ },
label = { Text("Assist Chip") },
leadingIcon = {
Icon(
Icons.Filled.Settings,
contentDescription = "Localized description",
Modifier.size(AssistChipDefaults.IconSize)
)
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun ElevatedAssistChipSample() {
ElevatedAssistChip(
onClick = { /* Do something! */ },
label = { Text("Assist Chip") },
leadingIcon = {
Icon(
Icons.Filled.Settings,
contentDescription = "Localized description",
Modifier.size(AssistChipDefaults.IconSize)
)
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun FilterChipSample() {
var selected by remember { mutableStateOf(false) }
FilterChip(
selected = selected,
onClick = { selected = !selected },
label = { Text("Filter chip") },
leadingIcon = if (selected) {
{
Icon(
imageVector = Icons.Filled.Done,
contentDescription = "Localized Description",
modifier = Modifier.size(FilterChipDefaults.IconSize)
)
}
} else {
null
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun ElevatedFilterChipSample() {
var selected by remember { mutableStateOf(false) }
ElevatedFilterChip(
selected = selected,
onClick = { selected = !selected },
label = { Text("Filter chip") },
leadingIcon = if (selected) {
{
Icon(
imageVector = Icons.Filled.Done,
contentDescription = "Localized Description",
modifier = Modifier.size(FilterChipDefaults.IconSize)
)
}
} else {
null
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun FilterChipWithLeadingIconSample() {
var selected by remember { mutableStateOf(false) }
FilterChip(
selected = selected,
onClick = { selected = !selected },
label = { Text("Filter chip") },
leadingIcon = if (selected) {
{
Icon(
imageVector = Icons.Filled.Done,
contentDescription = "Localized Description",
modifier = Modifier.size(FilterChipDefaults.IconSize)
)
}
} else {
{
Icon(
imageVector = Icons.Filled.Home,
contentDescription = "Localized description",
modifier = Modifier.size(FilterChipDefaults.IconSize)
)
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun InputChipSample() {
var selected by remember { mutableStateOf(false) }
InputChip(
selected = selected,
onClick = { selected = !selected },
label = { Text("Input Chip") },
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun InputChipWithAvatarSample() {
var selected by remember { mutableStateOf(false) }
InputChip(
selected = selected,
onClick = { selected = !selected },
label = { Text("Input Chip") },
avatar = {
Icon(
Icons.Filled.Person,
contentDescription = "Localized description",
Modifier.size(InputChipDefaults.AvatarSize)
)
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun SuggestionChipSample() {
SuggestionChip(
onClick = { /* Do something! */ },
label = { Text("Suggestion Chip") }
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun ElevatedSuggestionChipSample() {
ElevatedSuggestionChip(
onClick = { /* Do something! */ },
label = { Text("Suggestion Chip") }
)
}
@Preview
@Sampled
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChipGroupSingleLineSample() {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Row(modifier = Modifier.horizontalScroll(rememberScrollState())) {
repeat(9) { index ->
AssistChip(
modifier = Modifier.padding(horizontal = 4.dp),
onClick = { /* do something*/ },
label = { Text("Chip $index") }
)
}
}
}
}
| apache-2.0 | 18946afb19e8c07893c5ced5c76edb42 | 28.65272 | 75 | 0.645125 | 4.734135 | false | false | false | false |
androidx/androidx | glance/glance-wear-tiles/src/androidMain/kotlin/androidx/glance/wear/tiles/curved/CurvedProperties.kt | 3 | 4405 | /*
* 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.glance.wear.tiles.curved
import androidx.compose.runtime.Immutable
import androidx.compose.ui.unit.TextUnit
import androidx.glance.text.FontStyle
import androidx.glance.text.FontWeight
import androidx.glance.unit.ColorProvider
/**
* The alignment of a [CurvedRow]'s elements, with respect to its anchor angle. This specifies how
* elements added to a [CurvedRow] should be laid out with respect to the [CurvedRow]'s anchor
* angle.
*
* As an example, assume that the following diagrams are wrapped to an arc, and
* each represents a [CurvedRow] element containing a single text element. The text
* element's anchor angle is "0" for all cases.
*
* ```
* AnchorType.Start:
* -180 0 180
* Hello World!
*
*
* AnchorType.Center:
* -180 0 180
* Hello World!
*
* AnchorType.End:
* -180 0 180
* Hello World!
* ```
*/
@JvmInline
public value class AnchorType private constructor(private val value: Int) {
public companion object {
/**
* Anchor at the start of the elements. This will cause elements added to a
* [CurvedRow] to begin at the given anchor angle, and sweep around to the right.
*/
public val Start: AnchorType = AnchorType(0)
/**
* Anchor at the center of the elements. This will cause the center of the
* whole set of elements added to a [CurvedRow] to be pinned at the given anchor angle.
*/
public val Center: AnchorType = AnchorType(1)
/**
* Anchor at the end of the elements. This will cause the set of elements
* inside the [CurvedRow] to end at the specified anchor angle, i.e. all elements
* should be to the left of anchor angle.
*/
public val End: AnchorType = AnchorType(2)
}
}
/**
* How to lay down components when they are thinner than the [CurvedRow]. Similar to vertical
* alignment in a Row.
*/
@JvmInline
public value class RadialAlignment private constructor(private val value: Int) {
companion object {
/**
* Put the child closest to the center of the [CurvedRow], within the available space
*/
val Inner = RadialAlignment(0)
/**
* Put the child in the middle point of the available space.
*/
val Center = RadialAlignment(1)
/**
* Put the child farthest from the center of the [CurvedRow], within the available space
*/
val Outer = RadialAlignment(2)
}
}
/**
* Description of a text style for the [CurvedScope.curvedText] composable.
*/
@Immutable
public class CurvedTextStyle(
public val color: ColorProvider? = null,
public val fontSize: TextUnit? = null,
public val fontWeight: FontWeight? = null,
public val fontStyle: FontStyle? = null
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is CurvedTextStyle) return false
if (color != other.color) return false
if (fontSize != other.fontSize) return false
if (fontWeight != other.fontWeight) return false
if (fontStyle != other.fontStyle) return false
return true
}
override fun hashCode(): Int {
var result = fontSize.hashCode()
result = 31 * result + fontWeight.hashCode()
result = 31 * result + fontStyle.hashCode()
return result
}
override fun toString() =
"TextStyle(size=$fontSize, fontWeight=$fontWeight, fontStyle=$fontStyle)"
}
| apache-2.0 | aad3427b4b7516ca449228725281d1ab | 33.414063 | 98 | 0.62361 | 4.50409 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/KeyChildImpl.kt | 2 | 9354 | // 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.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class KeyChildImpl(val dataSource: KeyChildData) : KeyChild, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(KeyParent::class.java, KeyChild::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val data: String
get() = dataSource.data
override val parentEntity: KeyParent
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!!
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: KeyChildData?) : ModifiableWorkspaceEntityBase<KeyChild, KeyChildData>(result), KeyChild.Builder {
constructor() : this(KeyChildData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity KeyChild is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field KeyChild#data should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field KeyChild#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field KeyChild#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as KeyChild
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.data != dataSource.data) this.data = dataSource.data
if (parents != null) {
val parentEntityNew = parents.filterIsInstance<KeyParent>().single()
if ((this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id) {
this.parentEntity = parentEntityNew
}
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData(true).data = value
changedProperty.add("data")
}
override var parentEntity: KeyParent
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as KeyParent
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as KeyParent
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityClass(): Class<KeyChild> = KeyChild::class.java
}
}
class KeyChildData : WorkspaceEntityData<KeyChild>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<KeyChild> {
val modifiable = KeyChildImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): KeyChild {
return getCached(snapshot) {
val entity = KeyChildImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return KeyChild::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return KeyChild(data, entitySource) {
this.parentEntity = parents.filterIsInstance<KeyParent>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(KeyParent::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as KeyChildData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as KeyChildData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | b18a300210754964874033c045713625 | 35.539063 | 147 | 0.688155 | 5.142386 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/common/collectors/CommonConstraintsCollector.kt | 2 | 6942 | // 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.j2k.post.processing.inference.common.collectors
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.BoundTypeCalculator
import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintBuilder
import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.InferenceContext
import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.asBoundType
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.asAssignment
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class CommonConstraintsCollector : ConstraintsCollector() {
override fun ConstraintBuilder.collectConstraints(
element: KtElement,
boundTypeCalculator: BoundTypeCalculator,
inferenceContext: InferenceContext,
resolutionFacade: ResolutionFacade
) = with(boundTypeCalculator) {
when {
element is KtBinaryExpressionWithTypeRHS && KtPsiUtil.isUnsafeCast(element) -> {
element.right?.typeElement?.let { inferenceContext.typeElementToTypeVariable[it] }?.also { typeVariable ->
element.left.isSubtypeOf(
typeVariable,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.ASSIGNMENT
)
}
}
element is KtBinaryExpression && element.asAssignment() != null -> {
element.right?.isSubtypeOf(
element.left ?: return,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.ASSIGNMENT
)
}
element is KtVariableDeclaration -> {
inferenceContext.declarationToTypeVariable[element]?.also { typeVariable ->
element.initializer?.isSubtypeOf(
typeVariable,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.INITIALIZER
)
}
}
element is KtParameter -> {
inferenceContext.declarationToTypeVariable[element]?.also { typeVariable ->
element.defaultValue?.isSubtypeOf(
typeVariable,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.INITIALIZER
)
}
}
element is KtReturnExpression -> {
val functionTypeVariable = element.getTargetFunction(element.analyze(resolutionFacade))
?.resolveToDescriptorIfAny(resolutionFacade)
?.let { functionDescriptor ->
inferenceContext.declarationDescriptorToTypeVariable[functionDescriptor]
} ?: return
element.returnedExpression?.isSubtypeOf(
functionTypeVariable,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.RETURN
)
}
element is KtReturnExpression -> {
val targetTypeVariable =
element.getTargetFunction(element.analyze(resolutionFacade))?.let { function ->
inferenceContext.declarationToTypeVariable[function]
}
if (targetTypeVariable != null) {
element.returnedExpression?.isSubtypeOf(
targetTypeVariable,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.RETURN
)
}
}
element is KtLambdaExpression -> {
val targetTypeVariable =
inferenceContext.declarationToTypeVariable[element.functionLiteral] ?: return
element.functionLiteral.bodyExpression?.statements?.lastOrNull()
?.takeIf { it !is KtReturnExpression }
?.also { implicitReturn ->
implicitReturn.isSubtypeOf(
targetTypeVariable,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.RETURN
)
}
}
element is KtForExpression -> {
val loopParameterTypeVariable =
element.loopParameter?.typeReference?.typeElement?.let { typeElement ->
inferenceContext.typeElementToTypeVariable[typeElement]
}
if (loopParameterTypeVariable != null) {
val loopRangeBoundType = element.loopRange?.boundType(inferenceContext) ?: return
val boundType =
element.loopRangeElementType(resolutionFacade)
?.boundType(
contextBoundType = loopRangeBoundType,
inferenceContext = inferenceContext
) ?: return
boundType.typeParameters.firstOrNull()?.boundType?.isSubtypeOf(
loopParameterTypeVariable.asBoundType(),
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.ASSIGNMENT
)
}
}
}
Unit
}
private fun KtForExpression.loopRangeElementType(resolutionFacade: ResolutionFacade): KotlinType? {
val loopRangeType = loopRange?.getType(analyze(resolutionFacade)) ?: return null
return loopRangeType
.constructor
.declarationDescriptor
?.safeAs<ClassDescriptor>()
?.getMemberScope(loopRangeType.arguments)
?.getDescriptorsFiltered(DescriptorKindFilter.FUNCTIONS) {
it.asString() == "iterator"
}?.filterIsInstance<FunctionDescriptor>()
?.firstOrNull { it.valueParameters.isEmpty() }
?.original
?.returnType
}
} | apache-2.0 | 5e60c40551f66f2344aec267ca16e67c | 47.552448 | 158 | 0.616537 | 6.176157 | false | false | false | false |
zhiayang/pew | core/src/main/kotlin/Entities/MobAI/PlayerController.kt | 1 | 1071 | // Copyright (c) 2014 Orion Industries, [email protected]
// Licensed under the Apache License version 2.0
package Entities.MobAI
import Entities.CharacterEntity
import com.badlogic.gdx.math.Vector2
import Utilities.InputManager
import java.util.HashSet
public class PlayerController(owner: CharacterEntity) : CharacterAI(owner)
{
init
{
this.owner.game.input.Register(this.owner.game.input.CreateKeySet("up", "down", "left", "right", "space"),
InputManager.ReceiverAction(InputManager.KeyState.Down)
{
false
})
}
override fun Update(): Vector2
{
var input: Vector2 = Vector2()
var keys: MutableSet<String> = HashSet()
this.owner.game.input.getKeysDown().forEach {keys.add(this.owner.game.input.TranslateKey(it))}
if (keys.contains("space"))
this.owner.
if (keys.contains("left"))
input.x = -1.0f
else if (keys.contains("right"))
input.x = +1.0f
else
input.x = 0.0f
if (keys.contains("up"))
input.y = +1.0f
else if (keys.contains("down"))
input.y = -1.0f
else
input.y = 0.0f
return input
}
}
| apache-2.0 | cf55bb34c8aaba95a4abb803b9c556ef | 20.857143 | 108 | 0.690943 | 2.99162 | false | false | false | false |
siosio/intellij-community | plugins/ide-features-trainer/src/training/ui/welcomeScreen/IFTInteractiveCourse.kt | 1 | 4357 | // 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 training.ui.welcomeScreen
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.wm.InteractiveCourseData
import com.intellij.openapi.wm.InteractiveCourseFactory
import com.intellij.openapi.wm.impl.welcomeScreen.learnIde.HeightLimitedPane
import com.intellij.openapi.wm.impl.welcomeScreen.learnIde.LearnIdeContentColorsAndFonts
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.scale.JBUIScale
import training.FeaturesTrainerIcons
import training.learn.CourseManager
import training.learn.LearnBundle
import training.learn.OpenLessonActivities
import training.learn.course.IftModule
import training.learn.course.KLesson
import training.statistic.StatisticBase
import training.util.rigid
import java.awt.event.ActionEvent
import javax.swing.*
import javax.swing.plaf.FontUIResource
import javax.swing.plaf.LabelUI
internal class IFTInteractiveCourse : InteractiveCourseFactory {
override fun getInteractiveCourseData(): InteractiveCourseData = IFTInteractiveCourseData()
}
private class IFTInteractiveCourseData : InteractiveCourseData {
override fun getName(): String {
return LearnBundle.message("welcome.tab.header.learn.ide.features")
}
override fun getDescription(): String {
return LearnBundle.message("welcome.tab.description.learn.ide.features")
}
override fun getIcon(): Icon {
return FeaturesTrainerIcons.Img.PluginIcon
}
override fun getActionButtonName(): String {
return LearnBundle.message("welcome.tab.start.learning.button")
}
override fun getAction(): Action {
return object : AbstractAction(LearnBundle.message("welcome.tab.start.learning.button")) {
override fun actionPerformed(e: ActionEvent?) {
openLearningFromWelcomeScreen(null)
}
}
}
override fun getExpandContent(): JComponent {
val modules = CourseManager.instance.modules
val panel = JPanel()
panel.isOpaque = false
panel.layout = BoxLayout(panel, BoxLayout.PAGE_AXIS)
panel.add(rigid(16, 1))
for (module in modules) {
panel.add(moduleHeader(module))
panel.add(rigid(2, 2))
panel.add(moduleDescription(module))
panel.add(rigid(16, 16))
}
panel.add(rigid(16, 15))
StatisticBase.logWelcomeScreenPanelExpanded()
return panel
}
private fun moduleDescription(module: IftModule): HeightLimitedPane {
return HeightLimitedPane(module.description, -1, LearnIdeContentColorsAndFonts.ModuleDescriptionColor)
}
private fun moduleHeader(module: IftModule): LinkLabel<Any> {
val linkLabel = object : LinkLabel<Any>(module.name, null) {
override fun setUI(ui: LabelUI?) {
super.setUI(ui)
if (font != null) {
font = FontUIResource(font.deriveFont(font.size2D + JBUIScale.scale(-1) + if (SystemInfo.isWindows) JBUIScale.scale(1) else 0))
}
}
}
linkLabel.name = "linkLabel.${module.name}"
linkLabel.setListener(
{ _, _ ->
StatisticBase.logModuleStarted(module)
openLearningFromWelcomeScreen(module)
}, null)
return linkLabel
}
private fun openLearningFromWelcomeScreen(module: IftModule?) {
val action = ActionManager.getInstance().getAction("ShowLearnPanel")
val onboardingLesson = findOnboardingLesson(module)
if (onboardingLesson != null) {
OpenLessonActivities.openOnboardingFromWelcomeScreen(onboardingLesson)
}
else {
CourseManager.instance.unfoldModuleOnInit = module ?: CourseManager.instance.modules.firstOrNull()
val anActionEvent = AnActionEvent.createFromAnAction(action, null, ActionPlaces.WELCOME_SCREEN, DataContext.EMPTY_CONTEXT)
ActionUtil.performActionDumbAwareWithCallbacks(action, anActionEvent)
}
}
private fun findOnboardingLesson(module: IftModule?): KLesson? {
val firstLesson = module?.lessons?.singleOrNull()
return firstLesson?.takeIf { it.id.contains("onboarding") }
}
}
| apache-2.0 | dcec87c5276ff8c31f38aee925cb02d9 | 36.239316 | 158 | 0.760845 | 4.515026 | false | false | false | false |
Shurup228/brainfuck_kotlin | src/Interpreter.kt | 1 | 1517 | import java.util.LinkedList
import java.util.Scanner
class Interpreter(code: String) {
private val field: Field = Field()
private val instructions: LinkedList<Token> = Parser(code).tokens
private var index: Int = 0
private val scanner: Scanner = Scanner(System.`in`)
fun run(start: Int = 0, end: Int = instructions.lastIndex) {
index = start
while (index <= end) {
val instruction = instructions[index]
when (instruction) {
Print -> print(field.current)
Write -> field.current = scanner.next()[0]
is Move -> field.move(instruction.value)
is ChangeValue -> field.change(instruction.value)
is OpenLoop -> {
if (field.current.toInt() == 0) {
index = instruction.closeLoopIndex
} else {
run(index + 1, instruction.closeLoopIndex - 1) // if we don't substract 1
index -= 1 // from that value, run will go into recursion and then add to index
} // number of loops it encounter and we need to substract from index, so that
} // it won't pass one instruction right after the CloseLoop token
is CloseLoop -> {
if (field.current.toInt() != 0) {
index = instruction.openLoopIndex - 1
}
}
}
index += 1
}
}
} | mit | 8b159700edc8d712e47de6bd78bb08f9 | 41.166667 | 103 | 0.522083 | 4.862179 | false | false | false | false |
vovagrechka/fucking-everything | aplight/src/main/java/aplight/aplight-2.kt | 1 | 2905 | package aplight
import fuckotlin.psi.KtFile
import kotlinx.coroutines.experimental.*
import psikopath.parseKtFiles
import vgrechka.*
import java.io.File
import java.util.*
import kotlin.concurrent.thread
import kotlin.coroutines.experimental.CoroutineContext
object CodeGen {
private val jobs = mutableListOf<Job>()
private val allKotlinSourceFiles = Collections.synchronizedSet(mutableSetOf<File>())
private val allKtFilesPromise = CompletableDeferred<List<KtFile>>()
fun requestKotlinFilesParsing(files: List<File>): Deferred<List<KtFile>> {
fun normalize(path: String) = path.toLowerCase().replace("\\", "/")
allKotlinSourceFiles += files
return async {
val allKtFiles = allKtFilesPromise.await()
val filesNotFound = mutableListOf<File>() // We ignore compiler errors, but are going to bitch if files don't even exist
val ktFiles = mutableListOf<KtFile>()
for (file in files) {
val ktFile = allKtFiles.find {normalize(it.virtualFilePath) == normalize(file.path)}
if (ktFile == null)
filesNotFound += file
else
ktFiles += ktFile
}
if (filesNotFound.isNotEmpty())
bitch("Source files not found: ${filesNotFound.map {it.path}}")
ktFiles
}
}
fun scheduleJob(block: suspend () -> Unit) {
jobs += launch(
context = DefaultDispatcher + object : CoroutineExceptionHandler {
override val key = CoroutineExceptionHandler.Key
override fun handleException(context: CoroutineContext, exception: Throwable) {
ApLight.failed.set(true)
Thread {
exception.printStackTrace()
System.err.flush()
System.out.flush()
// System.exit(1)
}.also {
// XXX By default, thread created in this context is daemon (because parent is daemon),
// and it doesn't even have enough time to even print stack trace.
// Just printing stack trace (without spawning separate thread) is also not an option, cause main thread terminates faster
it.isDaemon = false
it.start()
}
}
},
start = CoroutineStart.DEFAULT) {
block()}
}
fun parseKotlinFilesAndWaitJobs() = runBlocking {
val sourceFiles = allKotlinSourceFiles.toList()
// clog("Parsing .kt files: $sourceFiles")
val parsedFiles = parseKtFiles(sourceFiles)
// clog("Got parsed .kt files: $parsedFiles")
allKtFilesPromise.complete(parsedFiles)
jobs.forEach {it.join()}
}
}
| apache-2.0 | 9d6eddf471106a045373d10b9323d75c | 35.3125 | 146 | 0.581756 | 5.369686 | false | false | false | false |
GunoH/intellij-community | plugins/settings-repository/src/RepositoryManager.kt | 2 | 3188 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.settingsRepository
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.containers.CollectionFactory
import java.io.InputStream
import java.util.*
interface RepositoryManager {
fun createRepositoryIfNeeded(): Boolean
/**
* Think twice before use
*/
fun deleteRepository()
fun isRepositoryExists(): Boolean
@NlsSafe
fun getUpstream(): String?
fun hasUpstream(): Boolean
/**
* Return error message if failed
*/
fun setUpstream(url: String?, branch: String? = null)
fun <R> read(path: String, consumer: (InputStream?) -> R): R
/**
* Returns false if file is not written (for example, due to ignore rules).
*/
fun write(path: String, content: ByteArray): Boolean
fun delete(path: String): Boolean
fun processChildren(path: String, filter: (name: String) -> Boolean, processor: (name: String, inputStream: InputStream) -> Boolean)
/**
* syncType will be passed if called before sync.
*
* If fixStateIfCannotCommit, repository state will be fixed before commit.
*/
suspend fun commit(syncType: SyncType? = null, fixStateIfCannotCommit: Boolean = true): Boolean
fun getAheadCommitsCount(): Int
suspend fun push()
suspend fun fetch(): Updater
suspend fun pull(): UpdateResult?
fun has(path: String): Boolean
suspend fun resetToTheirs(): UpdateResult?
suspend fun resetToMy(localRepositoryInitializer: (() -> Unit)?): UpdateResult?
fun canCommit(): Boolean
interface Updater {
suspend fun merge(): UpdateResult?
// valid only if merge was called before
val definitelySkipPush: Boolean
}
}
interface UpdateResult {
val changed: Collection<String>
val deleted: Collection<String>
}
internal val EMPTY_UPDATE_RESULT = ImmutableUpdateResult(Collections.emptySet(), Collections.emptySet())
internal data class ImmutableUpdateResult(override val changed: Collection<String>, override val deleted: Collection<String>) : UpdateResult {
fun toMutable() = MutableUpdateResult(changed, deleted)
}
internal class MutableUpdateResult(changed: Collection<String>, deleted: Collection<String>) : UpdateResult {
override val changed = CollectionFactory.createSmallMemoryFootprintSet(changed)
override val deleted = CollectionFactory.createSmallMemoryFootprintSet(deleted)
fun add(result: UpdateResult?): MutableUpdateResult {
if (result != null) {
add(result.changed, result.deleted)
}
return this
}
fun add(newChanged: Collection<String>, newDeleted: Collection<String>): MutableUpdateResult {
changed.removeAll(newDeleted)
deleted.removeAll(newChanged)
changed.addAll(newChanged)
deleted.addAll(newDeleted)
return this
}
fun addChanged(newChanged: Collection<String>): MutableUpdateResult {
deleted.removeAll(newChanged)
changed.addAll(newChanged)
return this
}
}
internal fun UpdateResult?.isEmpty() = this == null || (changed.isEmpty() && deleted.isEmpty())
internal class AuthenticationException(cause: Throwable) : RuntimeException(cause.message, cause) | apache-2.0 | 92617285ae53fc931244283de7b6a4fe | 27.72973 | 142 | 0.738394 | 4.681351 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/testFramework/src/org/jetbrains/intellij/build/testFramework/IdeStructureTestBase.kt | 2 | 4847 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.testFramework
import com.intellij.openapi.application.PathManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.SoftAssertions
import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension
import org.jetbrains.intellij.build.BuildContext
import org.jetbrains.intellij.build.IdeaProjectLoaderUtil
import org.jetbrains.intellij.build.ProductProperties
import org.jetbrains.intellij.build.ProprietaryBuildTools
import org.jetbrains.intellij.build.impl.DistributionJARsBuilder
import org.jetbrains.intellij.build.impl.ModuleStructureValidator
import org.jetbrains.jps.model.java.JpsJavaClasspathKind
import org.jetbrains.jps.model.java.JpsJavaDependencyScope
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModuleDependency
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.nio.file.Path
import java.util.*
@ExtendWith(SoftAssertionsExtension::class)
abstract class IdeStructureTestBase {
protected open val projectHome: Path
get() = Path.of(PathManager.getHomePathFor(javaClass)!!)
protected abstract fun createProductProperties(projectHome: Path): ProductProperties
protected abstract fun createBuildTools(): ProprietaryBuildTools
protected open val missingModulesException: Set<MissingModuleException>
get() = emptySet()
data class MissingModuleException(val fromModule: String, val toModule: String, val scope: JpsJavaDependencyScope)
private fun createBuildContext(): BuildContext {
val productProperties = createProductProperties(projectHome)
return runBlocking(Dispatchers.Default) {
createBuildContext(homePath = projectHome,
productProperties = productProperties,
buildTools = createBuildTools(),
skipDependencySetup = false,
communityHomePath = IdeaProjectLoaderUtil.guessCommunityHome(javaClass))
}
}
@Test
fun moduleStructureValidation(softly: SoftAssertions) {
val context = createBuildContext()
val jarBuilder = DistributionJARsBuilder(context, emptySet())
println("Packed modules:")
val moduleToJar = jarBuilder.state.platform.jarToModules.entries.asSequence()
.flatMap { it.value.map { e -> e to it.key } }
.groupBy(keySelector = { it.first }, valueTransform = { it.second })
.toSortedMap()
for (kv in moduleToJar) {
println(" ${kv.key} ${kv.value}")
}
val validator = ModuleStructureValidator(context, jarBuilder.state.platform.jarToModules)
val errors = validator.validate()
for (error in errors) {
softly.collectAssertionError(error)
}
}
@Test
fun moduleClosureValidation(softly: SoftAssertions) {
val buildContext = createBuildContext()
val jarBuilder = DistributionJARsBuilder(buildContext, emptySet())
val exceptions = missingModulesException
val activeExceptions = mutableSetOf<MissingModuleException>()
val moduleToJar = jarBuilder.state.platform.jarToModules.asSequence()
.flatMap { it.value.map { e -> e to it.key } }
.toMap(TreeMap())
for (kv in moduleToJar) {
val module = buildContext.findRequiredModule(kv.key)
for (dependency in module.dependenciesList.dependencies) {
if (dependency !is JpsModuleDependency) {
continue
}
val dependencyExtension = JpsJavaExtensionService.getInstance().getDependencyExtension(dependency)!!
if (!dependencyExtension.scope.isIncludedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME)) {
continue
}
val moduleDependency = dependency.module!!
if (!moduleToJar.containsKey(moduleDependency.name)) {
val missingModuleException = MissingModuleException(module.name, moduleDependency.name, dependencyExtension.scope)
if (exceptions.contains(missingModuleException)) {
activeExceptions.add(missingModuleException)
}
else {
val message = "${buildContext.productProperties.productCode} (${javaClass.simpleName}): missing module from the product layout '${moduleDependency.name}' referenced from '${module.name}' scope ${dependencyExtension.scope}"
softly.fail<Unit>(message)
}
}
}
}
for (moduleName in exceptions.minus(activeExceptions)) {
softly.fail<Unit>("${buildContext.productProperties.productCode} (${javaClass.simpleName}): module '$moduleName' is mentioned in ${::missingModulesException.name}, but it was not used. Please remove it from the list")
}
}
} | apache-2.0 | 7945fdacc7c3621c0dd86743cc91ba7e | 43.477064 | 234 | 0.732618 | 4.915822 | false | false | false | false |
mglukhikh/intellij-community | uast/uast-common/src/org/jetbrains/uast/visitor/UastVisitor.kt | 1 | 9450 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.visitor
import org.jetbrains.uast.*
interface UastVisitor {
fun visitElement(node: UElement): Boolean
fun visitFile(node: UFile): Boolean = visitElement(node)
fun visitImportStatement(node: UImportStatement): Boolean = visitElement(node)
fun visitDeclaration(node: UDeclaration) = visitElement(node)
fun visitClass(node: UClass): Boolean = visitDeclaration(node)
fun visitInitializer(node: UClassInitializer): Boolean = visitDeclaration(node)
fun visitMethod(node: UMethod): Boolean = visitDeclaration(node)
fun visitVariable(node: UVariable): Boolean = visitDeclaration(node)
fun visitParameter(node: UParameter): Boolean = visitVariable(node)
fun visitField(node: UField): Boolean = visitVariable(node)
fun visitLocalVariable(node: ULocalVariable): Boolean = visitVariable(node)
fun visitEnumConstant(node: UEnumConstant): Boolean = visitField(node)
fun visitAnnotation(node: UAnnotation): Boolean = visitElement(node)
// Expressions
fun visitExpression(node: UExpression) = visitElement(node)
fun visitLabeledExpression(node: ULabeledExpression) = visitExpression(node)
fun visitDeclarationsExpression(node: UDeclarationsExpression) = visitExpression(node)
fun visitBlockExpression(node: UBlockExpression) = visitExpression(node)
fun visitQualifiedReferenceExpression(node: UQualifiedReferenceExpression) = visitExpression(node)
fun visitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression) = visitExpression(node)
fun visitTypeReferenceExpression(node: UTypeReferenceExpression) = visitExpression(node)
fun visitCallExpression(node: UCallExpression) = visitExpression(node)
fun visitBinaryExpression(node: UBinaryExpression) = visitExpression(node)
fun visitBinaryExpressionWithType(node: UBinaryExpressionWithType) = visitExpression(node)
fun visitPolyadicExpression(node: UPolyadicExpression) = visitExpression(node)
fun visitParenthesizedExpression(node: UParenthesizedExpression) = visitExpression(node)
fun visitUnaryExpression(node: UUnaryExpression) = visitExpression(node)
fun visitPrefixExpression(node: UPrefixExpression) = visitExpression(node)
fun visitPostfixExpression(node: UPostfixExpression) = visitExpression(node)
fun visitExpressionList(node: UExpressionList) = visitExpression(node)
fun visitIfExpression(node: UIfExpression) = visitExpression(node)
fun visitSwitchExpression(node: USwitchExpression) = visitExpression(node)
fun visitSwitchClauseExpression(node: USwitchClauseExpression) = visitExpression(node)
fun visitWhileExpression(node: UWhileExpression) = visitExpression(node)
fun visitDoWhileExpression(node: UDoWhileExpression) = visitExpression(node)
fun visitForExpression(node: UForExpression) = visitExpression(node)
fun visitForEachExpression(node: UForEachExpression) = visitExpression(node)
fun visitTryExpression(node: UTryExpression) = visitExpression(node)
fun visitCatchClause(node: UCatchClause) = visitElement(node)
fun visitLiteralExpression(node: ULiteralExpression) = visitExpression(node)
fun visitThisExpression(node: UThisExpression) = visitExpression(node)
fun visitSuperExpression(node: USuperExpression) = visitExpression(node)
fun visitReturnExpression(node: UReturnExpression) = visitExpression(node)
fun visitBreakExpression(node: UBreakExpression) = visitExpression(node)
fun visitContinueExpression(node: UContinueExpression) = visitExpression(node)
fun visitThrowExpression(node: UThrowExpression) = visitExpression(node)
fun visitArrayAccessExpression(node: UArrayAccessExpression) = visitExpression(node)
fun visitCallableReferenceExpression(node: UCallableReferenceExpression) = visitExpression(node)
fun visitClassLiteralExpression(node: UClassLiteralExpression) = visitExpression(node)
fun visitLambdaExpression(node: ULambdaExpression) = visitExpression(node)
fun visitObjectLiteralExpression(node: UObjectLiteralExpression) = visitExpression(node)
// After
fun afterVisitElement(node: UElement) {}
fun afterVisitFile(node: UFile) {
afterVisitElement(node)
}
fun afterVisitImportStatement(node: UImportStatement) {
afterVisitElement(node)
}
fun afterVisitDeclaration(node: UDeclaration) {
afterVisitElement(node)
}
fun afterVisitClass(node: UClass) {
afterVisitDeclaration(node)
}
fun afterVisitInitializer(node: UClassInitializer) {
afterVisitDeclaration(node)
}
fun afterVisitMethod(node: UMethod) {
afterVisitDeclaration(node)
}
fun afterVisitVariable(node: UVariable) {
afterVisitElement(node)
}
fun afterVisitParameter(node: UParameter) {
afterVisitVariable(node)
}
fun afterVisitField(node: UField) {
afterVisitVariable(node)
}
fun afterVisitLocalVariable(node: ULocalVariable) {
afterVisitVariable(node)
}
fun afterVisitEnumConstant(node: UEnumConstant) {
afterVisitField(node)
}
fun afterVisitAnnotation(node: UAnnotation) {
afterVisitElement(node)
}
// Expressions
fun afterVisitExpression(node: UExpression) {
afterVisitElement(node)
}
fun afterVisitLabeledExpression(node: ULabeledExpression) {
afterVisitExpression(node)
}
fun afterVisitDeclarationsExpression(node: UDeclarationsExpression) {
afterVisitExpression(node)
}
fun afterVisitBlockExpression(node: UBlockExpression) {
afterVisitExpression(node)
}
fun afterVisitQualifiedReferenceExpression(node: UQualifiedReferenceExpression) {
afterVisitExpression(node)
}
fun afterVisitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression) {
afterVisitExpression(node)
}
fun afterVisitTypeReferenceExpression(node: UTypeReferenceExpression) {
afterVisitExpression(node)
}
fun afterVisitCallExpression(node: UCallExpression) {
afterVisitExpression(node)
}
fun afterVisitBinaryExpression(node: UBinaryExpression) {
afterVisitExpression(node)
}
fun afterVisitBinaryExpressionWithType(node: UBinaryExpressionWithType) {
afterVisitExpression(node)
}
fun afterVisitParenthesizedExpression(node: UParenthesizedExpression) {
afterVisitExpression(node)
}
fun afterVisitUnaryExpression(node: UUnaryExpression) {
afterVisitExpression(node)
}
fun afterVisitPrefixExpression(node: UPrefixExpression) {
afterVisitExpression(node)
}
fun afterVisitPostfixExpression(node: UPostfixExpression) {
afterVisitExpression(node)
}
fun afterVisitExpressionList(node: UExpressionList) {
afterVisitExpression(node)
}
fun afterVisitIfExpression(node: UIfExpression) {
afterVisitExpression(node)
}
fun afterVisitSwitchExpression(node: USwitchExpression) {
afterVisitExpression(node)
}
fun afterVisitSwitchClauseExpression(node: USwitchClauseExpression) {
afterVisitExpression(node)
}
fun afterVisitWhileExpression(node: UWhileExpression) {
afterVisitExpression(node)
}
fun afterVisitDoWhileExpression(node: UDoWhileExpression) {
afterVisitExpression(node)
}
fun afterVisitForExpression(node: UForExpression) {
afterVisitExpression(node)
}
fun afterVisitForEachExpression(node: UForEachExpression) {
afterVisitExpression(node)
}
fun afterVisitTryExpression(node: UTryExpression) {
afterVisitExpression(node)
}
fun afterVisitCatchClause(node: UCatchClause) {
afterVisitElement(node)
}
fun afterVisitLiteralExpression(node: ULiteralExpression) {
afterVisitExpression(node)
}
fun afterVisitThisExpression(node: UThisExpression) {
afterVisitExpression(node)
}
fun afterVisitSuperExpression(node: USuperExpression) {
afterVisitExpression(node)
}
fun afterVisitReturnExpression(node: UReturnExpression) {
afterVisitExpression(node)
}
fun afterVisitBreakExpression(node: UBreakExpression) {
afterVisitExpression(node)
}
fun afterVisitContinueExpression(node: UContinueExpression) {
afterVisitExpression(node)
}
fun afterVisitThrowExpression(node: UThrowExpression) {
afterVisitExpression(node)
}
fun afterVisitArrayAccessExpression(node: UArrayAccessExpression) {
afterVisitExpression(node)
}
fun afterVisitCallableReferenceExpression(node: UCallableReferenceExpression) {
afterVisitExpression(node)
}
fun afterVisitClassLiteralExpression(node: UClassLiteralExpression) {
afterVisitExpression(node)
}
fun afterVisitLambdaExpression(node: ULambdaExpression) {
afterVisitExpression(node)
}
fun afterVisitObjectLiteralExpression(node: UObjectLiteralExpression) {
afterVisitExpression(node)
}
fun afterVisitPolyadicExpression(node: UPolyadicExpression) {
afterVisitExpression(node)
}
}
abstract class AbstractUastVisitor : UastVisitor {
override fun visitElement(node: UElement): Boolean = false
}
object EmptyUastVisitor : AbstractUastVisitor() | apache-2.0 | a386fb25262c8696015f2f4988ba7f9c | 32.278169 | 102 | 0.789418 | 4.886246 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/ui/appdetail/page/usedpermission/AppPermissionListAdapter.kt | 1 | 2906 | package sk.styk.martin.apkanalyzer.ui.appdetail.page.usedpermission
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.LiveData
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import sk.styk.martin.apkanalyzer.databinding.ListItemAppPermissionDetailBinding
import sk.styk.martin.apkanalyzer.ui.appdetail.page.DetailInfoDescriptionAdapter
import sk.styk.martin.apkanalyzer.util.TextInfo
import sk.styk.martin.apkanalyzer.util.live.SingleLiveEvent
import javax.inject.Inject
class AppPermissionListAdapter @Inject constructor() : DetailInfoDescriptionAdapter<AppPermissionListAdapter.ViewHolder>() {
data class DecomposedPermissionData(val completeName: String, val simpleName: String)
private val showPermissionDetailEvent = SingleLiveEvent<String>()
val showPermissionDetail: LiveData<String> = showPermissionDetailEvent
var items = emptyList<DecomposedPermissionData>()
set(value) {
val diffResult = DiffUtil.calculateDiff(StringDiffCallback(value, field))
field = value
diffResult.dispatchUpdatesTo(this)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemBinding = ListItemAppPermissionDetailBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(itemBinding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(PermissionDataViewModel(items[position]))
}
override fun getItemCount() = items.size
inner class PermissionDataViewModel(private val permission: DecomposedPermissionData) {
val simpleName = permission.simpleName
val completeName = permission.completeName
fun showDetail() {
showPermissionDetailEvent.value = permission.completeName
}
fun copyName(): Boolean {
copyToClipboardEvent.value = CopyToClipboard(TextInfo.from(completeName))
return true
}
}
inner class ViewHolder(val binding: ListItemAppPermissionDetailBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(viewModel: PermissionDataViewModel) {
binding.viewModel = viewModel
}
}
private inner class StringDiffCallback(private val newList: List<DecomposedPermissionData>,
private val oldList: List<DecomposedPermissionData>) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition] == newList[newItemPosition]
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition] == newList[newItemPosition]
}
} | gpl-3.0 | f9508a4d5c0f0a6f550816366224467e | 40.528571 | 138 | 0.742602 | 5.207885 | false | false | false | false |
mhshams/yekan | vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/core/http/WebSocketFrame.kt | 2 | 1142 | package io.vertx.kotlin.core.http
import io.vertx.kotlin.core.buffer.Buffer
import io.vertx.kotlin.core.internal.Delegator
/**
*/
class WebSocketFrame(override val delegate: io.vertx.core.http.WebSocketFrame) : Delegator<io.vertx.core.http.WebSocketFrame> {
companion object {
fun binaryFrame(data: Buffer, isFinal: Boolean): WebSocketFrame =
WebSocketFrame(io.vertx.core.http.WebSocketFrame.binaryFrame(data.delegate, isFinal))
fun textFrame(str: String, isFinal: Boolean): WebSocketFrame =
WebSocketFrame(io.vertx.core.http.WebSocketFrame.textFrame(str, isFinal))
fun continuationFrame(data: Buffer, isFinal: Boolean): WebSocketFrame =
WebSocketFrame(io.vertx.core.http.WebSocketFrame.continuationFrame(data.delegate, isFinal));
}
fun isText(): Boolean = delegate.isText()
fun isBinary(): Boolean = delegate.isBinary()
fun isContinuation(): Boolean = delegate.isContinuation()
fun textData(): String = delegate.textData()
fun binaryData(): Buffer = Buffer(delegate.binaryData())
fun isFinal(): Boolean = delegate.isFinal()
}
| apache-2.0 | 01a931f83675cb7ad66a4411a6f92307 | 35.83871 | 127 | 0.712785 | 4.358779 | false | false | false | false |
TachiWeb/TachiWeb-Server | Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ChapterLoader.kt | 1 | 3276 | package eu.kanade.tachiyomi.ui.reader.loader
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import rx.Completable
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import timber.log.Timber
/**
* Loader used to retrieve the [PageLoader] for a given chapter.
*/
class ChapterLoader(
private val downloadManager: DownloadManager,
private val manga: Manga,
private val source: Source
) {
/**
* Returns a completable that assigns the page loader and loads the its pages. It just
* completes if the chapter is already loaded.
*/
fun loadChapter(chapter: ReaderChapter): Completable {
if (chapter.state is ReaderChapter.State.Loaded) {
return Completable.complete()
}
return Observable.just(chapter)
.doOnNext { chapter.state = ReaderChapter.State.Loading }
.observeOn(Schedulers.io())
.flatMap {
Timber.d("Loading pages for ${chapter.chapter.name}")
val loader = getPageLoader(it)
chapter.pageLoader = loader
loader.getPages().take(1).doOnNext { pages ->
pages.forEach { it.chapter = chapter }
}
}
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { pages ->
if (pages.isEmpty()) {
throw Exception("Page list is empty")
}
chapter.state = ReaderChapter.State.Loaded(pages)
// If the chapter is partially read, set the starting page to the last the user read
// otherwise use the requested page.
if (!chapter.chapter.read) {
chapter.requestedPage = chapter.chapter.last_page_read
}
}
.toCompletable()
.doOnError { chapter.state = ReaderChapter.State.Error(it) }
}
/**
* Returns the page loader to use for this [chapter].
*/
private fun getPageLoader(chapter: ReaderChapter): PageLoader {
val isDownloaded = downloadManager.isChapterDownloaded(chapter.chapter, manga, true)
return when {
isDownloaded -> DownloadPageLoader(chapter, manga, source, downloadManager)
source is HttpSource -> HttpPageLoader(chapter, source)
source is LocalSource -> source.getFormat(chapter.chapter).let { format ->
when (format) {
is LocalSource.Format.Directory -> DirectoryPageLoader(format.file)
is LocalSource.Format.Zip -> ZipPageLoader(format.file)
is LocalSource.Format.Rar -> RarPageLoader(format.file)
is LocalSource.Format.Epub -> EpubPageLoader(format.file)
}
}
else -> error("Loader not implemented")
}
}
}
| apache-2.0 | 3d81a832e2f688f7d33bcb98cf74b7d9 | 38 | 104 | 0.599512 | 5.110764 | false | false | false | false |
sky-map-team/stardroid | app/src/test/java/com/google/android/stardroid/control/AstronomerModelTest.kt | 1 | 7581 | // Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.stardroid.control
import com.google.android.stardroid.math.LatLong
import com.google.android.stardroid.math.MathUtils.sqrt
import com.google.android.stardroid.math.Vector3
import com.google.android.stardroid.math.Vector3Subject
import junit.framework.TestCase
import org.junit.Test
import java.util.*
/**
* Test of the [AstronomerModelImpl] class.
*
* @author John Taylor
*/
class AstronomerModelTest {
private var astronomer: AstronomerModel = AstronomerModelImpl(ZeroMagneticDeclinationCalculator())
/**
* The phone is flat, long side pointing North at lat,long = 0, 90.
*/
@Test
fun testSetPhoneSensorValues_phoneFlatAtLat0Long90() {
val location = LatLong(0f, 90f)
// Phone flat on back, top edge towards North
// The following are in the phone's coordinate system.
val acceleration = Vector3(0f, 0f, 10f)
val magneticField = Vector3(0f, 1f, 10f)
// The following are in the celestial coordinate system.
val expectedZenith = Vector3(0f, 1f, 0f)
val expectedNadir = Vector3(0f, -1f, 0f)
val expectedNorth = Vector3(0f, 0f, 1f)
val expectedEast = Vector3(-1f, 0f, 0f) // N cross Up
val expectedSouth = Vector3(0f, 0f, -1f)
val expectedWest = Vector3(1f, 0f, 0f)
checkModelOrientation(
location, acceleration, magneticField, expectedZenith, expectedNadir,
expectedNorth, expectedEast, expectedSouth, expectedWest, expectedPointing = expectedNadir,
expectedUpAlongPhone = expectedNorth
)
}
/**
* As previous test, but at lat, long = (45, 0)
*/
@Test
fun testSetPhoneSensorValues_phoneFlatAtLat45Long0() {
val location = LatLong(45f, 0f)
val acceleration = Vector3(0f, 0f, 10f)
val magneticField = Vector3(0f, 10f, 0f)
val expectedZenith = Vector3(1 / SQRT2, 0f, 1 / SQRT2)
val expectedNadir = Vector3(-1 / SQRT2, 0f, -1 / SQRT2)
val expectedNorth = Vector3(-1 / SQRT2, 0f, 1 / SQRT2)
val expectedEast = Vector3(0f, 1f, 0f)
val expectedSouth = Vector3(1 / SQRT2, 0f, -1 / SQRT2)
val expectedWest = Vector3(0f, -1f, 0f)
checkModelOrientation(
location, acceleration, magneticField, expectedZenith, expectedNadir,
expectedNorth, expectedEast, expectedSouth, expectedWest, expectedPointing = expectedNadir,
expectedUpAlongPhone = expectedNorth
)
}
/**
* As previous test, but at lat, long = (0, 0)
*/
@Test
fun testSetPhoneSensorValues_phoneFlatOnEquatorAtMeridian() {
val location = LatLong(0f, 0f)
// Phone flat on back, top edge towards North
val acceleration = Vector3(0f, 0f, 10f)
val magneticField = Vector3(0f, 1f, 10f)
val expectedZenith = Vector3(1f, 0f, 0f)
val expectedNadir = Vector3(-1f, 0f, 0f)
val expectedNorth = Vector3(0f, 0f, 1f)
val expectedEast = Vector3(0f, 1f, 0f)
val expectedSouth = Vector3(0f, 0f, -1f)
val expectedWest = Vector3(0f, -1f, 0f)
checkModelOrientation(
location, acceleration, magneticField, expectedZenith, expectedNadir,
expectedNorth, expectedEast, expectedSouth, expectedWest, expectedPointing = expectedNadir,
expectedUpAlongPhone = expectedNorth
)
}
/**
* As previous test, but with the phone vertical, but in landscape mode
* and pointing east.
*/
@Test
fun testSetPhoneSensorValues_phoneLandscapeFacingEastOnEquatorAtMeridian() {
val location = LatLong(0f, 0f)
val acceleration = Vector3(10f, 0f, 0f)
val magneticField = Vector3(-10f, 1f, 0f)
val expectedZenith = Vector3(1f, 0f, 0f)
val expectedNadir = Vector3(-1f, 0f, 0f)
val expectedNorth = Vector3(0f, 0f, 1f)
val expectedEast = Vector3(0f, 1f, 0f)
val expectedSouth = Vector3(0f, 0f, -1f)
val expectedWest = Vector3(0f, -1f, 0f)
checkModelOrientation(
location, acceleration, magneticField, expectedZenith, expectedNadir,
expectedNorth, expectedEast, expectedSouth, expectedWest, expectedPointing = expectedEast,
expectedUpAlongPhone = expectedNorth
)
}
/**
* As previous test, but in portrait mode facing north.
*/
@Test
fun testSetPhoneSensorValues_phoneStandingUpFacingNorthOnEquatorAtMeridian() {
val location = LatLong(0f, 0f)
val acceleration = Vector3(0f, 10f, 0f)
val magneticField = Vector3(0f, 10f, -1f)
val expectedZenith = Vector3(1f, 0f, 0f)
val expectedNadir = Vector3(-1f, 0f, 0f)
val expectedNorth = Vector3(0f, 0f, 1f)
val expectedEast = Vector3(0f, 1f, 0f)
val expectedSouth = Vector3(0f, 0f, -1f)
val expectedWest = Vector3(0f, -1f, 0f)
checkModelOrientation(
location, acceleration, magneticField, expectedZenith, expectedNadir,
expectedNorth, expectedEast, expectedSouth, expectedWest, expectedPointing = expectedNorth,
expectedUpAlongPhone = expectedZenith
)
}
private fun checkModelOrientation(
location: LatLong,
acceleration: Vector3,
magneticField: Vector3,
expectedZenith: Vector3,
expectedNadir: Vector3,
expectedNorth: Vector3,
expectedEast: Vector3,
expectedSouth: Vector3,
expectedWest: Vector3,
expectedPointing: Vector3,
expectedUpAlongPhone: Vector3
) {
astronomer.location = location
val fakeClock =
Clock {
// This date is special as RA, DEC = (0, 0) is directly overhead at the
// equator on the Greenwich meridian.
// 12:07 March 20th 2009
val calendar = GregorianCalendar(TimeZone.getTimeZone("UTC"))
calendar[2009, 2, 20, 12, 7] = 24
calendar.timeInMillis
}
astronomer.setClock(fakeClock)
astronomer.setPhoneSensorValues(acceleration, magneticField)
Vector3Subject.assertThat(astronomer.zenith).isWithin(TOL).of(expectedZenith)
Vector3Subject.assertThat(astronomer.nadir).isWithin(TOL).of(expectedNadir)
Vector3Subject.assertThat(astronomer.north).isWithin(TOL).of(expectedNorth)
Vector3Subject.assertThat(astronomer.east).isWithin(TOL).of(expectedEast)
Vector3Subject.assertThat(astronomer.south).isWithin(TOL).of(expectedSouth)
Vector3Subject.assertThat(astronomer.west).isWithin(TOL).of(expectedWest)
Vector3Subject.assertThat(astronomer.pointing.lineOfSight).isWithin(TOL).of(expectedPointing)
Vector3Subject.assertThat(astronomer.pointing.perpendicular).isWithin(TOL).of(expectedUpAlongPhone)
}
companion object {
private val SQRT2 = sqrt(2f)
private const val TOL = 1e-3f
}
} | apache-2.0 | 14b48ee8080df2206421c2935ab4ee41 | 40.659341 | 107 | 0.66205 | 3.683673 | false | true | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/presentation/newdb/NewDatabaseViewModel.kt | 1 | 7801 | package com.ivanovsky.passnotes.presentation.newdb
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.github.terrakok.cicerone.Router
import com.ivanovsky.passnotes.R
import com.ivanovsky.passnotes.data.entity.FileDescriptor
import com.ivanovsky.passnotes.data.entity.FSType
import com.ivanovsky.passnotes.data.repository.keepass.KeepassDatabaseKey
import com.ivanovsky.passnotes.domain.FileHelper
import com.ivanovsky.passnotes.domain.ResourceProvider
import com.ivanovsky.passnotes.domain.interactor.ErrorInteractor
import com.ivanovsky.passnotes.domain.interactor.newdb.NewDatabaseInteractor
import com.ivanovsky.passnotes.presentation.Screens.GroupsScreen
import com.ivanovsky.passnotes.presentation.Screens.StorageListScreen
import com.ivanovsky.passnotes.presentation.core.DefaultScreenStateHandler
import com.ivanovsky.passnotes.presentation.core.ScreenState
import com.ivanovsky.passnotes.presentation.core.event.SingleLiveEvent
import com.ivanovsky.passnotes.presentation.groups.GroupsArgs
import com.ivanovsky.passnotes.presentation.storagelist.Action
import com.ivanovsky.passnotes.util.StringUtils.EMPTY
import kotlinx.coroutines.launch
import java.io.File
import java.util.regex.Pattern
class NewDatabaseViewModel(
private val interactor: NewDatabaseInteractor,
private val errorInteractor: ErrorInteractor,
private val fileHelper: FileHelper,
private val resourceProvider: ResourceProvider,
private val router: Router
) : ViewModel() {
val screenStateHandler = DefaultScreenStateHandler()
val screenState = MutableLiveData(ScreenState.data())
val filename = MutableLiveData(EMPTY)
val password = MutableLiveData(EMPTY)
val confirmation = MutableLiveData(EMPTY)
val filenameError = MutableLiveData<String?>(null)
val passwordError = MutableLiveData<String?>(null)
val confirmationError = MutableLiveData<String?>(null)
val storageType = MutableLiveData<String>()
val storagePath = MutableLiveData(resourceProvider.getString(R.string.not_selected))
val doneButtonVisibility = MutableLiveData(true)
val isAddTemplates = MutableLiveData(true)
val hideKeyboardEvent = SingleLiveEvent<Unit>()
val showSnackBarEvent = SingleLiveEvent<String>()
private var selectedStorageDir: FileDescriptor? = null
fun createNewDatabaseFile() {
val filename = this.filename.value ?: return
val password = this.password.value ?: return
val confirmation = this.confirmation.value ?: return
val isAddTemplates = this.isAddTemplates.value ?: false
if (!isFieldsValid(filename, password, confirmation)) {
return
}
val storageDir = selectedStorageDir
if (storageDir == null) {
val errorText = resourceProvider.getString(R.string.storage_is_not_selected)
screenState.value = ScreenState.dataWithError(errorText)
return
}
hideKeyboardEvent.call()
doneButtonVisibility.value = false
screenState.value = ScreenState.loading()
val dbKey = KeepassDatabaseKey(password)
val dbFile = storageDir.copy(
path = storageDir.path + "/" + "$filename.kdbx"
)
viewModelScope.launch {
val result = interactor.createNewDatabaseAndOpen(dbKey, dbFile, isAddTemplates)
if (result.isSucceededOrDeferred) {
val created = result.obj
if (created) {
router.replaceScreen(
GroupsScreen(
GroupsArgs(
groupUid = null,
isCloseDatabaseOnExit = true
)
)
)
} else {
val errorText = resourceProvider.getString(R.string.error_was_occurred)
screenState.value = ScreenState.dataWithError(errorText)
doneButtonVisibility.value = true
}
} else {
val message = errorInteractor.processAndGetMessage(result.error)
screenState.value = ScreenState.dataWithError(message)
doneButtonVisibility.value = true
}
}
}
private fun isFieldsValid(
filename: String,
password: String,
confirmation: String
): Boolean {
if (filename.isBlank() || password.isBlank() || confirmation.isBlank()) {
filenameError.value = if (filename.isBlank()) {
resourceProvider.getString(R.string.empty_field)
} else {
null
}
passwordError.value = if (password.isBlank()) {
resourceProvider.getString(R.string.empty_field)
} else {
null
}
confirmationError.value = if (confirmation.isBlank()) {
resourceProvider.getString(R.string.empty_field)
} else {
null
}
return false
}
if (FILE_NAME_PATTERN.matcher(filename).matches()) {
filenameError.value = null
} else {
filenameError.value =
resourceProvider.getString(R.string.field_contains_illegal_character)
}
if (PASSWORD_PATTERN.matcher(password).matches()) {
passwordError.value = null
} else {
passwordError.value =
resourceProvider.getString(R.string.field_contains_illegal_character)
}
if (password == confirmation) {
confirmationError.value = null
} else {
confirmationError.value =
resourceProvider.getString(R.string.this_field_should_match_password)
}
return filenameError.value == null &&
passwordError.value == null &&
confirmationError.value == null
}
fun onSelectStorageClicked() {
router.setResultListener(StorageListScreen.RESULT_KEY) { file ->
if (file is FileDescriptor) {
onStorageSelected(file)
}
}
router.navigateTo(StorageListScreen(Action.PICK_STORAGE))
}
fun onTemplatesInfoButtonClicked() {
showSnackBarEvent.call(
resourceProvider.getString(R.string.add_templates_info_message)
)
}
fun navigateBack() = router.exit()
private fun onStorageSelected(selectedFile: FileDescriptor) {
selectedStorageDir = selectedFile
when (selectedFile.fsAuthority.type) {
FSType.REGULAR_FS -> {
val file = File(selectedFile.path)
if (fileHelper.isLocatedInPrivateStorage(file)) {
storageType.value = resourceProvider.getString(R.string.private_storage)
} else {
storageType.value = resourceProvider.getString(R.string.public_storage)
}
}
FSType.DROPBOX -> {
storageType.value = resourceProvider.getString(R.string.dropbox)
}
FSType.WEBDAV -> {
storageType.value = resourceProvider.getString(R.string.webdav)
}
FSType.SAF -> {
storageType.value = resourceProvider.getString(R.string.public_storage)
}
}
storagePath.value = selectedFile.path
}
companion object {
private val FILE_NAME_PATTERN = Pattern.compile("[\\w-_]{1,50}")
// TODO: Refactor, create Validator entity which will be able to validate
// different text
val PASSWORD_PATTERN = Pattern.compile("[\\w@#$!%^&+=]{4,20}")
}
} | gpl-2.0 | 3bcb06be94beaf316b80060f3fb5e56e | 35.976303 | 92 | 0.635688 | 5.102027 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/pattern/action/OpenOthersPatternAction.kt | 1 | 5196 | /*
* Copyright (C) 2017-2021 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.pattern.action
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager.NameNotFoundException
import android.net.Uri
import android.widget.Toast
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import jp.hazuki.yuzubrowser.legacy.Constants.intent.EXTRA_OPEN_FROM_YUZU
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.pattern.PatternAction
import jp.hazuki.yuzubrowser.legacy.tab.manager.MainTabData
import jp.hazuki.yuzubrowser.ui.utils.PackageUtils
import java.io.IOException
import java.net.URISyntaxException
class OpenOthersPatternAction : PatternAction {
var openType: Int = 0
private set
private var mUrl: String? = null
override val typeId: Int
get() = OPEN_OTHERS
val intent: Intent?
get() {
try {
return Intent.parseUri(mUrl, 0)
} catch (e: URISyntaxException) {
e.printStackTrace()
}
return null
}
constructor(intent: Intent) {
openType = TYPE_NORMAL
mUrl = intent.toUri(0)
}
constructor(type: Int) {
openType = type
}
@Throws(IOException::class)
constructor(reader: JsonReader) {
if (reader.peek() != JsonReader.Token.BEGIN_OBJECT) return
reader.beginObject()
while (reader.hasNext()) {
when (reader.nextName()) {
FIELD_TYPE -> openType = reader.nextInt()
FIELD_INTENT -> {
if (reader.peek() == JsonReader.Token.STRING) {
mUrl = reader.nextString()
} else {
reader.skipValue()
}
}
else -> reader.skipValue()
}
}
reader.endObject()
}
@Throws(IOException::class)
override fun write(writer: JsonWriter): Boolean {
writer.value(OPEN_OTHERS)
writer.beginObject()
writer.name(FIELD_TYPE)
writer.value(openType)
writer.name(FIELD_INTENT)
writer.value(mUrl)
writer.endObject()
return true
}
override fun getTitle(context: Context): String {
when (openType) {
TYPE_NORMAL -> {
val pre = context.getString(R.string.pattern_open_others)
try {
val pm = context.packageManager
return "$pre : ${pm.getActivityInfo(intent!!.component!!, 0).loadLabel(pm)}"
} catch (e: NameNotFoundException) {
e.printStackTrace()
}
return pre
}
TYPE_APP_LIST -> return context.getString(R.string.pattern_open_app_list)
TYPE_APP_CHOOSER -> return context.getString(R.string.pattern_open_app_chooser)
else -> throw IllegalStateException()
}
}
override fun run(context: Context, tab: MainTabData, url: String): Boolean {
var intent: Intent?
when (openType) {
TYPE_NORMAL -> {
intent = this.intent
intent!!.data = Uri.parse(url)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
TYPE_APP_LIST -> {
intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
TYPE_APP_CHOOSER -> {
intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
intent = PackageUtils.createChooser(context, url, context.getText(R.string.open))
}
else -> throw IllegalStateException()
}
try {
intent!!.putExtra(EXTRA_OPEN_FROM_YUZU, true)
context.startActivity(intent)
return true
} catch (e: ActivityNotFoundException) {
e.printStackTrace()
Toast.makeText(context, R.string.app_notfound, Toast.LENGTH_SHORT).show()
} catch (e: IllegalArgumentException) {
e.printStackTrace()
Toast.makeText(context, R.string.app_notfound, Toast.LENGTH_SHORT).show()
}
return false
}
companion object {
private const val FIELD_TYPE = "0"
private const val FIELD_INTENT = "1"
const val TYPE_NORMAL = 0
const val TYPE_APP_LIST = 1
const val TYPE_APP_CHOOSER = 2
}
}
| apache-2.0 | be9f315822131b6cab05d78629565a15 | 32.307692 | 97 | 0.592571 | 4.514335 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/adapters/SmartListDiffUtil.kt | 1 | 1889 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Hadrien De Sousa <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.adapters
import net.jami.smartlist.ConversationItemViewModel
import androidx.recyclerview.widget.DiffUtil
import net.jami.model.Conversation
import net.jami.services.ConversationFacade
class SmartListDiffUtil(
private val mOldList: ConversationFacade.ConversationList,
private val mNewList: ConversationFacade.ConversationList
) : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return mOldList.getCombinedSize()
}
override fun getNewListSize(): Int {
return mNewList.getCombinedSize()
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = mOldList[oldItemPosition]
val newItem = mNewList[newItemPosition]
if (oldItem == null || newItem == null)
return oldItem === newItem
return newItem.uri == oldItem.uri
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return mNewList[newItemPosition] === mOldList[oldItemPosition]
}
} | gpl-3.0 | 3963e931397fed5b2ab178b79a9385e0 | 36.8 | 90 | 0.729487 | 4.362587 | false | false | false | false |
grote/Liberario | app/src/main/java/de/grobox/transportr/networks/TransportNetworks.kt | 1 | 36646 | /*
* Transportr
*
* Copyright (c) 2013 - 2018 Torsten Grote
*
* This program is Free Software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.grobox.transportr.networks
import android.content.Context
import de.grobox.transportr.R
import de.grobox.transportr.networks.TransportNetwork.Status.ALPHA
import de.grobox.transportr.networks.TransportNetwork.Status.BETA
import de.schildbach.pte.*
import okhttp3.HttpUrl
import java.util.*
private val networks = arrayOf(
Continent(
R.string.np_continent_europe, R.drawable.continent_europe,
listOf(
Country(
R.string.np_continent_europe, flag = "🇪🇺", sticky = true, networks = listOf(
TransportNetwork(
id = NetworkId.RT,
name = R.string.np_name_rt,
description = R.string.np_desc_rt,
agencies = R.string.np_desc_rt_networks,
logo = R.drawable.network_rt_logo,
factory = { RtProvider() }
),
TransportNetwork(
id = NetworkId.DB,
name = R.string.np_name_db,
description = R.string.np_desc_db2,
logo = R.drawable.network_db_logo,
factory = { DbProvider("{\"type\":\"AID\",\"aid\":\"n91dB8Z77MLdoR0K\"}", "bdI8UVj40K5fvxwf".toByteArray(Charsets.UTF_8)) }
)
)
),
Country(
R.string.np_region_germany, flag = "🇩🇪", networks = listOf(
TransportNetwork(
id = NetworkId.DB,
name = R.string.np_name_db,
description = R.string.np_desc_db,
logo = R.drawable.network_db_logo,
itemIdExtra = 1,
factory = { DbProvider("{\"type\":\"AID\",\"aid\":\"n91dB8Z77MLdoR0K\"}", "bdI8UVj40K5fvxwf".toByteArray(Charsets.UTF_8)) }
),
TransportNetwork(
id = NetworkId.BVG,
description = R.string.np_desc_bvg,
logo = R.drawable.network_bvg_logo,
factory = { BvgProvider("{\"aid\":\"1Rxs112shyHLatUX4fofnmdxK\",\"type\":\"AID\"}") }
),
TransportNetwork(
id = NetworkId.VBB,
description = R.string.np_desc_vbb,
logo = R.drawable.network_vbb_logo,
factory = { VbbProvider("{\"type\":\"AID\",\"aid\":\"hafas-vbb-apps\"}", "RCTJM2fFxFfxxQfI".toByteArray(Charsets.UTF_8)) }
),
TransportNetwork(
id = NetworkId.BAYERN,
name = R.string.np_name_bayern,
description = R.string.np_desc_bayern,
logo = R.drawable.network_bayern_logo,
factory = { BayernProvider() }
),
TransportNetwork(
id = NetworkId.AVV,
description = R.string.np_desc_avv,
logo = R.drawable.network_avv_logo,
status = BETA,
factory = { AvvProvider() }
),
TransportNetwork(
id = NetworkId.MVV,
description = R.string.np_desc_mvv,
logo = R.drawable.network_mvv_logo,
factory = { MvvProvider() }
),
TransportNetwork(
id = NetworkId.INVG,
description = R.string.np_desc_invg,
logo = R.drawable.network_invg_logo,
status = BETA,
factory = { InvgProvider("{\"type\":\"AID\",\"aid\":\"GITvwi3BGOmTQ2a5\"}", "ERxotxpwFT7uYRsI".toByteArray(Charsets.UTF_8)) }
),
TransportNetwork(
id = NetworkId.VGN,
description = R.string.np_desc_vgn,
agencies = R.string.np_desc_vgn_networks,
logo = R.drawable.network_vgn_logo,
status = BETA,
factory = { VgnProvider() }
),
TransportNetwork(
id = NetworkId.VVM,
description = R.string.np_desc_vvm,
logo = R.drawable.network_vvm_logo,
factory = { VvmProvider() }
),
TransportNetwork(
id = NetworkId.VMV,
description = R.string.np_desc_vmv,
logo = R.drawable.network_vmv_logo,
factory = { VmvProvider() }
),
TransportNetwork(
id = NetworkId.GVH,
description = R.string.np_desc_gvh,
logo = R.drawable.network_gvh_logo,
factory = { GvhProvider() }
),
TransportNetwork(
id = NetworkId.BSVAG,
name = R.string.np_name_bsvag,
description = R.string.np_desc_bsvag,
logo = R.drawable.network_bsvag_logo,
factory = { BsvagProvider() }
),
TransportNetwork(
id = NetworkId.VVO,
description = R.string.np_desc_vvo,
logo = R.drawable.network_vvo_logo,
factory = { VvoProvider(HttpUrl.parse("http://efaproxy.fahrinfo.uptrade.de/standard/")) }
),
TransportNetwork(
id = NetworkId.VMS,
description = R.string.np_desc_vms,
logo = R.drawable.network_vms_logo,
status = BETA,
factory = { VmsProvider() }
),
TransportNetwork(
id = NetworkId.NASA,
name = R.string.np_name_nasa,
description = R.string.np_desc_nasa,
logo = R.drawable.network_nasa_logo,
status = BETA,
factory = { NasaProvider("{\"aid\":\"nasa-apps\",\"type\":\"AID\"}") }
),
TransportNetwork(
id = NetworkId.VRR,
description = R.string.np_desc_vrr,
logo = R.drawable.network_vrr_logo,
factory = { VrrProvider() }
),
TransportNetwork(
id = NetworkId.MVG,
description = R.string.np_desc_mvg,
logo = R.drawable.network_mvg_logo,
factory = { MvgProvider() }
),
TransportNetwork(
id = NetworkId.NVV,
name = R.string.np_name_nvv,
description = R.string.np_desc_nvv,
logo = R.drawable.network_nvv_logo,
factory = { NvvProvider("{\"type\":\"AID\",\"aid\":\"Kt8eNOH7qjVeSxNA\"}") }
),
TransportNetwork(
id = NetworkId.VRN,
description = R.string.np_desc_vrn,
logo = R.drawable.network_vrn_logo,
factory = { VrnProvider() }
),
TransportNetwork(
id = NetworkId.VVS,
description = R.string.np_desc_vvs,
logo = R.drawable.network_vvs_logo,
factory = { VvsProvider(HttpUrl.parse("http://www2.vvs.de/oeffi/")) }
),
TransportNetwork(
id = NetworkId.DING,
description = R.string.np_desc_ding,
logo = R.drawable.network_ding_logo,
factory = { DingProvider() }
),
TransportNetwork(
id = NetworkId.KVV,
description = R.string.np_desc_kvv,
logo = R.drawable.network_kvv_logo,
factory = { KvvProvider(HttpUrl.parse("https://projekte.kvv-efa.de/oeffi/")) }
),
TransportNetwork(
id = NetworkId.NVBW,
description = R.string.np_desc_nvbw,
logo = R.drawable.network_nvbw_logo,
factory = { NvbwProvider() }
),
TransportNetwork(
id = NetworkId.VVV,
description = R.string.np_desc_vvv,
logo = R.drawable.network_vvv_logo,
factory = { VvvProvider() }
),
TransportNetwork(
id = NetworkId.VGS,
description = R.string.np_desc_vgs,
logo = R.drawable.network_vgs_logo,
factory = { VgsProvider("{\"type\":\"AID\",\"aid\":\"51XfsVqgbdA6oXzHrx75jhlocRg6Xe\"}", "HJtlubisvxiJxss".toByteArray(Charsets.UTF_8)) }
),
TransportNetwork(
id = NetworkId.VRS,
description = R.string.np_desc_vrs,
logo = R.drawable.network_vrs_logo,
factory = { VrsProvider() }
),
TransportNetwork(
id = NetworkId.VMT,
description = R.string.np_desc_vmt,
factory = { VmtProvider("{\"aid\":\"vj5d7i3g9m5d7e3\",\"type\":\"AID\"}") }
)
)
),
Country(
R.string.np_region_austria, flag = "🇦🇹", networks = listOf(
TransportNetwork(
id = NetworkId.OEBB,
name = R.string.np_name_oebb,
description = R.string.np_desc_oebb,
logo = R.drawable.network_oebb_logo,
factory = { OebbProvider("{\"type\":\"AID\",\"aid\":\"OWDL4fE4ixNiPBBm\"}") }
),
TransportNetwork(
id = NetworkId.VOR,
description = R.string.np_desc_vor,
logo = R.drawable.network_vor_logo,
factory = { VorProvider(VAO) }
),
TransportNetwork(
id = NetworkId.LINZ,
name = R.string.np_name_linz,
description = R.string.np_desc_linz,
logo = R.drawable.network_linz_logo,
factory = { LinzProvider() }
),
TransportNetwork(
id = NetworkId.VVT,
description = R.string.np_desc_vvt,
logo = R.drawable.network_vvt_logo,
factory = { VvtProvider(VAO) }
),
// TransportNetwork(
// id = NetworkId.IVB,
// description = R.string.np_desc_ivb,
// logo = R.drawable.network_ivb_logo,
// factory = { IvbProvider() }
// ),
TransportNetwork(
id = NetworkId.STV,
name = R.string.np_name_stv,
description = R.string.np_desc_stv,
logo = R.drawable.network_stv_logo,
factory = { StvProvider() }
),
TransportNetwork(
id = NetworkId.WIEN,
name = R.string.np_name_wien,
description = R.string.np_desc_wien,
logo = R.drawable.network_wien_logo,
factory = { WienProvider() }
),
TransportNetwork(
id = NetworkId.VMOBIL,
name = R.string.np_name_vmobil,
description = R.string.np_desc_vmobil,
logo = R.drawable.network_vmobil_logo,
factory = { VmobilProvider(VAO) }
)
)
),
Country(
R.string.np_region_liechtenstein, flag = "🇱🇮", networks = listOf(
TransportNetwork(
id = NetworkId.VMOBIL,
name = R.string.np_name_vmobil,
description = R.string.np_desc_vmobil,
logo = R.drawable.network_vmobil_logo,
itemIdExtra = 1,
factory = { VmobilProvider(VAO) }
)
)
),
Country(
R.string.np_region_switzerland, flag = "🇨🇭", networks = listOf(
TransportNetwork(
id = NetworkId.SBB,
name = R.string.np_name_sbb,
description = R.string.np_desc_sbb,
logo = R.drawable.network_sbb_logo,
factory = { SbbProvider() }
),
TransportNetwork(
id = NetworkId.VBL,
description = R.string.np_desc_vbl,
logo = R.drawable.network_vbl_logo,
factory = { VblProvider() }
),
TransportNetwork(
id = NetworkId.ZVV,
description = R.string.np_desc_zvv,
logo = R.drawable.network_zvv_logo,
factory = { ZvvProvider("{\"type\":\"AID\",\"aid\":\"hf7mcf9bv3nv8g5f\"}") }
)
)
),
Country(
R.string.np_region_belgium, flag = "🇧🇪", networks = listOf(
TransportNetwork(
id = NetworkId.SNCB,
name = R.string.np_region_belgium,
description = R.string.np_desc_sncb,
agencies = R.string.np_desc_sncb_networks,
logo = R.drawable.network_sncb_logo,
factory = { SncbProvider("{\"type\":\"AID\",\"aid\":\"sncb-mobi\"}") }
)
)
),
Country(
R.string.np_region_luxembourg, flag = "🇱🇺", networks = listOf(
TransportNetwork(
id = NetworkId.LU,
name = R.string.np_name_lu,
description = R.string.np_desc_lu,
agencies = R.string.np_desc_lu_networks,
factory = { LuProvider("{\"type\":\"AID\",\"aid\":\"Aqf9kNqJLjxFx6vv\"}") }
)
)
),
Country(
R.string.np_region_netherlands, flag = "🇳🇱", networks = listOf(
TransportNetwork(
id = NetworkId.NS,
description = R.string.np_desc_ns,
logo = R.drawable.network_ns_logo,
status = BETA,
factory = { NsProvider() }
),
TransportNetwork(
id = NetworkId.NEGENTWEE,
name = R.string.np_name_negentwee,
description = R.string.np_desc_negentwee,
logo = R.drawable.network_negentwee_logo,
status = ALPHA,
factory = {
if (Locale.getDefault().language == "nl") {
NegentweeProvider(NegentweeProvider.Language.NL_NL)
} else {
NegentweeProvider(NegentweeProvider.Language.EN_GB)
}
}
)
)
),
Country(
R.string.np_region_denmark, flag = "🇩🇰", networks = listOf(
TransportNetwork(
id = NetworkId.DSB,
description = R.string.np_desc_dsb,
logo = R.drawable.network_dsb_logo,
factory = { DsbProvider("{\"type\":\"AID\",\"aid\":\"irkmpm9mdznstenr-android\"}") }
)
)
),
Country(
R.string.np_region_sweden, flag = "🇸🇪", networks = listOf(
TransportNetwork(
id = NetworkId.SE,
description = R.string.np_desc_se,
logo = R.drawable.network_se_logo,
factory = { SeProvider("{\"type\":\"AID\",\"aid\":\"h5o3n7f4t2m8l9x1\"}") }
)
)
),
Country(
R.string.np_region_finland, flag = "🇫🇮", networks = listOf(
TransportNetwork(
id = NetworkId.FINLAND,
name = R.string.np_region_finland,
description = R.string.np_desc_fi,
agencies = R.string.np_desc_fi_networks,
logo = R.drawable.network_fi_logo,
status = BETA,
factory = { FinlandProvider(NAVITIA) }
)
)
),
Country(
R.string.np_region_gb, flag = "🇬🇧", networks = listOf(
TransportNetwork(
id = NetworkId.TLEM,
description = R.string.np_desc_tlem,
factory = { TlemProvider() }
),
TransportNetwork(
id = NetworkId.MERSEY,
name = R.string.np_name_mersey,
description = R.string.np_desc_mersey,
logo = R.drawable.network_mersey_logo,
factory = { MerseyProvider() }
)
)
),
Country(
R.string.np_region_ireland, flag = "🇮🇪", networks = listOf(
TransportNetwork(
id = NetworkId.TFI,
description = R.string.np_desc_tfi,
logo = R.drawable.network_tfi_logo,
factory = { TfiProvider() }
)
)
),
Country(
R.string.np_name_it, flag = "🇮🇹", networks = listOf(
TransportNetwork(
id = NetworkId.IT,
name = R.string.np_name_it,
description = R.string.np_desc_it,
agencies = R.string.np_desc_it_networks,
logo = R.drawable.network_it_logo,
status = BETA,
goodLineNames = true,
factory = { ItalyProvider(NAVITIA) }
)
)
),
Country(
R.string.np_region_poland, "🇵🇱", networks = listOf(
TransportNetwork(
id = NetworkId.PL,
name = R.string.np_name_pl,
description = R.string.np_desc_pl,
logo = R.drawable.network_pl_logo,
factory = { PlProvider() }
),
TransportNetwork(
id = NetworkId.PLNAVITIA,
name = R.string.np_name_pl_navitia,
description = R.string.np_desc_pl_navitia,
agencies = R.string.np_desc_pl_navitia_networks,
logo = R.drawable.network_pl_navitia_logo,
factory = { PlNavitiaProvider(NAVITIA) }
)
)
),
Country(
R.string.np_region_france, "🇫🇷", networks = listOf(
TransportNetwork(
id = NetworkId.PARIS,
name = R.string.np_name_paris,
description = R.string.np_desc_paris,
agencies = R.string.np_desc_paris_networks,
logo = R.drawable.network_paris_logo,
status = BETA,
factory = { ParisProvider(NAVITIA) }
),
TransportNetwork(
id = NetworkId.FRANCESOUTHWEST,
name = R.string.np_name_frenchsouthwest,
description = R.string.np_desc_frenchsouthwest,
agencies = R.string.np_desc_frenchsouthwest_networks,
logo = R.drawable.network_francesouthwest_logo,
status = BETA,
goodLineNames = true,
factory = { FranceSouthWestProvider(NAVITIA) }
),
TransportNetwork(
id = NetworkId.FRANCENORTHEAST,
name = R.string.np_name_francenortheast,
description = R.string.np_desc_francenortheast,
agencies = R.string.np_desc_francenortheast_networks,
logo = R.drawable.network_francenortheast_logo,
status = ALPHA,
goodLineNames = true,
factory = { FranceNorthEastProvider(NAVITIA) }
),
TransportNetwork(
id = NetworkId.FRANCENORTHWEST,
name = R.string.np_name_francenorthwest,
description = R.string.np_desc_francenorthwest,
agencies = R.string.np_desc_francenorthwest_networks,
logo = R.drawable.network_francenorthwest_logo,
status = ALPHA,
factory = { FranceNorthWestProvider(NAVITIA) }
),
TransportNetwork(
id = NetworkId.FRANCESOUTHEAST,
name = R.string.np_name_frenchsoutheast,
description = R.string.np_desc_frenchsoutheast,
agencies = R.string.np_desc_frenchsoutheast_networks,
logo = R.drawable.network_francesoutheast_logo,
status = BETA,
goodLineNames = true,
factory = { FranceSouthEastProvider(NAVITIA) }
)
)
),
Country(
R.string.np_region_pt, flag = "🇵🇹", networks = listOf(
TransportNetwork(
id = NetworkId.PT,
name = R.string.np_name_pt,
description = R.string.np_desc_pt,
agencies = R.string.np_desc_pt_networks,
logo = R.drawable.network_portugal_logo,
status = BETA,
factory = { PortugalProvider(NAVITIA) }
)
)
),
Country(
R.string.np_name_spain, flag = "🇪🇸", networks = listOf(
TransportNetwork(
id = NetworkId.SPAIN,
name = R.string.np_name_spain,
description = R.string.np_desc_spain,
agencies = R.string.np_desc_spain_networks,
logo = R.drawable.network_spain_logo,
status = BETA,
factory = { SpainProvider(NAVITIA) }
)
)
),
Country(
R.string.np_name_hungary, flag = "🇭🇺", networks = listOf(
TransportNetwork(
id = NetworkId.HUNGARY,
name = R.string.np_name_hungary,
description = R.string.np_desc_hungary,
agencies = R.string.np_desc_hungary_networks,
logo = R.drawable.network_hungary_logo,
status = BETA,
factory = { HungaryProvider(NAVITIA) }
)
)
)
)
),
Continent(
R.string.np_continent_africa, R.drawable.continent_africa, countries = listOf(
Country(
R.string.np_name_ghana, flag = "🇬🇭", networks = listOf(
TransportNetwork(
id = NetworkId.GHANA,
name = R.string.np_name_ghana,
description = R.string.np_desc_ghana,
status = ALPHA,
goodLineNames = true,
factory = { GhanaProvider(NAVITIA) }
)
)
)
)
),
Continent(
R.string.np_continent_north_america, R.drawable.continent_north_america, countries = listOf(
Country(
R.string.np_region_usa, "🇺🇸", networks = listOf(
TransportNetwork(
id = NetworkId.RTACHICAGO,
name = R.string.np_name_rtachicago,
description = R.string.np_desc_rtachicago,
agencies = R.string.np_desc_rtachicago_networks,
logo = R.drawable.network_rtachicago_logo,
status = BETA,
factory = { RtaChicagoProvider() }
),
TransportNetwork(
id = NetworkId.CALIFORNIA,
name = R.string.np_name_california,
description = R.string.np_desc_california,
logo = R.drawable.network_california_logo,
status = ALPHA,
factory = { CaliforniaProvider(NAVITIA) }
),
TransportNetwork(
id = NetworkId.OREGON,
name = R.string.np_name_oregon,
description = R.string.np_desc_oregon,
logo = R.drawable.network_oregon_logo,
status = ALPHA,
factory = { OregonProvider(NAVITIA) }
),
TransportNetwork(
id = NetworkId.NEWYORK,
name = R.string.np_name_usny,
description = R.string.np_desc_usny,
status = ALPHA,
factory = { NewyorkProvider(NAVITIA) }
)
)
),
Country(
R.string.np_region_canada, flag = "🇨🇦", networks = listOf(
TransportNetwork(
id = NetworkId.ONTARIO,
name = R.string.np_name_ontario,
description = R.string.np_desc_ontario,
agencies = R.string.np_desc_ontario_networks,
logo = R.drawable.network_ontario_logo,
status = BETA,
goodLineNames = true,
factory = { OntarioProvider(NAVITIA) }
),
TransportNetwork(
id = NetworkId.QUEBEC,
name = R.string.np_name_quebec,
description = R.string.np_desc_quebec,
agencies = R.string.np_desc_quebec_networks,
logo = R.drawable.network_quebec_logo,
status = ALPHA,
goodLineNames = true,
factory = { QuebecProvider(NAVITIA) }
),
TransportNetwork(
id = NetworkId.BRITISHCOLUMBIA,
name = R.string.np_name_britishcolumbia,
description = R.string.np_desc_britishcolumbia,
agencies = R.string.np_desc_britishcolumbia_networks,
logo = R.drawable.network_britishcolumbia_logo,
status = ALPHA,
// check the line below
goodLineNames = true,
factory = { BritishColumbiaProvider(NAVITIA) }
)
)
)
)
),
Continent(
R.string.np_continent_central_america, R.drawable.continent_central_america, countries = listOf(
Country(
R.string.np_name_costa_rica, flag = "🇨🇷", networks = listOf(
TransportNetwork(
id = NetworkId.CR,
name = R.string.np_name_costa_rica,
description = R.string.np_desc_costa_rica,
agencies = R.string.np_desc_costa_rica_networks,
status = ALPHA,
goodLineNames = true,
factory = { CostaRicaProvider(null) }
)
)
),
Country(
R.string.np_name_nicaragua, flag = "🇳🇮", networks = listOf(
TransportNetwork(
id = NetworkId.NICARAGUA,
name = R.string.np_name_nicaragua,
description = R.string.np_desc_nicaragua,
logo = R.drawable.network_nicaragua_logo,
status = ALPHA,
goodLineNames = true,
factory = { NicaraguaProvider(NAVITIA) }
)
)
)
)
),
Continent(
R.string.np_continent_south_america, R.drawable.continent_south_america, countries = listOf(
Country(
R.string.np_name_br, flag = "🇧🇷", networks = listOf(
TransportNetwork(
id = NetworkId.BR,
name = R.string.np_name_br,
description = R.string.np_desc_br,
agencies = R.string.np_desc_br_networks,
logo = R.drawable.network_br_logo,
status = ALPHA,
goodLineNames = true,
factory = { BrProvider(NAVITIA) }
),
TransportNetwork(
id = NetworkId.BRFLORIPA,
name = R.string.np_name_br_floripa,
description = R.string.np_desc_br_floripa,
agencies = R.string.np_desc_br_floripa_networks,
logo = R.drawable.network_brfloripa_logo,
status = ALPHA,
goodLineNames = true,
factory = { BrFloripaProvider(HttpUrl.parse("https://api.transportr.app/floripa/v1/"), null) }
)
)
)
)
),
Continent(
R.string.np_continent_asia, R.drawable.continent_asia, countries = listOf(
Country(
R.string.np_region_uae, "🇦🇪", networks = listOf(
TransportNetwork(
id = NetworkId.DUB,
name = R.string.np_name_dub,
description = R.string.np_desc_dub,
status = BETA,
factory = { DubProvider() }
)
)
)
)
),
Continent(
R.string.np_continent_oceania, R.drawable.continent_oceania, countries = listOf(
Country(
R.string.np_region_australia, flag = "🇦🇺", networks = listOf(
TransportNetwork(
id = NetworkId.AUSTRALIA,
name = R.string.np_name_australia,
description = R.string.np_desc_australia,
agencies = R.string.np_desc_australia_networks,
logo = R.drawable.network_aus_logo,
status = BETA,
factory = { AustraliaProvider(NAVITIA) }
),
TransportNetwork(
id = NetworkId.SYDNEY,
name = R.string.np_name_sydney,
description = R.string.np_desc_sydney,
logo = R.drawable.network_sydney_logo,
factory = { SydneyProvider() }
)
)
),
Country(
R.string.np_name_nz, flag = "🇳🇿", networks = listOf(
TransportNetwork(
id = NetworkId.NZ,
name = R.string.np_name_nz,
description = R.string.np_desc_nz,
agencies = R.string.np_desc_nz_networks,
logo = R.drawable.network_nz_logo,
status = BETA,
factory = { NzProvider(NAVITIA) }
)
)
)
)
)
)
private const val NAVITIA = "87a37b95-913a-4cb4-ba52-eb0bc0b304ca"
private const val VAO = "{\"aid\":\"hf7mcf9bv3nv8g5f\",\"pw\":\"87a6f8ZbnBih32\",\"type\":\"USER\",\"user\":\"mobile\"}"
internal fun getContinentItems(context: Context): List<ContinentItem> {
return List(networks.size) { i ->
networks[i].getItem(context)
}.sortedBy { it.getName(context) }
}
internal fun getTransportNetwork(id: NetworkId): TransportNetwork? {
for (continent in networks) {
return continent.getTransportNetworks().find { it.id == id } ?: continue
}
return null
}
internal fun getTransportNetworkPositions(context: Context, network: TransportNetwork): Triple<Int, Int, Int> {
val continents = networks.sortedBy { it.getName(context) }.withIndex()
for ((continentIndex, continent) in continents) {
val countries = continent.countries.sortedWith(Country.Comparator(context)).withIndex()
for ((countryIndex, country) in countries) {
val networkIndex = country.networks.indexOf(network)
if (networkIndex > -1) {
return Triple(continentIndex, countryIndex, networkIndex)
}
}
}
return Triple(-1, -1, -1)
}
| gpl-3.0 | c1824de0838f532a806fa6204b0acc31 | 45.409669 | 161 | 0.4205 | 4.728805 | false | false | false | false |
tmarsteel/kotlin-prolog | async/src/main/kotlin/com/github/prologdb/async/LazySequenceImpl.kt | 1 | 9493 | package com.github.prologdb.async
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import java.util.concurrent.LinkedBlockingDeque
import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.createCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
internal class LazySequenceImpl<T : Any>(override val principal: Any, code: suspend LazySequenceBuilder<T>.() -> T?) : LazySequence<T> {
/**
* The sequence itself is always working. Results are cached if
* [step] is called more often than necessary for one result.
*/
private enum class InnerState {
/**
* Between steps that do not yield nor declare a future to wait for
*/
RUNNING,
/**
* The coroutine has called [LazySequenceBuilder.yieldAll].
* Calculations and result access is to be done on the subsequence.
*/
SUBSEQUENCE,
/**
* Like [SUBSEQUENCE] but for [LazySequenceBuilder.yieldAllFinal].
*/
SUBSEQUENCE_FINAL,
/**
* Currently waiting for a future. In this case, the [continuation]
* needs to be invoked with the future return value (typing is
* erased out of necessity)
*/
WAITING_ON_FUTURE,
DEPLETED,
FAILED
}
/**
* When [step] finds a new solution, it is appended to this queue.
* This way, invocations of [step] can advance the progress; consumption
* of the results can follow another pace.
*/
private val queuedResults = LinkedBlockingDeque<T>()
@Volatile private var innerState: InnerState = InnerState.RUNNING
/* These are important in state SUBSEQUENCE */
@Volatile private var currentSubSequence: LazySequence<T>? = null
/* These are important in state WAITING_ON_FUTURE */
@Volatile private var currentWaitingFuture: Future<*>? = null
/* These are important in state FAILED */
@Volatile private var error: Throwable? = null
override val state: LazySequence.State
get() = if (queuedResults.isNotEmpty()) LazySequence.State.RESULTS_AVAILABLE else when (innerState) {
InnerState.RUNNING,
InnerState.SUBSEQUENCE,
InnerState.SUBSEQUENCE_FINAL,
InnerState.WAITING_ON_FUTURE -> LazySequence.State.PENDING
InnerState.DEPLETED -> LazySequence.State.DEPLETED
InnerState.FAILED -> LazySequence.State.FAILED
}
private val onComplete = object : Continuation<T?> {
override val context: CoroutineContext = EmptyCoroutineContext
override fun resumeWith(result: Result<T?>) {
if (result.isSuccess) {
result.getOrThrow()?.let(queuedResults::add)
innerState = InnerState.DEPLETED
} else {
error = result.exceptionOrNull()!!
innerState = InnerState.FAILED
}
}
}
private val builder = object : LazySequenceBuilder<T> {
override val principal = [email protected]
override suspend fun <E> await(future: Future<E>): E {
if (future is WorkableFuture ) {
PrincipalConflictException.requireCompatible(principal, future.principal)
}
if (!future.isDone) {
currentWaitingFuture = future
innerState = InnerState.WAITING_ON_FUTURE
suspendCoroutine<Any?> { continuation = it }
}
return try {
future.get()
}
catch (ex: ExecutionException) {
throw ex.cause ?: ex
}
catch (ex: Throwable) {
throw ex
}
}
override suspend fun yield(result: T) {
queuedResults.add(result)
innerState = InnerState.RUNNING
suspendCoroutine<Any?> { continuation = it }
}
override suspend fun yieldAll(results: Iterable<T>) {
queuedResults.addAll(results)
innerState = InnerState.RUNNING
suspendCoroutine<Any?> { continuation = it }
}
override suspend fun yieldAll(results: LazySequence<T>) {
PrincipalConflictException.requireCompatible(principal, results.principal)
currentSubSequence = results
innerState = InnerState.SUBSEQUENCE
suspendCoroutine<Any?> { continuation = it }
}
override suspend fun yieldAllFinal(results: LazySequence<T>): T? {
PrincipalConflictException.requireCompatible(principal, results.principal)
currentSubSequence = results
innerState = InnerState.SUBSEQUENCE_FINAL
@Suppress("UNCHECKED_CAST")
return suspendCoroutine<Any?> { continuation = it } as T?
}
}
@Suppress("UNCHECKED_CAST")
private var continuation: Continuation<Any?> = code.createCoroutine(builder, onComplete) as Continuation<Any?>
private val stepMutex = Any()
override fun step(): LazySequence.State {
synchronized(stepMutex) {
when (innerState) {
InnerState.FAILED,
InnerState.DEPLETED -> return state
InnerState.WAITING_ON_FUTURE -> {
val future = currentWaitingFuture!!
if (future is WorkableFuture) {
future.step()
}
if (future.isDone) {
innerState = InnerState.RUNNING
currentWaitingFuture = null
continuation.resume(Unit)
}
// else -> future not yet done, continue to wait
}
InnerState.RUNNING -> continuation.resume(Unit)
InnerState.SUBSEQUENCE,
InnerState.SUBSEQUENCE_FINAL -> {
val subSeq = currentSubSequence!!
var subState = subSeq.step()
if (subState == LazySequence.State.DEPLETED) {
innerState = InnerState.RUNNING
currentSubSequence = null
continuation.resume(null)
} else {
while (subState == LazySequence.State.RESULTS_AVAILABLE) {
val result = try {
subSeq.tryAdvance()
} catch (handledRightBelow: Throwable) {
null
}
subState = subSeq.state
queuedResults.addLast(result ?: break)
}
when (subState) {
LazySequence.State.DEPLETED -> {
val wasFinal = innerState == InnerState.SUBSEQUENCE_FINAL
innerState = InnerState.RUNNING
currentSubSequence = null
if (wasFinal) {
continuation.resumeWith(Result.success(queuedResults.pollLast()))
}
}
LazySequence.State.FAILED -> {
val ex = try {
subSeq.tryAdvance()
null
} catch (ex: Throwable) {
ex
}
?: RuntimeException("Sub-Sequence reported state FAILED but tryAdvance() did not throw.")
continuation.resumeWithException(ex)
}
else -> { /* all good, go on */
}
}
}
}
}
Unit
}
return state
}
override tailrec fun tryAdvance(): T? {
while (queuedResults.isEmpty()) {
when (innerState) {
InnerState.DEPLETED -> return null
InnerState.FAILED -> throw error ?: throw IllegalStateException()
InnerState.WAITING_ON_FUTURE -> {
try {
currentWaitingFuture!!.get()
}
catch (handledInStep: Throwable) {}
step()
}
else -> step()
}
}
// catch race condition between loop condition and now
return queuedResults.poll() ?: tryAdvance()
}
override fun close() {
if (innerState == InnerState.DEPLETED || innerState == InnerState.FAILED) return
synchronized(stepMutex) {
innerState = InnerState.DEPLETED
}
val subSequenceEx = try {
currentSubSequence?.close()
null
} catch (ex: Throwable) {
ex
}
val futureEx = try {
currentWaitingFuture?.cancel(true)
null
} catch (ex: Throwable) {
ex
}
throwMultipleNotNull(subSequenceEx, futureEx)
}
}
| mit | 57cf3c01cefb10412f8405c5822d0fab | 33.52 | 136 | 0.529548 | 5.637173 | false | false | false | false |
duftler/orca | orca-dry-run/src/main/kotlin/com/netflix/spinnaker/orca/dryrun/DryRunStageDefinitionBuilderFactory.kt | 1 | 2747 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.dryrun
import com.netflix.spinnaker.orca.StageResolver
import com.netflix.spinnaker.orca.pipeline.CheckPreconditionsStage
import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilder
import com.netflix.spinnaker.orca.pipeline.model.Stage
class DryRunStageDefinitionBuilderFactory(
stageResolver: StageResolver
) : DefaultStageDefinitionBuilderFactory(stageResolver) {
override fun builderFor(stage: Stage): StageDefinitionBuilder =
stage.execution.let { execution ->
super.builderFor(stage).let {
if (!execution.trigger.isDryRun || stage.shouldExecuteNormallyInDryRun) {
it
} else {
DryRunStage(it)
}
}
}
private val Stage.shouldExecuteNormallyInDryRun: Boolean
get() = isManualJudgment ||
isPipeline ||
isExpressionPrecondition ||
isFindImage ||
isDetermineTargetServerGroup ||
isRollbackCluster ||
isEvalVariables
private val Stage.isManualJudgment: Boolean
get() = type == "manualJudgment"
private val Stage.isPipeline: Boolean
get() = type == "pipeline"
private val Stage.isFindImage: Boolean
get() = type in setOf("findImage", "findImageFromTags")
private val Stage.isDetermineTargetServerGroup: Boolean
get() = type == "determineTargetServerGroup"
private val Stage.isExpressionPrecondition: Boolean
get() = isPreconditionStage && (isExpressionChild || isExpressionParent)
private val Stage.isPreconditionStage: Boolean
get() = type == CheckPreconditionsStage.PIPELINE_CONFIG_TYPE
private val Stage.isExpressionChild: Boolean
get() = context["preconditionType"] == "expression"
@Suppress("UNCHECKED_CAST")
private val Stage.isExpressionParent: Boolean
get() = (context["preconditions"] as Iterable<Map<String, Any>>?)?.run {
all { it["type"] == "expression" }
} == true
private val Stage.isRollbackCluster: Boolean
get() = type == "rollbackCluster"
private val Stage.isEvalVariables: Boolean
get() = type == "evaluateVariables"
}
| apache-2.0 | 8a95e9b98cdd1ce263e65e22ba78b7bd | 32.91358 | 81 | 0.731707 | 4.353407 | false | false | false | false |
manami-project/manami | manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/inconsistencies/DiffFragment.kt | 1 | 4110 | package io.github.manamiproject.manami.gui.inconsistencies
import io.github.manamiproject.manami.app.inconsistencies.animelist.metadata.AnimeListMetaDataDiff
import io.github.manamiproject.modb.core.extensions.EMPTY
import io.github.manamiproject.modb.core.models.Episodes
import io.github.manamiproject.modb.core.models.Title
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleDoubleProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.scene.Parent
import javafx.scene.layout.Priority.ALWAYS
import tornadofx.*
class DiffFragment: Fragment() {
private val entries: ObjectProperty<ObservableList<DiffViewerEntry>> = SimpleObjectProperty(
FXCollections.observableArrayList()
)
private val tableViewWidthProperty = SimpleDoubleProperty()
private val tableViewHeightProperty = SimpleDoubleProperty()
private val showTitleProperty = SimpleBooleanProperty(false)
private val showTypeProperty = SimpleBooleanProperty(false)
private val showEpiosdesProperty = SimpleBooleanProperty(false)
private val showThumbnailProperty = SimpleBooleanProperty(false)
val diff: SimpleObjectProperty<AnimeListMetaDataDiff> = SimpleObjectProperty<AnimeListMetaDataDiff>().apply {
onChange {
if (it == null) {
return@onChange
}
val current = DiffViewerEntry(
entryType = "current",
title = it.currentEntry.title,
type = it.currentEntry.type.toString(),
episodes = it.currentEntry.episodes,
thumbnail = it.currentEntry.thumbnail.toString(),
)
entries.value.add(current)
val replacement = DiffViewerEntry(
entryType = "replacement",
title = it.replacementEntry.title,
type = it.replacementEntry.type.toString(),
episodes = it.replacementEntry.episodes,
thumbnail = it.replacementEntry.thumbnail.toString(),
)
entries.value.add(replacement)
showTitleProperty.set(current.title != replacement.title)
showTypeProperty.set(current.type != replacement.type)
showEpiosdesProperty.set(current.episodes != replacement.episodes)
showThumbnailProperty.set(current.thumbnail != replacement.thumbnail)
}
}
override val root: Parent = pane {
prefWidthProperty().bind(tableViewWidthProperty)
prefHeightProperty().bind(tableViewHeightProperty)
tableview<DiffViewerEntry> {
hgrow = ALWAYS
vgrow = ALWAYS
fitToParentSize()
itemsProperty().bind(entries)
tableViewWidthProperty.bindBidirectional(prefWidthProperty())
tableViewHeightProperty.bindBidirectional(prefHeightProperty())
readonlyColumn(EMPTY, DiffViewerEntry::entryType) {
sortableProperty().set(false)
}
readonlyColumn("Title", DiffViewerEntry::title) {
sortableProperty().set(false)
visibleProperty().bindBidirectional(showTitleProperty)
}
readonlyColumn("Type", DiffViewerEntry::type) {
sortableProperty().set(false)
visibleProperty().bindBidirectional(showTypeProperty)
}
readonlyColumn("Episodes", DiffViewerEntry::episodes) {
sortableProperty().set(false)
visibleProperty().bindBidirectional(showEpiosdesProperty)
}
readonlyColumn("Thumbnail", DiffViewerEntry::thumbnail) {
sortableProperty().set(false)
visibleProperty().bindBidirectional(showThumbnailProperty)
}
}
}
}
private data class DiffViewerEntry(
val entryType: String,
val title: Title,
val type: String,
val episodes: Episodes,
val thumbnail: String,
) | agpl-3.0 | bf9acb2ebcceb83339ee6feda6162ab7 | 38.152381 | 113 | 0.672019 | 5.386632 | false | false | false | false |
arcao/Geocaching4Locus | geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/internal/moshi/adapter/EnumAdapterFactory.kt | 1 | 3196 | package com.arcao.geocaching4locus.data.api.internal.moshi.adapter
import com.arcao.geocaching4locus.data.api.model.enums.AdditionalWaypointType
import com.arcao.geocaching4locus.data.api.model.enums.GeocacheListType
import com.arcao.geocaching4locus.data.api.model.enums.GeocacheStatus
import com.arcao.geocaching4locus.data.api.model.enums.IdType
import com.arcao.geocaching4locus.data.api.model.enums.IdValueType
import com.arcao.geocaching4locus.data.api.model.enums.MembershipType
import com.arcao.geocaching4locus.data.api.model.enums.StatusCode
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import java.lang.reflect.Type
class EnumAdapterFactory : JsonAdapter.Factory {
override fun create(
type: Type,
annotations: MutableSet<out Annotation>,
moshi: Moshi
): JsonAdapter<*>? {
return when (type) {
AdditionalWaypointType::class.java -> AdditionalWaypointTypeAdapter.INSTANCE
GeocacheListType::class.java -> GeocacheListTypeAdapter.INSTANCE
GeocacheStatus::class.java -> GeocacheStatusAdapter.INSTANCE
MembershipType::class.java -> MembershipTypeAdapter.INSTANCE
StatusCode::class.java -> StatusCodeAdapter.INSTANCE
else -> null
}
}
abstract class ValueEnumAdapter<T : IdValueType> : JsonAdapter<T>() {
abstract fun from(value: String?): T
final override fun fromJson(reader: JsonReader): T = from(reader.nextString())
final override fun toJson(writer: JsonWriter, value: T?) {
writer.value(value?.value)
}
}
abstract class IdEnumAdapter<T : IdType> : JsonAdapter<T>() {
abstract fun from(id: Int?): T
final override fun fromJson(reader: JsonReader): T = from(reader.nextInt())
final override fun toJson(writer: JsonWriter, value: T?) {
writer.value(value?.id)
}
}
class AdditionalWaypointTypeAdapter : IdEnumAdapter<AdditionalWaypointType>() {
companion object {
val INSTANCE = AdditionalWaypointTypeAdapter()
}
override fun from(id: Int?) = AdditionalWaypointType.from(id)
}
class GeocacheListTypeAdapter : IdEnumAdapter<GeocacheListType>() {
companion object {
val INSTANCE = GeocacheListTypeAdapter()
}
override fun from(id: Int?) = GeocacheListType.from(id)
}
class GeocacheStatusAdapter : ValueEnumAdapter<GeocacheStatus>() {
companion object {
val INSTANCE = GeocacheStatusAdapter()
}
override fun from(value: String?) = GeocacheStatus.from(value)
}
class MembershipTypeAdapter : IdEnumAdapter<MembershipType>() {
companion object {
val INSTANCE = MembershipTypeAdapter()
}
override fun from(id: Int?) = MembershipType.from(id)
}
class StatusCodeAdapter : IdEnumAdapter<StatusCode>() {
companion object {
val INSTANCE = StatusCodeAdapter()
}
override fun from(id: Int?) = StatusCode.from(id) ?: StatusCode.BAD_REQUEST
}
}
| gpl-3.0 | a0061f453c7703d915513aa452fd9b4e | 35.735632 | 88 | 0.685857 | 4.591954 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-dessert-release | app/src/main/java/com/example/dessertrelease/ui/DessertReleaseViewModel.kt | 1 | 3160 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dessertrelease.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.dessertrelease.DessertReleaseApplication
import com.example.dessertrelease.R
import com.example.dessertrelease.data.UserPreferencesRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
/*
* View model of Dessert Release components
*/
class DessertReleaseViewModel(
private val userPreferencesRepository: UserPreferencesRepository
) : ViewModel() {
// UI states access for various [DessertReleaseUiState]
val uiState: StateFlow<DessertReleaseUiState> =
userPreferencesRepository.isLinearLayout.map { isLinearLayout ->
DessertReleaseUiState(isLinearLayout)
}.stateIn(
scope = viewModelScope,
// Flow is set to emits value for when app is on the foreground
// 5 seconds stop delay is added to ensure it flows continuously
// for cases such as configuration change
started = SharingStarted.WhileSubscribed(5_000),
initialValue = DessertReleaseUiState()
)
/*
* [selectLayout] change the layout and icons accordingly and
* save the selection in DataStore through [userPreferencesRepository]
*/
fun selectLayout(isLinearLayout: Boolean) {
viewModelScope.launch {
userPreferencesRepository.saveLayoutPreference(isLinearLayout)
}
}
companion object {
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val application = (this[APPLICATION_KEY] as DessertReleaseApplication)
DessertReleaseViewModel(application.userPreferencesRepository)
}
}
}
}
/*
* Data class containing various UI States for Dessert Release screens
*/
data class DessertReleaseUiState(
val isLinearLayout: Boolean = true,
val toggleContentDescription: Int =
if (isLinearLayout) R.string.grid_layout_toggle else R.string.linear_layout_toggle,
val toggleIcon: Int =
if (isLinearLayout) R.drawable.ic_grid_layout else R.drawable.ic_linear_layout
)
| apache-2.0 | f039e30d2f6cce4bb383107dc062e64f | 37.536585 | 93 | 0.740823 | 4.992101 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/ParserDialog.kt | 1 | 2184 | package de.maibornwolff.codecharta.importer.gitlogparser
import com.github.kinquirer.KInquirer
import com.github.kinquirer.components.promptConfirm
import com.github.kinquirer.components.promptInput
import de.maibornwolff.codecharta.importer.gitlogparser.subcommands.LogScanCommand
import de.maibornwolff.codecharta.importer.gitlogparser.subcommands.RepoScanCommand
import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface
class ParserDialog {
companion object : ParserDialogInterface {
override fun collectParserArgs(): List<String> {
val isLogScan = KInquirer.promptConfirm(
message = "Do you already have a git.log and git ls file?",
default = false
)
val subcommand: String =
if (isLogScan) {
"log-scan"
} else {
"repo-scan"
}
val subcommandArguments =
if (isLogScan) LogScanCommand().getDialog().collectParserArgs()
else RepoScanCommand().getDialog().collectParserArgs()
val outputFileName: String = KInquirer.promptInput(
message = "What is the name of the output file? If empty, the result will be returned to stdOut",
hint = "path/to/output/filename.cc.json"
)
val isCompressed = (outputFileName.isEmpty()) || KInquirer.promptConfirm(
message = "Do you want to compress the output file?",
default = true
)
val isSilent: Boolean =
KInquirer.promptConfirm(message = "Do you want to suppress command line output?", default = false)
val addAuthor: Boolean =
KInquirer.promptConfirm(message = "Do you want to add authors to every file?", default = false)
return listOfNotNull(
subcommand,
"--output-file=$outputFileName",
if (isCompressed) null else "--not-compressed",
"--silent=$isSilent",
"--add-author=$addAuthor"
).plus(subcommandArguments)
}
}
}
| bsd-3-clause | 18aa5c69c6f32ff84079b4cf62eda35f | 38.709091 | 114 | 0.608974 | 5.326829 | false | false | false | false |
LorittaBot/Loritta | web/showtime/showtime-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/showtime/frontend/views/CommandsView.kt | 1 | 9652 | package net.perfectdreams.loritta.cinnamon.showtime.frontend.views
import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.dom.addClass
import kotlinx.dom.removeClass
import net.perfectdreams.loritta.cinnamon.showtime.frontend.ShowtimeFrontend
import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.onClick
import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.select
import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.selectAll
import org.w3c.dom.Element
import org.w3c.dom.HTMLAnchorElement
import org.w3c.dom.HTMLDivElement
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.HTMLSpanElement
import org.w3c.dom.get
import kotlin.js.Date
class CommandsView(val showtime: ShowtimeFrontend) : DokyoView() {
override suspend fun onLoad() {
val commandCategories = document.selectAll<HTMLDivElement>("lori-command-category")
val commandEntries = document.selectAll<HTMLDivElement>("lori-command-entry")
val commandCategoryInfo = document.selectAll<HTMLDivElement>("[data-category-info]")
val searchBar = document.select<HTMLInputElement>(".search-bar")
// Auto close all command entries when you click on a new command entry
commandEntries.forEach { entry ->
entry.onClick {
commandEntries.filterNot { it == entry }.forEach {
it.children[0]?.removeAttribute("open")
}
}
}
commandCategories.forEach { categoryTag ->
val categoryEnumName = categoryTag.getAttribute("data-command-category")
val parentAElement = categoryTag.parentElement as HTMLAnchorElement
// We are going to handle the events on the anchor element
parentAElement.onClick {
// Accessibility stuff
if (it.asDynamic().ctrlKey as Boolean || it.asDynamic().metaKey as Boolean || it.asDynamic().shiftKey as Boolean)
return@onClick
it.preventDefault()
if (categoryEnumName == "ALL") {
// If we trying to see all commands, just reset the display of everything
commandEntries.forEach { it.style.display = "" }
} else {
// Hide & Unhide command entries
commandEntries.filter { it.getAttribute("data-command-category") == categoryEnumName }
.forEach { it.style.display = "" }
commandEntries.filterNot { it.getAttribute("data-command-category") == categoryEnumName }
.forEach { it.style.display = "none" }
}
// Hide & Unhide category info
commandCategoryInfo.filter { it.getAttribute("data-category-info") == categoryEnumName }
.forEach { it.style.display = "" }
commandCategoryInfo.filterNot { it.getAttribute("data-category-info") == categoryEnumName }
.forEach { it.style.display = "none" }
// Reset the search bar
searchBar.value = ""
// Toggle selection
commandCategories.filter { it.getAttribute("data-command-category") == categoryEnumName }
.forEach { it.parentElement?.addClass("selected") }
commandCategories.filterNot { it.getAttribute("data-command-category") == categoryEnumName }
.forEach { it.parentElement?.removeClass("selected") }
// Reset scroll to the top of the page
window.scrollTo(0.0, 0.0)
// And push the URL to the history!
// This is actually not needed, but useful if someone wants to share the URL
showtime.pushState(parentAElement.href)
}
}
// Search is a pain to handle, but not impossible!
// We need to do filtering based on the currently visible elements AND the current active category!
searchBar.addEventListener("input", {
val start = Date.now()
// Cache the RegEx to avoid object creation!
// Also, we escpae the search bar value to avoid users writing RegEx...
// (not that is a huuuuge issue because, well, they will only wreck havoc in their own PC, but still...)
val regex = Regex(Regex.escape(searchBar.value), RegexOption.IGNORE_CASE)
// Remove all yellow backgrounds
// We can't use .remove() because that would remove the entire tag, but we want to keep the inner text!
// Behold, a workaround! https://stackoverflow.com/a/60332957/7271796
document.selectAll<HTMLSpanElement>(".yellow").forEach {
it.outerHTML = it.innerHTML
}
// We need to get the currently active category to not unhide stuff that shouldn't be unhidden
// Also, it should be impossible that there isn't any children (unless if the HTML is malformed)
val activeCategory = document.select<HTMLAnchorElement>(".entry.selected")
.children[0]
?.getAttribute("data-command-category") ?: return@addEventListener
commandEntries.forEach {
if (searchBar.value.isBlank()) {
// Search Bar is empty, just unhide everything
if (activeCategory == "ALL") {
it.style.display = ""
} else {
val shouldBeVisible = it.getAttribute("data-command-category") == activeCategory
if (shouldBeVisible)
it.style.display = ""
else
it.style.display = "none"
}
} else {
val shouldBeVisible = activeCategory == "ALL" || it.getAttribute("data-command-category") == activeCategory
// If it shouldn't be visible anyways, do not even *try* to check stuff, just hide them and carry on
if (!shouldBeVisible) {
it.style.display = "none"
return@forEach
}
// Because we want to add a few nice details to the search results (a yellow background on results)
// we need to get all the indexes in the command label and description
val commandLabelElement = it.select<HTMLElement>("lori-command-label")
val commandDescriptionElement = it.select<HTMLElement>("lori-command-description")
fun findMatchesWithinAndHighlight(element: Element): Boolean {
// We need to use innerHTML because we also care about the positions of HTML tags within the text
// If we used something like innerText or textContent, any HTML tag would break the search
val innerHTML = element.innerHTML
val results = regex.findAll(innerHTML)
.toList()
if (results.isNotEmpty()) {
val changedInnerHTMLBuilder = StringBuilder(innerHTML)
// Inserting stuff somewhere would've been too easy... But then you remember that, if you insert
// something, this will cause EVERYTHING to shift, so you also need to add a offset based on the
// size of the tag that you've inserted...
var offset = 0
for (result in results) {
// ew, raw HTML!
// But because we aren't injecting any user input... it is fine ;3
val startingTag = "<span class='yellow' style='background-color: #f7ff00b5;'>"
val endTag = "</span>"
changedInnerHTMLBuilder.insert(
result.range.first + offset,
startingTag
)
offset += startingTag.length
// Even tho "last" is inclusive... it is not working as expected, so we need to +1
changedInnerHTMLBuilder.insert(result.range.last + offset + 1, endTag)
offset += endTag.length
}
element.innerHTML = changedInnerHTMLBuilder.toString()
return true
}
return false
}
// Yes, we need to do both in separate lines, we can't shove them in the same line because, if there is the word in the label, the description
// won't be highlighted! And we want both :3
val labelResult = findMatchesWithinAndHighlight(commandLabelElement)
val descriptionResult = findMatchesWithinAndHighlight(commandDescriptionElement)
val hasAnyMatch = labelResult || descriptionResult
if (hasAnyMatch) {
it.style.display = ""
} else {
it.style.display = "none"
}
}
}
println("End: ${Date.now() - start}")
}, false)
}
} | agpl-3.0 | 8300a0df25d577dc0864266db57c9f4f | 50.074074 | 162 | 0.560402 | 5.359245 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/utils/ext/ContextExt.kt | 1 | 9485 | package com.androidvip.hebf.utils.ext
import android.app.AppOpsManager
import android.app.Dialog
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.PixelFormat
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import android.widget.Toast
import androidx.annotation.DrawableRes
import androidx.fragment.app.Fragment
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.androidvip.hebf.*
import com.androidvip.hebf.utils.Logger.logError
import com.androidvip.hebf.utils.Logger.logWTF
import com.androidvip.hebf.utils.UserPrefs
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.topjohnwu.superuser.ShellUtils
import java.util.*
fun Context?.toast(messageRes: Int, short: Boolean = true) {
if (this == null) return
toast(getString(messageRes), short)
}
fun Context?.toast(message: String?, short: Boolean = true) {
if (message == null || this == null) return
val length = if (short) Toast.LENGTH_SHORT else Toast.LENGTH_LONG
val ctx = this
if (ShellUtils.onMainThread()) {
Toast.makeText(ctx, message, length).show()
} else {
Handler(Looper.getMainLooper()).post {
Toast.makeText(ctx, message, length).show()
}
}
}
inline fun Context.confirm(
message: String = getString(R.string.confirmation_message),
crossinline onConfirm: () -> Unit
) = MaterialAlertDialogBuilder(this).apply {
setTitle(android.R.string.dialog_alert_title)
setMessage(message)
setCancelable(false)
setNegativeButton(R.string.cancelar) { _, _ -> }
setPositiveButton(android.R.string.yes) { _, _ ->
onConfirm()
}
applyAnim().also {
it.show()
}
}
fun Context.runOnMainThread(f: Context.() -> Unit) {
if (Looper.getMainLooper() === Looper.myLooper()) {
f()
} else {
Handler(Looper.getMainLooper()).post { f() }
}
}
fun Context.createVectorDrawable(@DrawableRes resId: Int ) : VectorDrawableCompat? {
return VectorDrawableCompat.create(resources, resId, theme)
}
fun Fragment.createVectorDrawable(@DrawableRes resId: Int ) : VectorDrawableCompat? {
return requireContext().createVectorDrawable(resId)
}
fun Context.getThemedVectorDrawable(@DrawableRes resId: Int): VectorDrawableCompat? {
return createVectorDrawable(resId)?.apply {
setTintCompat(getColorFromAttr(R.attr.colorOnSurface))
}
}
fun Context?.hasUsageStatsPermission(): Boolean {
if (this == null) return false
return try {
val applicationInfo = packageManager.getApplicationInfo(packageName, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
val appOpsManager = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val mode = appOpsManager.checkOpNoThrow(
AppOpsManager.OPSTR_GET_USAGE_STATS,
applicationInfo.uid,
applicationInfo.packageName
)
mode == AppOpsManager.MODE_ALLOWED
} else false
} else false
} catch (e: Exception) {
false
}
}
/**
* Checks if the devices is connected to a network and
* this network has connections stabilised
*
* @return true if the device is online, false otherwise
*/
fun Context?.isOnline(): Boolean {
if (this == null) return false
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = cm.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnectedOrConnecting
}
/**
* Shows an web page in a dialog box. The dialog allows refreshing
* the current page via [SwipeRefreshLayout]
*
* @param url the url to load into the dialog's WebView
*/
fun Context?.webDialog(url: String?) {
if (this == null || url.isNullOrEmpty()) return
val dialog = Dialog(this).apply {
requestWindowFeature(Window.FEATURE_NO_TITLE)
setContentView(R.layout.dialog_web)
setCancelable(true)
}
val webView = dialog.findViewById<WebView>(R.id.webView)
val pb = dialog.findViewById<ProgressBar>(R.id.pb_home)
val swipeLayout: SwipeRefreshLayout = dialog.findViewById(R.id.swipeToRefresh)
swipeLayout.setColorSchemeResources(R.color.colorAccent)
swipeLayout.setOnRefreshListener { webView.reload() }
webView.apply {
val webSettings = webView.settings
webSettings.javaScriptEnabled = true
loadUrl(url)
webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
swipeLayout.isRefreshing = false
}
}
webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, progress: Int) {
pb.progress = progress
if (progress == 100) {
pb.visibility = View.GONE
swipeLayout.isRefreshing = false
} else {
pb.visibility = View.VISIBLE
}
}
}
}
dialog.show()
}
/**
* Opens a web page in a external app
*
* @param context used to start the new activity
* @param url the url to load externally
*/
fun Context?.launchUrl(url: String?) {
if (this == null) return
try {
val uri = Uri.parse(url)
val i = Intent(Intent.ACTION_VIEW, uri)
startActivity(i)
} catch (e: ActivityNotFoundException) {
logWTF("Could not start browser: ${e.message}", this)
}
}
/**
* Changes the interface text to English (US)
*/
fun Context?.toEnglish() {
if (this == null) return
val userPrefs = UserPrefs(applicationContext)
val englishLanguage = userPrefs.getBoolean("english_language", false)
if (englishLanguage) {
val locale = Locale("en")
Locale.setDefault(locale)
val config = Configuration()
config.locale = locale
resources.updateConfiguration(config, resources.displayMetrics)
}
}
fun Context?.hasStoragePermissions(): Boolean {
if (this == null) return false
val perm = "android.permission.READ_EXTERNAL_STORAGE"
val res = checkCallingOrSelfPermission(perm)
return res == PackageManager.PERMISSION_GRANTED
}
fun Context?.canDrawOverlays(): Boolean {
if (this == null) return false
return when {
Build.VERSION.SDK_INT < Build.VERSION_CODES.M -> true
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1 -> {
Settings.canDrawOverlays(this)
}
else -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(this)) return true
// Android 8.0 Oreo bug, always returns false
// This workaround tries to create a window and if an exception is thrown then return false
try {
val mgr = getSystemService(Context.WINDOW_SERVICE) as? WindowManager ?: return false
val viewToAdd = View(this)
val params = WindowManager.LayoutParams(
0,
0,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
} else {
WindowManager.LayoutParams.TYPE_PHONE
},
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSPARENT
)
viewToAdd.layoutParams = params
mgr.addView(viewToAdd, params)
mgr.removeView(viewToAdd)
return true
} catch (e: java.lang.Exception) {
logError(e, applicationContext)
}
false
}
}
}
fun Context?.requestWriteSettingsPermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || this == null) return
if (!Settings.System.canWrite(this)) {
val perm = MaterialAlertDialogBuilder(this)
perm.setTitle(R.string.app_name)
perm.setMessage(getString(R.string.mod_settings_dialog))
perm.setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() }
perm.setPositiveButton(android.R.string.ok) { _, _ ->
try {
Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS).apply {
data = Uri.parse("package:${BuildConfig.APPLICATION_ID}")
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(this)
}
} catch (e: java.lang.Exception) {
logWTF(e.message, applicationContext)
}
}
perm.create().also {
runCatching { it.show() }
}
}
} | apache-2.0 | 9a16f1d19b836b241409e4fabf1c9bf0 | 33.747253 | 115 | 0.650079 | 4.56229 | false | false | false | false |
Haldir65/AndroidRepo | otherprojects/_013_gridlayoutmanager/app/src/main/java/com/me/harris/gridsample/GridSampleActivity.kt | 1 | 2100 | package com.me.harris.gridsample
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import kotlinx.android.synthetic.main.activity_grid_sample.*
class GridSampleActivity: AppCompatActivity() {
val adapter_ by lazy {
CustomAdapter(10,10,"john")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_grid_sample)
recycler_flow?.run {
adapter = adapter_
layoutManager = CustomStaggeredGridLayoutManager(2, RecyclerView.VERTICAL)
addItemDecoration(SimpleDecoration())
addOnScrollListener(object :RecyclerView.OnScrollListener(){
val temp = intArrayOf(-1,-1)
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val manager = layoutManager as StaggeredGridLayoutManager
manager.findFirstVisibleItemPositions(temp)
val position = Math.min(temp[0],temp[1])
if (position>=5){
fake_strip.visibility = View.VISIBLE
}else{
fake_strip.visibility = View.GONE
}
manager.findLastVisibleItemPositions(temp)
val position2 = Math.max(temp[0],temp[1])
if (position2+4>recyclerView.adapter!!.itemCount){
Log.w("==","STARTING PRELOADING")
}
}
})
}
}
} | apache-2.0 | eadf74fbaa5246d726d780d6dbb3a38b | 37.2 | 94 | 0.61619 | 5.46875 | false | false | false | false |
nguyenhoanglam/ImagePicker | imagepicker/src/main/java/com/nguyenhoanglam/imagepicker/model/ImagePickerConfig.kt | 1 | 2698 | /*
* Copyright (C) 2021 Image Picker
* Author: Nguyen Hoang Lam <[email protected]>
*/
package com.nguyenhoanglam.imagepicker.model
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Environment
import android.os.Parcelable
import com.nguyenhoanglam.imagepicker.R
import kotlinx.parcelize.Parcelize
import java.util.*
enum class RootDirectory(val value: String) {
DCIM(Environment.DIRECTORY_DCIM),
PICTURES(Environment.DIRECTORY_PICTURES),
DOWNLOADS(Environment.DIRECTORY_DOWNLOADS)
}
@Parcelize
class ImagePickerConfig(
var statusBarColor: String = "#000000",
var isLightStatusBar: Boolean = false,
var toolbarColor: String = "#212121",
var toolbarTextColor: String = "#FFFFFF",
var toolbarIconColor: String = "#FFFFFF",
var backgroundColor: String = "#424242",
var progressIndicatorColor: String = "#009688",
var selectedIndicatorColor: String = "#1976D2",
var isCameraOnly: Boolean = false,
var isMultipleMode: Boolean = false,
var isFolderMode: Boolean = false,
var isShowNumberIndicator: Boolean = false,
var isShowCamera: Boolean = false,
var maxSize: Int = Int.MAX_VALUE,
var folderGridCount: GridCount = GridCount(2, 4),
var imageGridCount: GridCount = GridCount(3, 5),
var doneTitle: String? = null,
var folderTitle: String? = null,
var imageTitle: String? = null,
var limitMessage: String? = null,
var rootDirectory: RootDirectory = RootDirectory.DCIM,
var subDirectory: String? = null,
var isAlwaysShowDoneButton: Boolean = false,
var selectedImages: ArrayList<Image> = arrayListOf()
) : Parcelable {
fun initDefaultValues(context: Context) {
val resource = context.resources
if (folderTitle == null) {
folderTitle = resource.getString(R.string.imagepicker_title_folder)
}
if (imageTitle == null) {
imageTitle = resource.getString(R.string.imagepicker_title_image)
}
if (doneTitle == null) {
doneTitle = resource.getString(R.string.imagepicker_action_done)
}
if (subDirectory == null) {
subDirectory = getDefaultSubDirectoryName(context)
}
}
private fun getDefaultSubDirectoryName(context: Context): String {
val pm = context.packageManager
val ai: ApplicationInfo? = try {
pm.getApplicationInfo(context.applicationContext.packageName ?: "", 0)
} catch (e: PackageManager.NameNotFoundException) {
null
}
return (if (ai != null) pm.getApplicationLabel(ai) else "Camera") as String
}
} | apache-2.0 | 0c2c905c8978a726c25f0fcd8c9dd915 | 34.051948 | 83 | 0.688288 | 4.255521 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/items/list/DemoableItemListAdapter.kt | 1 | 3557 | package com.lasthopesoftware.bluewater.client.browsing.items.list
import android.app.Activity
import android.os.Build
import android.view.View
import android.widget.ViewAnimator
import com.lasthopesoftware.bluewater.R
import com.lasthopesoftware.bluewater.client.browsing.items.access.ProvideItems
import com.lasthopesoftware.bluewater.client.browsing.items.list.menus.changes.handlers.IItemListMenuChangeHandler
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.parameters.IFileListParameterProvider
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.stringlist.FileStringListProvider
import com.lasthopesoftware.bluewater.client.browsing.items.menu.LongClickViewAnimatorListener
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.stored.library.items.StoredItemAccess
import com.lasthopesoftware.bluewater.shared.android.messages.SendMessages
import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise
import com.lasthopesoftware.bluewater.tutorials.ManageTutorials
import com.lasthopesoftware.bluewater.tutorials.TutorialManager
import tourguide.tourguide.Overlay
import tourguide.tourguide.Pointer
import tourguide.tourguide.ToolTip
import tourguide.tourguide.TourGuide
class DemoableItemListAdapter
(
private val activity: Activity,
sendMessages: SendMessages,
fileListParameterProvider: IFileListParameterProvider,
fileStringListProvider: FileStringListProvider,
itemListMenuEvents: IItemListMenuChangeHandler,
storedItemAccess: StoredItemAccess,
provideItems: ProvideItems,
libraryId: LibraryId,
private val manageTutorials: ManageTutorials
) : ItemListAdapter(
activity,
sendMessages,
fileListParameterProvider,
fileStringListProvider,
itemListMenuEvents,
storedItemAccess,
provideItems,
libraryId
) {
private var wasTutorialShown = false
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
super.onBindViewHolder(holder, position)
if (itemCount == 1 || position != 2)
bindTutorialView(holder.itemView)
}
private fun bindTutorialView(view: View) {
// use this flag to ensure the least amount of possible work is done for this tutorial
if (wasTutorialShown) return
wasTutorialShown = true
fun showTutorial() {
val displayColor =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) activity.resources.getColor(R.color.clearstream_blue, null)
else activity.resources.getColor(R.color.clearstream_blue)
val tourGuide = TourGuide.init(activity).with(TourGuide.Technique.CLICK)
.setPointer(Pointer().setColor(displayColor))
.setToolTip(
ToolTip()
.setTitle(activity.getString(R.string.title_long_click_menu))
.setDescription(activity.getString(R.string.tutorial_long_click_menu))
.setBackgroundColor(displayColor)
)
.setOverlay(Overlay())
.playOn(view)
view.setOnLongClickListener {
tourGuide.cleanUp()
if (view is ViewAnimator)
view.setOnLongClickListener(LongClickViewAnimatorListener(view))
false
}
}
if (DEBUGGING_TUTORIAL) {
showTutorial()
return
}
manageTutorials
.promiseWasTutorialShown(TutorialManager.KnownTutorials.longPressListTutorial)
.eventually(LoopedInPromise.response({ wasShown ->
if (!wasShown) {
showTutorial()
manageTutorials.promiseTutorialMarked(TutorialManager.KnownTutorials.longPressListTutorial)
}
}, activity))
}
companion object {
private const val DEBUGGING_TUTORIAL = false
}
}
| lgpl-3.0 | 8c4f5b2f1d3b55cb1f50fc9dc9444b9a | 33.872549 | 116 | 0.809109 | 4.116898 | false | false | false | false |
andrei-heidelbacher/algostorm | algostorm-systems/src/main/kotlin/com/andreihh/algostorm/systems/graphics2d/CameraSystem.kt | 1 | 2392 | /*
* Copyright 2017 Andrei Heidelbacher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.andreihh.algostorm.systems.graphics2d
import com.andreihh.algostorm.core.drivers.graphics2d.Canvas
import com.andreihh.algostorm.core.ecs.EntityGroup
import com.andreihh.algostorm.core.ecs.EntityRef.Id
import com.andreihh.algostorm.core.event.Event
import com.andreihh.algostorm.core.event.Subscribe
import com.andreihh.algostorm.systems.physics2d.position
class CameraSystem : GraphicsSystem() {
private val entities: EntityGroup by context(ENTITY_POOL)
private val camera: Camera by context(CAMERA)
private val canvas: Canvas by context(GRAPHICS_DRIVER)
private var followedEntityId: Id? = null
object UpdateCamera : Event
data class FocusOn(val x: Int, val y: Int) : Event
data class Follow(val entityId: Id) : Event
data class Scroll(val dx: Int, val dy: Int) : Event
object UnFollow : Event
@Suppress("unused_parameter")
@Subscribe
fun onUpdateCamera(event: UpdateCamera) {
camera.resize(canvas.width, canvas.height)
val id = followedEntityId ?: return
val entity = entities[id] ?: return
val (tx, ty) = entity.position ?: return
val x = tileWidth * tx + tileWidth / 2
val y = tileHeight * ty + tileHeight / 2
camera.focusOn(x, y)
}
@Subscribe
fun onFocusOn(event: FocusOn) {
followedEntityId = null
camera.focusOn(event.x, event.y)
}
@Subscribe
fun onFollow(event: Follow) {
followedEntityId = event.entityId
}
@Subscribe
fun onScroll(event: Scroll) {
followedEntityId = null
camera.translate(event.dx, event.dy)
}
@Suppress("unused_parameter")
@Subscribe
fun onUnFollow(event: UnFollow) {
followedEntityId = null
}
}
| apache-2.0 | 8374ed4209bfafe8cd854befd3077bc3 | 30.473684 | 75 | 0.699833 | 4.061121 | false | false | false | false |
aakaashjois/TODO | app/src/main/java/com/biryanistudio/todo/fragments/TodoFragment.kt | 1 | 2620 | package com.biryanistudio.todo.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.biryanistudio.todo.R
import com.biryanistudio.todo.adapters.TodoRecyclerViewAdapter
import com.biryanistudio.todo.database.TodoItem
import io.realm.Realm
import io.realm.Sort
import kotlinx.android.synthetic.main.list_fragment.*
import kotlinx.android.synthetic.main.list_fragment.view.*
import kotlin.properties.Delegates.notNull
/**
* Created by Aakaash Jois.
* 23/06/17 - 9:21 AM.
*/
class TodoFragment : Fragment() {
var page: Int by notNull()
lateinit var realm: Realm
companion object {
val PAGE = "page"
fun newInstance(page: Int): TodoFragment {
return TodoFragment().apply {
arguments = Bundle().apply { putFloat(PAGE, page.toFloat()) }
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
page = arguments.getFloat(PAGE, -1f).toInt()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
realm = Realm.getDefaultInstance()
val realmResults = realm.where(TodoItem::class.java).equalTo(TodoItem.COMPLETED, page)
.findAllSorted(TodoItem.TIMESTAMP, Sort.DESCENDING)
val view = inflater.inflate(R.layout.list_fragment, container, false).apply {
recycler_view.adapter = TodoRecyclerViewAdapter(activity, realmResults)
empty_view.text = when (page) {
0 -> context.getString(R.string.text_not_added_pending_yet)
1 -> context.getString(R.string.text_not_completed)
else -> null
}
if (realmResults.size == 0) {
recycler_view.visibility = View.GONE
empty_view.visibility = View.VISIBLE
} else {
recycler_view.visibility = View.VISIBLE
empty_view.visibility = View.GONE
}
}
realmResults.addChangeListener({ result ->
if (result.size == 0) {
recycler_view.visibility = View.GONE
empty_view.visibility = View.VISIBLE
} else {
recycler_view.visibility = View.VISIBLE
empty_view.visibility = View.GONE
}
})
return view
}
override fun onDestroy() {
super.onDestroy()
realm.close()
}
}
| gpl-3.0 | 6c2d0ce5a6b13dad65f597eda5f97944 | 32.164557 | 94 | 0.620992 | 4.478632 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/settings/privacy/studies/StudiesFragment.kt | 1 | 5778 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.settings.privacy.studies
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.URLSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.text.HtmlCompat
import androidx.core.text.getSpans
import androidx.lifecycle.ViewModelProvider
import mozilla.components.browser.state.state.SessionState
import org.mozilla.focus.R
import org.mozilla.focus.databinding.FragmentStudiesBinding
import org.mozilla.focus.ext.components
import org.mozilla.focus.ext.showToolbar
import org.mozilla.focus.settings.BaseSettingsLikeFragment
import org.mozilla.focus.state.AppAction
import org.mozilla.focus.utils.SupportUtils
import kotlin.system.exitProcess
class StudiesFragment : BaseSettingsLikeFragment() {
private var _binding: FragmentStudiesBinding? = null
private val binding get() = _binding!!
private lateinit var viewModel: StudiesViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentStudiesBinding.inflate(inflater, container, false)
viewModel = ViewModelProvider(
this,
).get(StudiesViewModel::class.java)
setLearnMore()
setStudiesSwitch()
setRemoveStudyListener()
setObservers()
return binding.root
}
override fun onStart() {
super.onStart()
showToolbar(getString(R.string.preference_studies))
}
private fun setLearnMore() {
val sumoUrl =
SupportUtils.getGenericSumoURLForTopic(SupportUtils.SumoTopic.STUDIES)
val description = getString(R.string.preference_studies_summary)
val learnMore = getString(R.string.studies_learn_more)
val rawText = "$description <a href=\"$sumoUrl\">$learnMore</a>"
val text = HtmlCompat.fromHtml(rawText, HtmlCompat.FROM_HTML_MODE_COMPACT)
val spannableStringBuilder = SpannableStringBuilder(text)
val links = spannableStringBuilder.getSpans<URLSpan>()
for (link in links) {
addActionToLinks(spannableStringBuilder, link)
}
binding.studiesDescription.text = spannableStringBuilder
binding.studiesDescription.movementMethod = LinkMovementMethod.getInstance()
}
private fun addActionToLinks(spannableStringBuilder: SpannableStringBuilder, link: URLSpan) {
val start = spannableStringBuilder.getSpanStart(link)
val end = spannableStringBuilder.getSpanEnd(link)
val flags = spannableStringBuilder.getSpanFlags(link)
val clickable: ClickableSpan = object : ClickableSpan() {
override fun onClick(view: View) {
view.setOnClickListener {
openLearnMore.invoke()
}
}
}
spannableStringBuilder.setSpan(clickable, start, end, flags)
spannableStringBuilder.removeSpan(link)
}
private val openLearnMore = {
val tabId = requireContext().components.tabsUseCases.addTab(
url = SupportUtils.getGenericSumoURLForTopic(SupportUtils.SumoTopic.STUDIES),
source = SessionState.Source.Internal.Menu,
selectTab = true,
private = true,
)
requireContext().components.appStore.dispatch(AppAction.OpenTab(tabId))
}
private fun setStudiesTitleByState(switchState: Boolean) {
binding.studiesTitle.text = if (switchState) {
getString(R.string.preference_state_on)
} else {
getString(R.string.preference_state_off)
}
}
private fun setStudiesSwitch() {
binding.studiesSwitch.setOnClickListener {
val builder = AlertDialog.Builder(requireContext())
.setPositiveButton(
R.string.action_ok,
) { dialog, _ ->
viewModel.setStudiesState(binding.studiesSwitch.isChecked)
dialog.dismiss()
quitTheApp()
}
.setNegativeButton(
R.string.action_cancel,
) { dialog, _ ->
binding.studiesSwitch.isChecked = !binding.studiesSwitch.isChecked
setStudiesTitleByState(binding.studiesSwitch.isChecked)
dialog.dismiss()
}
.setTitle(R.string.preference_studies)
.setMessage(R.string.studies_restart_app)
.setCancelable(false)
val alertDialog: AlertDialog = builder.create()
alertDialog.show()
}
}
private fun quitTheApp() {
exitProcess(0)
}
private fun setRemoveStudyListener() {
binding.studiesList.studiesAdapter.removeStudyListener = { study ->
viewModel.removeStudy(study)
}
}
private fun setObservers() {
viewModel.exposedStudies.observe(
viewLifecycleOwner,
) { studies ->
binding.studiesList.studiesAdapter.submitList(studies)
}
viewModel.studiesState.observe(
viewLifecycleOwner,
) { state ->
binding.studiesSwitch.isChecked = state
setStudiesTitleByState(state)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| mpl-2.0 | 7b3186af4975f322eaa6d9533f758baa | 35.56962 | 97 | 0.657494 | 4.888325 | false | false | false | false |
mplatvoet/kovenant | projects/combine/src/test/kotlin/examples/combine.kt | 1 | 1556 | /*
* Copyright (c) 2015 Mark Platvoet<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* THE SOFTWARE.
*/
package examples.combine
import nl.komponents.kovenant.combine.and
import nl.komponents.kovenant.task
import support.fib
fun main(args: Array<String>) {
val fib20Promise = task { fib(20) }
val helloWorldPromise = task { "hello world" }
fib20Promise and helloWorldPromise success {
val (fib, msg) = it
println("$msg, fib(20) = $fib")
}
task { fib(20) } and task { "hello world" } success {
println("${it.second}, fib(20) = ${it.first}")
}
}
| mit | 31dd1c58b02f994d30aef1733828e7fc | 36.95122 | 80 | 0.72108 | 4.149333 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/state/AppReducer.kt | 1 | 10155 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@file:Suppress("TooManyFunctions")
package org.mozilla.focus.state
import mozilla.components.feature.top.sites.TopSite
import mozilla.components.lib.state.Reducer
/**
* Reducer creating a new [AppState] for dispatched [AppAction]s.
*/
@Suppress("ComplexMethod")
object AppReducer : Reducer<AppState, AppAction> {
override fun invoke(state: AppState, action: AppAction): AppState {
return when (action) {
is AppAction.SelectionChanged -> selectionChanged(state, action)
is AppAction.NoTabs -> noTabs(state)
is AppAction.EditAction -> editAction(state, action)
is AppAction.FinishEdit -> finishEditing(state, action)
is AppAction.HideTabs -> hideTabs(state)
is AppAction.ShowFirstRun -> showFirstRun(state)
is AppAction.FinishFirstRun -> finishFirstRun(state, action)
is AppAction.Lock -> lock(state, action)
is AppAction.Unlock -> unlock(state, action)
is AppAction.OpenSettings -> openSettings(state, action)
is AppAction.NavigateUp -> navigateUp(state, action)
is AppAction.OpenTab -> openTab(state, action)
is AppAction.TopSitesChange -> topSitesChanged(state, action)
is AppAction.SitePermissionOptionChange -> sitePermissionOptionChanged(state, action)
is AppAction.SecretSettingsStateChange -> secretSettingsStateChanged(
state,
action,
)
is AppAction.ShowEraseTabsCfrChange -> showEraseTabsCfrChanged(state, action)
is AppAction.ShowStartBrowsingCfrChange -> showStartBrowsingCfrChanged(state, action)
is AppAction.ShowTrackingProtectionCfrChange -> showTrackingProtectionCfrChanged(state, action)
is AppAction.OpenSitePermissionOptionsScreen -> openSitePermissionOptionsScreen(state, action)
is AppAction.ShowHomeScreen -> showHomeScreen(state)
is AppAction.ShowOnboardingSecondScreen -> showOnBoardingSecondScreen(state)
is AppAction.ShowSearchWidgetSnackBar -> showSearchWidgetSnackBarChanged(state, action)
}
}
}
/**
* The currently selected tab has changed.
*/
private fun selectionChanged(state: AppState, action: AppAction.SelectionChanged): AppState {
if (state.screen is Screen.FirstRun || state.screen is Screen.Locked) {
return state
}
return state.copy(
screen = Screen.Browser(tabId = action.tabId, showTabs = false),
)
}
/**
* All tabs have been closed.
*/
private fun noTabs(state: AppState): AppState {
if (state.screen is Screen.Home || state.screen is Screen.FirstRun || state.screen is Screen.Locked) {
return state
}
return state.copy(screen = Screen.Home)
}
/**
* The user wants to edit the URL of a tab.
*/
private fun editAction(state: AppState, action: AppAction.EditAction): AppState {
return state.copy(
screen = Screen.EditUrl(action.tabId),
)
}
/**
* The user finished editing the URL.
*/
private fun finishEditing(state: AppState, action: AppAction.FinishEdit): AppState {
return state.copy(
screen = Screen.Browser(tabId = action.tabId, showTabs = false),
)
}
/**
* Hide the tabs tray.
*/
private fun hideTabs(state: AppState): AppState {
return if (state.screen is Screen.Browser) {
state.copy(screen = state.screen.copy(showTabs = false))
} else {
state
}
}
/**
* The user finished the first run onboarding.
*/
private fun finishFirstRun(state: AppState, action: AppAction.FinishFirstRun): AppState {
return if (action.tabId != null) {
state.copy(screen = Screen.Browser(action.tabId, showTabs = false))
} else {
state.copy(screen = Screen.Home)
}
}
/**
* Force showing the first run screen (for testing).
*/
private fun showFirstRun(state: AppState): AppState {
return state.copy(screen = Screen.FirstRun)
}
private fun showOnBoardingSecondScreen(state: AppState): AppState {
return state.copy(screen = Screen.OnboardingSecondScreen)
}
/**
* Force showing the home screen.
*/
private fun showHomeScreen(state: AppState): AppState {
return state.copy(screen = Screen.Home)
}
/**
* Lock the application.
*/
private fun lock(state: AppState, action: AppAction.Lock): AppState {
return state.copy(screen = Screen.Locked(action.bundle))
}
/**
* Unlock the application.
*/
private fun unlock(state: AppState, action: AppAction.Unlock): AppState {
if (state.screen !is Screen.Locked) {
return state
}
return if (action.tabId != null) {
state.copy(screen = Screen.Browser(action.tabId, showTabs = false))
} else {
state.copy(screen = Screen.Home)
}
}
private fun openSettings(state: AppState, action: AppAction.OpenSettings): AppState {
return state.copy(
screen = Screen.Settings(page = action.page),
)
}
private fun openTab(state: AppState, action: AppAction.OpenTab): AppState {
return state.copy(
screen = Screen.Browser(tabId = action.tabId, showTabs = false),
)
}
/**
* The list of [TopSite] has changed.
*/
private fun topSitesChanged(state: AppState, action: AppAction.TopSitesChange): AppState {
return state.copy(topSites = action.topSites)
}
/**
* The rules of site permissions autoplay has changed.
*/
private fun sitePermissionOptionChanged(state: AppState, action: AppAction.SitePermissionOptionChange): AppState {
return state.copy(sitePermissionOptionChange = action.value)
}
/**
* The state of secret settings has changed.
*/
private fun secretSettingsStateChanged(state: AppState, action: AppAction.SecretSettingsStateChange): AppState {
return state.copy(secretSettingsEnabled = action.enabled)
}
/**
* The state of erase tabs CFR changed
*/
private fun showEraseTabsCfrChanged(state: AppState, action: AppAction.ShowEraseTabsCfrChange): AppState {
return state.copy(showEraseTabsCfr = action.value)
}
/**
* Update whether the start browsing CFR should be shown or not
*/
private fun showStartBrowsingCfrChanged(state: AppState, action: AppAction.ShowStartBrowsingCfrChange): AppState {
return state.copy(showStartBrowsingTabsCfr = action.value)
}
/**
* The state of search widget snackBar changed
*/
private fun showSearchWidgetSnackBarChanged(state: AppState, action: AppAction.ShowSearchWidgetSnackBar): AppState {
return state.copy(showSearchWidgetSnackbar = action.value)
}
/**
* The state of tracking protection CFR changed
*/
private fun showTrackingProtectionCfrChanged(
state: AppState,
action: AppAction.ShowTrackingProtectionCfrChange,
): AppState {
return state.copy(showTrackingProtectionCfrForTab = action.value)
}
private fun openSitePermissionOptionsScreen(
state: AppState,
action: AppAction.OpenSitePermissionOptionsScreen,
): AppState {
return state.copy(screen = Screen.SitePermissionOptionsScreen(sitePermission = action.sitePermission))
}
@Suppress("ComplexMethod", "ReturnCount")
private fun navigateUp(state: AppState, action: AppAction.NavigateUp): AppState {
if (state.screen is Screen.Browser) {
val screen = if (action.tabId != null) {
Screen.Browser(tabId = action.tabId, showTabs = false)
} else {
Screen.Home
}
return state.copy(screen = screen)
}
if (state.screen is Screen.SitePermissionOptionsScreen) {
return state.copy(screen = Screen.Settings(page = Screen.Settings.Page.SitePermissions))
}
if (state.screen !is Screen.Settings) {
return state
}
val screen = when (state.screen.page) {
Screen.Settings.Page.Start -> if (action.tabId != null) {
Screen.Browser(tabId = action.tabId, showTabs = false)
} else {
Screen.Home
}
Screen.Settings.Page.General -> Screen.Settings(page = Screen.Settings.Page.Start)
Screen.Settings.Page.Privacy -> Screen.Settings(page = Screen.Settings.Page.Start)
Screen.Settings.Page.Search -> Screen.Settings(page = Screen.Settings.Page.Start)
Screen.Settings.Page.Advanced -> Screen.Settings(page = Screen.Settings.Page.Start)
Screen.Settings.Page.Mozilla -> Screen.Settings(page = Screen.Settings.Page.Start)
Screen.Settings.Page.PrivacyExceptions -> Screen.Settings(page = Screen.Settings.Page.Privacy)
Screen.Settings.Page.PrivacyExceptionsRemove -> Screen.Settings(page = Screen.Settings.Page.PrivacyExceptions)
Screen.Settings.Page.SitePermissions -> Screen.Settings(page = Screen.Settings.Page.Privacy)
Screen.Settings.Page.Studies -> Screen.Settings(page = Screen.Settings.Page.Privacy)
Screen.Settings.Page.SecretSettings -> Screen.Settings(page = Screen.Settings.Page.Advanced)
Screen.Settings.Page.SearchList -> Screen.Settings(page = Screen.Settings.Page.Search)
Screen.Settings.Page.SearchRemove -> Screen.Settings(page = Screen.Settings.Page.SearchList)
Screen.Settings.Page.SearchAdd -> Screen.Settings(page = Screen.Settings.Page.SearchList)
Screen.Settings.Page.SearchAutocomplete -> Screen.Settings(page = Screen.Settings.Page.Search)
Screen.Settings.Page.SearchAutocompleteList -> Screen.Settings(page = Screen.Settings.Page.SearchAutocomplete)
Screen.Settings.Page.SearchAutocompleteAdd -> Screen.Settings(
page = Screen.Settings.Page.SearchAutocompleteList,
)
Screen.Settings.Page.SearchAutocompleteRemove -> Screen.Settings(
page = Screen.Settings.Page.SearchAutocompleteList,
)
Screen.Settings.Page.About -> Screen.Settings(page = Screen.Settings.Page.Mozilla)
Screen.Settings.Page.Locale -> Screen.Settings(page = Screen.Settings.Page.General)
Screen.Settings.Page.CookieBanner -> Screen.Settings(page = Screen.Settings.Page.Privacy)
}
return state.copy(screen = screen)
}
| mpl-2.0 | 9ded10f475dab55e4731238acd0d1cf7 | 35.528777 | 118 | 0.702905 | 4.203228 | false | false | false | false |
nestlabs/connectedhomeip | src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/clusterinteraction/HistoryCommandAdapter.kt | 2 | 7983 | package com.google.chip.chiptool.clusterclient.clusterinteraction
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import chip.clusterinfo.CommandResponseInfo
import com.google.chip.chiptool.R
import kotlinx.android.synthetic.main.cluster_callback_item.view.clusterCallbackDataTv
import kotlinx.android.synthetic.main.cluster_callback_item.view.clusterCallbackNameTv
import kotlinx.android.synthetic.main.cluster_callback_item.view.clusterCallbackTypeTv
import kotlinx.android.synthetic.main.cluster_interaction_history_item_info.view.historyClusterNameTv
import kotlinx.android.synthetic.main.cluster_interaction_history_item_info.view.historyCommandNameTv
import kotlinx.android.synthetic.main.cluster_parameter_item.view.clusterParameterData
import kotlinx.android.synthetic.main.cluster_parameter_item.view.clusterParameterNameTv
import kotlinx.android.synthetic.main.cluster_parameter_item.view.clusterParameterTypeTv
/**
* HistoryCommandAdapter implements the historyCommandList(RecycleView) Adapter and associates different
* history command with the same onClick function provided in [ClusterInteractionHistoryFragment.HistoryCommandListener]
*/
class HistoryCommandAdapter(
private val HistoryCommandList: List<HistoryCommand>,
private val listener: ClusterInteractionHistoryFragment.HistoryCommandListener,
private val inflater: LayoutInflater,
) : RecyclerView.Adapter<HistoryCommandAdapter.HistoryCommandViewHolder>() {
inner class HistoryCommandViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener {
var historyInfo: LinearLayout = itemView.findViewById(R.id.historyBasicInfo)
var parameterList: LinearLayout = itemView.findViewById(R.id.historyParameterList)
var responseValueList: LinearLayout = itemView.findViewById(R.id.historyResponseValueList)
var statusCode: LinearLayout = itemView.findViewById(R.id.historyItemStatus)
init {
itemView.setOnClickListener(this)
}
override fun onClick(endpointItem: View) {
val position = this.adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position)
}
}
}
interface OnItemClickListener {
fun onItemClick(position: Int)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryCommandViewHolder {
val itemView =
LayoutInflater.from(parent.context)
.inflate(R.layout.cluster_interaction_history_item, parent, false)
return HistoryCommandViewHolder(itemView)
}
override fun getItemCount(): Int {
return HistoryCommandList.size
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getItemViewType(position: Int): Int {
return position
}
override fun onBindViewHolder(
holder: HistoryCommandAdapter.HistoryCommandViewHolder,
position: Int
) {
// go through each element and fill the data
// fill out cluster name and command name
clearPreviousReview(holder)
val info = inflater.inflate(
R.layout.cluster_interaction_history_item_info,
null,
false
) as ConstraintLayout
info.historyClusterNameTv.text = HistoryCommandList[position].clusterName
info.historyCommandNameTv.text = HistoryCommandList[position].commandName
holder.historyInfo.addView(info)
// fill out parameterList
if (HistoryCommandList[position].parameterList.isEmpty()) {
val emptyParameterList =
inflater.inflate(android.R.layout.simple_list_item_1, null, false) as TextView
emptyParameterList.text = "No parameter"
holder.parameterList.addView(emptyParameterList)
} else {
HistoryCommandList[position].parameterList.forEach {
val param =
inflater.inflate(R.layout.cluster_parameter_item, null, false) as ConstraintLayout
param.clusterParameterData.setText(it.parameterData)
param.clusterParameterNameTv.text = it.parameterName
param.clusterParameterTypeTv.text = formatParameterType(it.parameterType)
holder.parameterList.addView(param)
}
}
// fill out responseList
if (HistoryCommandList[position].responseValue == null || HistoryCommandList[position].responseValue!!.isEmpty()) {
val emptyResponseInfo =
inflater.inflate(android.R.layout.simple_list_item_1, null, false) as TextView
emptyResponseInfo.text = "No response"
holder.responseValueList.addView(emptyResponseInfo)
} else {
populateCallbackResult(
HistoryCommandList[position].responseValue!!,
inflater,
holder.responseValueList
)
}
// fill out status
val statusInfo = inflater.inflate(android.R.layout.simple_list_item_1, null, false) as TextView
statusInfo.text = "Status: " + HistoryCommandList[position].status
holder.statusCode.addView(statusInfo)
}
private fun populateCallbackResult(
responseValues: Map<CommandResponseInfo, Any>,
inflater: LayoutInflater,
callbackList: LinearLayout
) {
responseValues.forEach { (variableNameType, response) ->
if (response is List<*>) {
createListResponseView(response, inflater, callbackList, variableNameType)
} else {
createBasicResponseView(response, inflater, callbackList, variableNameType)
}
}
}
private fun createBasicResponseView(
response: Any,
inflater: LayoutInflater,
callbackList: LinearLayout,
variableNameType: CommandResponseInfo
) {
val callbackItem =
inflater.inflate(R.layout.cluster_callback_item, null, false) as ConstraintLayout
callbackItem.clusterCallbackNameTv.text = variableNameType.name
callbackItem.clusterCallbackDataTv.text = if (response.javaClass == ByteArray::class.java) {
(response as ByteArray).decodeToString()
} else {
response.toString()
}
callbackItem.clusterCallbackTypeTv.text = variableNameType.type
callbackList.addView(callbackItem)
}
private fun createListResponseView(
response: List<*>,
inflater: LayoutInflater,
callbackList: LinearLayout,
variableNameType: CommandResponseInfo
) {
if (response.isEmpty()) {
val emptyCallback =
inflater.inflate(R.layout.cluster_callback_item, null, false) as ConstraintLayout
emptyCallback.clusterCallbackNameTv.text = "Result is empty"
callbackList.addView(emptyCallback)
} else {
response.forEachIndexed { index, it ->
val attributeCallbackItem =
inflater.inflate(R.layout.cluster_callback_item, null, false) as ConstraintLayout
attributeCallbackItem.clusterCallbackNameTv.text = variableNameType.name + "[$index]"
val objectString = if (it!!.javaClass == ByteArray::class.java) {
(it as ByteArray).contentToString()
} else {
it.toString()
}
var callbackClassName = if (it!!.javaClass == ByteArray::class.java) {
"Byte[]"
} else {
it!!.javaClass.toString().split('$').last()
}
attributeCallbackItem.clusterCallbackDataTv.text = objectString
attributeCallbackItem.clusterCallbackTypeTv.text = "List<$callbackClassName>"
callbackList.addView(attributeCallbackItem)
}
}
}
private fun formatParameterType(castType: Class<*>): String {
return if (castType == ByteArray::class.java) {
"Byte[]"
} else {
castType.toString()
}
}
private fun clearPreviousReview(holder: HistoryCommandAdapter.HistoryCommandViewHolder) {
holder.historyInfo.removeAllViews()
holder.parameterList.removeAllViews()
holder.responseValueList.removeAllViews()
holder.statusCode.removeAllViews()
}
} | apache-2.0 | b98e1a0513fa00ee37c9cebc8e2cfab2 | 38.330049 | 120 | 0.738319 | 4.65481 | false | false | false | false |
Ekito/koin | koin-projects/koin-androidx-viewmodel/src/main/java/org/koin/androidx/viewmodel/compat/ViewModelCompat.kt | 1 | 2540 | ///*
// * Copyright 2017-2020 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.androidx.viewmodel.compat
//
//import androidx.lifecycle.ViewModel
//import androidx.lifecycle.ViewModelStoreOwner
//import org.koin.androidx.viewmodel.ViewModelOwner
//import org.koin.androidx.viewmodel.koin.getViewModel
//import org.koin.core.context.GlobalContext
//import org.koin.core.parameter.ParametersDefinition
//import org.koin.core.qualifier.Qualifier
//
///**
// * LifecycleOwner functions to help for ViewModel in Java
// *
// * @author Jeziel Lago
// */
//object ViewModelCompat {
//
// /**
// * Lazy get a viewModel instance
// *
// * @param owner - LifecycleOwner
// * @param clazz - viewModel class dependency
// * @param qualifier - Koin BeanDefinition qualifier (if have several ViewModel beanDefinition of the same type)
// * @param parameters - parameters to pass to the BeanDefinition
// */
// @JvmOverloads
// @JvmStatic
// fun <T : ViewModel> viewModel(
// owner: ViewModelStoreOwner,
// clazz: Class<T>,
// qualifier: Qualifier? = null,
// parameters: ParametersDefinition? = null
// ): Lazy<T> = lazy { getViewModel(owner, clazz, qualifier, parameters) }
//
//
// /**
// * Get a viewModel instance
// *
// * @param owner - LifecycleOwner
// * @param clazz - Class of the BeanDefinition to retrieve
// * @param qualifier - Koin BeanDefinition qualifier (if have several ViewModel beanDefinition of the same type)
// * @param parameters - parameters to pass to the BeanDefinition
// */
// @JvmOverloads
// @JvmStatic
// fun <T : ViewModel> getViewModel(
// owner: ViewModelStoreOwner,
// clazz: Class<T>,
// qualifier: Qualifier? = null,
// parameters: ParametersDefinition? = null
// ): T = GlobalContext.get().getViewModel(qualifier, null, { ViewModelOwner.from(owner) }, clazz.kotlin, parameters)
//} | apache-2.0 | edcdefc90cad1ae62ce87dd3a79d6921 | 36.925373 | 120 | 0.677559 | 4.083601 | false | false | false | false |
ac-opensource/Matchmaking-App | app/src/main/java/com/youniversals/playupgo/main/MainActivity.kt | 1 | 14848 | package com.youniversals.playupgo.main
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.location.Geocoder
import android.os.Bundle
import android.support.design.widget.BottomNavigationView.*
import android.support.design.widget.BottomSheetBehavior
import android.text.TextUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.RelativeLayout
import com.bumptech.glide.Glide
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.places.Places
import com.google.android.gms.location.places.ui.PlacePicker
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.firebase.analytics.FirebaseAnalytics
import com.pixplicity.easyprefs.library.Prefs
import com.tbruyelle.rxpermissions.RxPermissions
import com.youniversals.playupgo.PlayUpApplication
import com.youniversals.playupgo.R
import com.youniversals.playupgo.data.Sport
import com.youniversals.playupgo.flux.BaseActivity
import com.youniversals.playupgo.flux.action.MatchActionCreator
import com.youniversals.playupgo.flux.action.UserActionCreator
import com.youniversals.playupgo.flux.store.MatchStore
import com.youniversals.playupgo.newmatch.AddNewMatchActivity
import com.youniversals.playupgo.newmatch.step.PickSportStepFragment
import com.youniversals.playupgo.notifications.NotificationActivity
import com.youniversals.playupgo.profile.ProfileActivity
import hotchemi.android.rate.AppRate
import kotlinx.android.synthetic.main.activity_main.*
import org.adw.library.widgets.discreteseekbar.DiscreteSeekBar
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subjects.PublishSubject
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class MainActivity : BaseActivity(), OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, PickSportStepFragment.SportPickerListener {
override fun onConnectionFailed(p0: ConnectionResult) {
}
@Inject lateinit var userActionCreator: UserActionCreator
@Inject lateinit var matchActionCreator: MatchActionCreator
@Inject lateinit var matchStore: MatchStore
lateinit var preferredSportImage: String
var preferredSportId: Long = 1
// @Inject lateinit var googleMapsApi: GoogleApi
private var matchPickerBottomSheetDialog: MatchPickerBottomSheetDialogFragment? = null
private var mMap: GoogleMap? = null
companion object {
fun startActivity(context: Context) {
val intent: Intent = Intent(context, MainActivity::class.java)
context.startActivity(intent)
}
}
private var mGoogleApiClient: GoogleApiClient? = null
private val PLACE_PICKER_REQUEST: Int = 1000
private val REQUEST_SPORT: Int = 2000
private lateinit var bottomSheetBehavior: BottomSheetBehavior<RelativeLayout>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
PlayUpApplication.fluxComponent.inject(this)
setContentView(R.layout.activity_main)
preferredSportImage = Prefs.getString("preferredSport.image", "https://maxcdn.icons8.com/Color/PNG/512/Sports/basketball-512.png")
preferredSportId = Prefs.getLong("preferredSport.id", 1L)
Glide.with(this).load(preferredSportImage).fitCenter().into(sportFilter)
AppRate.with(this)
.setInstallDays(0) // default 10, 0 means install day.
.setLaunchTimes(3) // default 10
.setRemindInterval(1) // default 1
.setShowLaterButton(true) // default true
.setDebug(false) // default false
.monitor()
// Show a dialog if meets conditions
AppRate.showRateDialogIfMeetsConditions(this)
bottomSheetBehavior = BottomSheetBehavior.from(llBottomSheet)
// change the state of the bottom sheet
bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN
initFlux()
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mGoogleApiClient = GoogleApiClient.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build()
mapFragment.getMapAsync(this)
rippleBackground.visibility = GONE
locationMarkerText.setOnClickListener {
rippleBackground.visibility = VISIBLE
locationMarkerText.visibility = INVISIBLE
rippleBackground.startRippleAnimation()
mMap?.uiSettings?.setAllGesturesEnabled(false)
rippleBackground.postDelayed({
val latLng = "${mMap?.cameraPosition?.target?.latitude},${mMap?.cameraPosition?.target?.longitude}"
val bundle = Bundle()
bundle.putString("coordinates", latLng)
bundle.putString("address", locationAddressTextView.text?.toString())
FirebaseAnalytics.getInstance(this).logEvent("search_nearby", bundle)
matchActionCreator.getNearbyMatches(latLng, radiusSeekBar?.progress!!, preferredSportId)
}, 3000)
}
locationAddressCard.setOnClickListener {
val builder = PlacePicker.IntentBuilder().setLatLngBounds(LatLngBounds(LatLng(14.424057,120.848934), LatLng(14.7782442,121.1636333)))
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST)
}
sportFilter.setOnClickListener {
val dialogFragment = PickSportStepFragment()
// dialogFragment.setTargetFragment(PickSportStepFragment(), REQUEST_SPORT)
dialogFragment.show(supportFragmentManager, "PickSportStepFragment")
}
locationMarker.setOnClickListener { onMapReady(mMap!!) }
radiusSeekBar.setOnProgressChangeListener(object : DiscreteSeekBar.OnProgressChangeListener {
override fun onProgressChanged(seekBar: DiscreteSeekBar?, value: Int, fromUser: Boolean) {
}
override fun onStartTrackingTouch(seekBar: DiscreteSeekBar?) {
}
override fun onStopTrackingTouch(seekBar: DiscreteSeekBar?) {
radiusTextView.text = ("Search game(s) within: ${seekBar?.progress}km")
}
})
bottomNavigationView.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.action_new_match -> {
AddNewMatchActivity.startActivity(this)
}
R.id.action_notifications -> {
NotificationActivity.startActivity(this)
}
R.id.action_profile -> {
ProfileActivity.startActivity(this, Prefs.getLong("externalId", -1).toString())
}
R.id.action_more -> {
bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
// bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
}
else -> {
}
}
return@setOnNavigationItemSelectedListener true
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle item selection
when (item.itemId) {
R.id.action_notifications -> {
NotificationActivity.startActivity(this)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun initFlux() {
matchStore.observable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
mMap?.uiSettings?.setAllGesturesEnabled(true)
rippleBackground.stopRippleAnimation()
rippleBackground.visibility = GONE
locationMarkerText.visibility = VISIBLE
if (it.error != null) return@subscribe
when (it.action) {
MatchActionCreator.ACTION_GET_NEARBY_MATCHES_S -> {
matchPickerBottomSheetDialog = MatchPickerBottomSheetDialogFragment.newInstance()
matchPickerBottomSheetDialog?.show(supportFragmentManager, MatchPickerBottomSheetDialogFragment::class.java.simpleName)
}
}
}, {
mMap?.uiSettings?.setAllGesturesEnabled(true)
rippleBackground.stopRippleAnimation()
rippleBackground.visibility = GONE
locationMarkerText.visibility = VISIBLE
})
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
if (isFinishing || isDestroyed) return
addSubscriptionToUnsubscribe(
RxPermissions(this).request(Manifest.permission.ACCESS_FINE_LOCATION)
.subscribe ({
if (it) { // Always true pre-M
val result = Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient, null)
result.setResultCallback { likelyPlaces ->
var lastLikelyhood = 0
var mostLikelyPlace = ""
var mostLikelyCoordinate: LatLng = LatLng(14.6091, 121.0223)
Observable.from(likelyPlaces)
for (placeLikelihood in likelyPlaces) {
Log.i("MainActivity", String.format("Place '%s' has likelihood: %g",
placeLikelihood.place.name,
placeLikelihood.likelihood))
if (placeLikelihood.likelihood >= lastLikelyhood) {
mostLikelyPlace = placeLikelihood.place.name.toString()
mostLikelyCoordinate = placeLikelihood.place.latLng
}
}
locationAddressTextView.text = mostLikelyPlace
mMap?.setOnCameraIdleListener {}
mMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(mostLikelyCoordinate, 16f))
setUpMapCameraIdleListener()
likelyPlaces.release()
}
} else {
// Oups permission denied
// Add a marker in Sydney and move the camera
val metroManila = LatLng(14.6091, 121.0223)
mMap?.setOnCameraIdleListener {}
mMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(metroManila, 14f))
setUpMapCameraIdleListener()
}
})
)
userActionCreator.preload()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
val place = PlacePicker.getPlace(this, data)
locationAddressTextView.text = place.name
mMap?.setOnCameraIdleListener {}
mMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(place.latLng, 16f))
setUpMapCameraIdleListener()
}
}
}
private fun setUpMapCameraIdleListener() {
val geocoder = Geocoder(this, Locale.getDefault())
val targetObservable : PublishSubject<LatLng> = PublishSubject.create()
targetObservable
.debounce(100, TimeUnit.MILLISECONDS)
.map { geocoder.getFromLocation(it.latitude, it.longitude, 1) }
.subscribeOn(Schedulers.io())
.filter { it != null }
.filter { it.size > 0 }
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
val addressLine = if (it[0].maxAddressLineIndex > 0) it[0].getAddressLine(0) + ", " else ""
val city = if (TextUtils.isEmpty(it[0].locality)) "" else it[0].locality + ", "
val state = if (TextUtils.isEmpty(it[0].adminArea)) "" else it[0].adminArea + ", "
val country = if (TextUtils.isEmpty(it[0].countryName)) "" else it[0].countryName
locationAddressTextView.text = "$addressLine$city$state$country"
}, {})
mMap?.setOnCameraMoveListener {
val target: LatLng? = mMap?.cameraPosition?.target
if (target != null) {
targetObservable.onNext(target)
}
}
}
override fun onSportPicked(sport: Sport) {
Prefs.putString("preferredSport.image", sport.icon)
Prefs.getLong("preferredSport.id", sport.id)
preferredSportImage = sport.icon
preferredSportId = sport.id
Glide.with(this).load(sport.icon).fitCenter().into(sportFilter)
}
override fun onBackPressed() {
if (bottomSheetBehavior.state == BottomSheetBehavior.STATE_COLLAPSED) {
bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN
return
}
super.onBackPressed()
}
}
| agpl-3.0 | d8c63ec1d82a3ecf4af1fb23f077df0e | 44.546012 | 147 | 0.624731 | 5.387518 | false | false | false | false |
uber/RIBs | android/libraries/rib-android/src/main/kotlin/com/uber/rib/core/lifecycle/ActivityLifecycleEvent.kt | 1 | 2632 | /*
* Copyright (C) 2017. Uber Technologies
*
* 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.uber.rib.core.lifecycle
import android.os.Bundle
/** Lifecycle events that can be emitted by Activities. */
open class ActivityLifecycleEvent private constructor(
/** @return this event's type. */
override val type: Type
) : ActivityEvent {
/** Types of activity events that can occur. */
enum class Type : ActivityEvent.BaseType {
CREATE, START, RESUME, USER_LEAVING, PAUSE, STOP, DESTROY
}
/** An [ActivityLifecycleEvent] that encapsulates information from [Activity.onCreate]. */
open class Create(
/** @return this event's savedInstanceState data. */
open val savedInstanceState: Bundle?
) : ActivityLifecycleEvent(Type.CREATE)
companion object {
private val START_EVENT = ActivityLifecycleEvent(Type.START)
private val RESUME_EVENT = ActivityLifecycleEvent(Type.RESUME)
private val USER_LEAVING_EVENT = ActivityLifecycleEvent(Type.USER_LEAVING)
private val PAUSE_EVENT = ActivityLifecycleEvent(Type.PAUSE)
private val STOP_EVENT = ActivityLifecycleEvent(Type.STOP)
private val DESTROY_EVENT = ActivityLifecycleEvent(Type.DESTROY)
/**
* Creates an event for onCreate.
*
* @param stateData the instate bundle.
* @return the created ActivityEvent.
*/
@JvmStatic
fun createOnCreateEvent(stateData: Bundle?): Create {
return Create(stateData)
}
/**
* Creates an activity event for a given type.
*
* @param type The type of event to get.
* @return The corresponding ActivityEvent.
*/
@JvmStatic
fun create(type: Type): ActivityLifecycleEvent {
return when (type) {
Type.START -> START_EVENT
Type.RESUME -> RESUME_EVENT
Type.USER_LEAVING -> USER_LEAVING_EVENT
Type.PAUSE -> PAUSE_EVENT
Type.STOP -> STOP_EVENT
Type.DESTROY -> DESTROY_EVENT
else -> throw IllegalArgumentException(
"Use the createOn${type.name.toLowerCase().capitalize()}Event() method for this type!"
)
}
}
}
}
| apache-2.0 | 7f77b73ebf974fb22569f6c8f33ae266 | 33.181818 | 96 | 0.691869 | 4.343234 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.