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
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/discord/webhook/WebhookSendSimpleExecutor.kt
1
4596
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord.webhook import dev.kord.common.entity.optional.Optional import dev.kord.common.entity.optional.optional import dev.kord.rest.json.request.EmbedImageRequest import dev.kord.rest.json.request.EmbedRequest import dev.kord.rest.json.request.EmbedThumbnailRequest import dev.kord.rest.json.request.WebhookExecuteRequest import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.loritta.common.utils.Color import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.discord.declarations.WebhookCommand import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions import net.perfectdreams.loritta.cinnamon.discord.utils.toKordColor class WebhookSendSimpleExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) { inner class Options : LocalizedApplicationCommandOptions(loritta) { val webhookUrl = string("webhook_url", WebhookCommand.I18N_PREFIX.Options.WebhookUrl.Text) val message = string("message", WebhookCommand.I18N_PREFIX.Options.Message.Text) val username = optionalString("username", WebhookCommand.I18N_PREFIX.Options.Username.Text) val avatarUrl = optionalString("avatar_url", WebhookCommand.I18N_PREFIX.Options.AvatarUrl.Text) val embedTitle = optionalString("embed_title", WebhookCommand.I18N_PREFIX.Options.EmbedTitle.Text) val embedDescription = optionalString("embed_description", WebhookCommand.I18N_PREFIX.Options.EmbedDescription.Text) val embedImageUrl = optionalString("embed_image_url", WebhookCommand.I18N_PREFIX.Options.EmbedImageUrl.Text) val embedThumbnailUrl = optionalString("embed_thumbnail_url", WebhookCommand.I18N_PREFIX.Options.EmbedThumbnailUrl.Text) val embedColor = optionalString("embed_color", WebhookCommand.I18N_PREFIX.Options.EmbedThumbnailUrl.Text) } override val options = Options() override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { context.deferChannelMessageEphemerally() // Defer the message ephemerally because we don't want users looking at the webhook URL val webhookUrl = args[options.webhookUrl] val message = args[options.message] val username = args[options.username] val avatarUrl = args[options.avatarUrl] // Embed Stuff val embedTitle = args[options.embedTitle] val embedDescription = args[options.embedDescription] val embedImageUrl = args[options.embedImageUrl] val embedThumbnailUrl = args[options.embedThumbnailUrl] val embedColor = args[options.embedColor] WebhookCommandUtils.sendMessageViaWebhook(context, webhookUrl) { val embed = if (embedTitle != null || embedDescription != null || embedImageUrl != null || embedThumbnailUrl != null) { EmbedRequest( title = embedTitle?.optional() ?: Optional(), description = embedDescription?.optional() ?: Optional(), image = embedImageUrl?.let { EmbedImageRequest(it) }?.optional() ?: Optional(), thumbnail = embedThumbnailUrl?.let { EmbedThumbnailRequest(it) }?.optional() ?: Optional(), color = embedColor?.let { try { Color.fromString(it) } catch (e: IllegalArgumentException) { context.failEphemerally(context.i18nContext.get(WebhookCommand.I18N_PREFIX.InvalidEmbedColor)) } }?.toKordColor()?.optional() ?: Optional() ) } else null WebhookExecuteRequest( content = message .replace( "\\n", "\n" ) // TODO: When Discord supports multi line options, then we don't need this anymore :D .optional(), username = username?.optional() ?: Optional(), avatar = avatarUrl?.optional() ?: Optional(), embeds = if (embed != null) listOf(embed).optional() else Optional() ) } } }
agpl-3.0
3b8a938a444479237264a951bcb5a727
52.453488
136
0.690601
4.968649
false
false
false
false
peterholak/mogul
native/src/mogul/platform/native/Window.kt
1
2774
package mogul.platform.native import kotlinx.cinterop.* import pangocairo.* import sdl.* import mogul.microdom.* import mogul.platform.* import mogul.platform.Cairo import mogul.platform.Window as WindowInterface class Window( title: String, val userEvents: UserEvents, val width: Int, val height: Int, val background: Color = Color.black, val autoClose: AutoClose = AutoClose.Close ) : WindowInterface { val window = SDL_CreateWindow( title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN ) ?: throw Exception("Failed to create window") internal val id: Long = SDL_GetWindowID(window).toLong() val renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED or SDL_RENDERER_PRESENTVSYNC ) ?: throw Exception("Failed to initialize renderer") val texture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TextureAccess.SDL_TEXTUREACCESS_STREAMING.value, width, height ) ?: throw Exception("Failed to create texture") private var invalidated = false override fun wasInvalidated() = invalidated override fun draw(code: (cairo: Cairo) -> Unit) { memScoped { val pixels = alloc<COpaquePointerVar>() val pitch = alloc<IntVar>() SDL_LockTexture(texture, null, pixels.ptr, pitch.ptr) val surface = cairo_image_surface_create_for_data( pixels.value!!.reinterpret<ByteVar>(), CAIRO_FORMAT_ARGB32, width, height, pitch.value ) val cairoT = cairo_create(surface) ?: throw Exception("Failed to initialize cairo") val cairo = Cairo(cairoT) cairo.setSourceRgb(background) cairo.setAntialias(Antialias.None) cairo_paint(cairoT) code(cairo) SDL_UnlockTexture(texture) invalidate() } } override fun invalidate() { invalidated = true userEvents.pushInvalidatedEvent(this) } override fun render() { SDL_RenderClear(renderer) SDL_RenderCopy(renderer, texture, null, null) SDL_RenderPresent(renderer) invalidated = false } override fun getPosition(): Position { var result: Position? = null memScoped { val xPtr = alloc<IntVar>() val yPtr = alloc<IntVar>() SDL_GetWindowPosition(window, xPtr.ptr, yPtr.ptr) result = Position(xPtr.value, yPtr.value) } return result!! } }
mit
0f7e2a45c517cf1da4c7d62a9e9127bb
28.827957
95
0.58796
4.577558
false
false
false
false
trevjonez/Kontrast
plugin/src/main/kotlin/com/trevjonez/kontrast/internal/RxExtensions.kt
1
7948
/* * Copyright 2017 Trevor Jones * * 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. */ @file:Suppress("NOTHING_TO_INLINE") package com.trevjonez.kontrast.internal import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import okio.BufferedSource import okio.Okio.buffer import okio.Okio.source import org.slf4j.Logger import java.io.BufferedWriter import java.net.Socket import kotlin.reflect.KClass typealias StdOut = okio.BufferedSource typealias StdErr = okio.BufferedSource internal fun <T> Completable.andThenEmit(value: T) = andThenObserve { Observable.just(value) } internal inline fun <T> Completable.andThenObserve(crossinline func: () -> Observable<T>): Observable<T> = andThen(Observable.unsafeCreate { func().subscribe(it::onNext, it::onError, it::onComplete) }) fun Socket.toObservable(input: Observable<String>, logger: Logger): Observable<String> { return Observable.create { emitter -> try { val disposable = CompositeDisposable() emitter.setDisposable(disposable) val out = getOutputStream().bufferedWriter() input.observeOn(Schedulers.io()) .subscribe({ out.writeAndFlush(it) }, { error -> logger.info("Socket sending threw. Attempting onError", error) if (!emitter.isDisposed) emitter.onError(error) }) addTo disposable buffer(source(getInputStream())) .readLines() .subscribeOn(Schedulers.io()) .subscribe({ emitter.onNext(it) }, { error -> logger.info("Socket reading threw. Attempting onError", error) if (!emitter.isDisposed) emitter.onError(error) }) addTo disposable object : Disposable { override fun isDisposed(): Boolean { return isClosed } override fun dispose() { logger.info("Disposing socket observable") close() } } addTo disposable } catch (error: Throwable) { logger.info("Socket setup threw. Attempting onError", error) if (!emitter.isDisposed) emitter.onError(error) } } } private fun BufferedWriter.writeAndFlush(value: String) { write(value) newLine() flush() } inline infix fun Disposable.addTo(compositeDisposable: CompositeDisposable) = apply { compositeDisposable.add(this) } fun BufferedSource.readLines(): Observable<String> { return Observable.create { emitter -> try { emitter.setDisposable(object : Disposable { override fun isDisposed(): Boolean { return false } override fun dispose() { close() } }) var next = readUtf8Line() while (next != null) { if (!emitter.isDisposed) emitter.onNext(next) next = readUtf8Line() } if (!emitter.isDisposed) emitter.onComplete() } catch (error: Throwable) { if (error is IllegalStateException && error.message?.contains("closed") == true) { if (!emitter.isDisposed) emitter.onComplete() } else if (!emitter.isDisposed) emitter.onError(error) } } } inline fun <T> Observable<T>.doOnFirst(crossinline action: (T) -> Unit): Observable<T> { var first = true return doOnNext { if (first) { first = false action(it) } } } fun ProcessBuilder.toObservable(name: String, logger: Logger, stdIn: Observable<String>): Observable<Pair<StdOut, StdErr>> { return Observable.create<Pair<StdOut, StdErr>> { emitter -> try { logger.info("Starting process: ${command().joinToString(separator = " ")}") val process = start() val inWriter = process.outputStream.bufferedWriter() val disposable = CompositeDisposable() emitter.setDisposable(disposable) val stdOut = buffer(source(process.inputStream)) val stdErr = buffer(source(process.errorStream)) stdIn.observeOn(Schedulers.io()) .subscribe { inWriter.write(it) inWriter.newLine() inWriter.flush() } addTo disposable object : Disposable { var disposed = false override fun isDisposed(): Boolean { return disposed } override fun dispose() { logger.info("Disposing: ${command().joinToString(separator = " ")}") disposed = true inWriter.close() } } addTo disposable if (!emitter.isDisposed) { emitter.onNext(stdOut to stdErr) } val result = process.waitFor() if (!emitter.isDisposed) { if (result == 0) emitter.onComplete() else emitter.onError(RuntimeException("$name exited with code $result")) } } catch (error: Throwable) { if (!emitter.isDisposed) { emitter.onError(error) } } } } fun ProcessBuilder.toCompletable(name: String, logger: Logger): Completable { return Completable.create { emitter -> try { logger.info("Starting process: ${command().joinToString(separator = " ")}") val process = start() val disposable = CompositeDisposable() emitter.setDisposable(disposable) val stdOut = buffer(source(process.inputStream)) stdOut.readLines() .subscribeOn(Schedulers.io()) .subscribe { logger.info("stdOut: $it") } addTo disposable val stdErr = buffer(source(process.errorStream)) stdErr.readLines() .subscribeOn(Schedulers.io()) .subscribe { logger.info("stdErr: $it") } addTo disposable object : Disposable { var disposed = false override fun isDisposed() = disposed override fun dispose() { logger.info("Disposing: ${command().joinToString(separator = " ")}") disposed = true } } addTo disposable val result = process.waitFor() if (!emitter.isDisposed) { when (result) { 0 -> emitter.onComplete() else -> emitter.onError(RuntimeException("$name exited with code $result")) } } } catch (error: Throwable) { if (!emitter.isDisposed) { emitter.onError(error) } } } } inline fun <reified T: Any> Observable<T>.never(): Observable<T> { return never(T::class) } fun <T, R: Any> Observable<T>.never(rType: KClass<R>): Observable<R> { return filter { false }.cast(rType.java) }
apache-2.0
acc2a1636aba1633d8f7efaca371238c
34.013216
124
0.563915
5.088348
false
false
false
false
cypressious/learning-spaces
app/src/main/java/de/maxvogler/learningspaces/adapters/LocationListAdapter.kt
2
1615
package de.maxvogler.learningspaces.adapters import android.content.Context import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import de.maxvogler.learningspaces.R import de.maxvogler.learningspaces.helpers.layoutInflater import de.maxvogler.learningspaces.models.Location import de.maxvogler.learningspaces.models.Weekday import org.jetbrains.anko.find public class LocationListAdapter(context: Context, locations: List<Location>) : ArrayAdapter<Location>(context, LocationListAdapter.layout, locations) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = convertView ?: context.layoutInflater.inflate(layout, parent, false) val freeSeats = view.find<TextView>(R.id.seats_free) val occupiedSeats = view.find<TextView>(R.id.seats_occupied) val openingHours = view.find<TextView>(R.id.time) val location = getItem(position) view.find<TextView>(R.id.name).text = location.name!! freeSeats.text = location.freeSeats.toString() occupiedSeats.text = location.occupiedSeats.toString() freeSeats.visibility = if (location.openingHours.isOpen()) VISIBLE else GONE occupiedSeats.visibility = if (location.openingHours.isOpen()) VISIBLE else GONE openingHours.text = location.openingHours.getHoursForDayString(Weekday.today()) return view } companion object { private val layout = R.layout.view_location_list_item } }
gpl-2.0
068c2500c86a4cc0c696526d7bd65b32
36.55814
88
0.752322
4.261214
false
false
false
false
mp911de/lettuce
src/main/kotlin/io/lettuce/core/api/coroutines/RedisStringCoroutinesCommandsImpl.kt
1
4885
/* * Copyright 2020-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.lettuce.core.api.coroutines import io.lettuce.core.* import io.lettuce.core.api.reactive.RedisStringReactiveCommands import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitFirstOrNull /** * Coroutine executed commands (based on reactive commands) for Strings. * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 */ @ExperimentalLettuceCoroutinesApi internal class RedisStringCoroutinesCommandsImpl<K : Any, V : Any>(private val ops: RedisStringReactiveCommands<K, V>) : RedisStringCoroutinesCommands<K, V> { override suspend fun append(key: K, value: V): Long? = ops.append(key, value).awaitFirstOrNull() override suspend fun bitcount(key: K): Long? = ops.bitcount(key).awaitFirstOrNull() override suspend fun bitcount(key: K, start: Long, end: Long): Long? = ops.bitcount(key, start, end).awaitFirstOrNull() override suspend fun bitfield(key: K, bitFieldArgs: BitFieldArgs): List<Long> = ops.bitfield(key, bitFieldArgs).map { it.value }.asFlow().toList() override suspend fun bitpos(key: K, state: Boolean): Long? = ops.bitpos(key, state).awaitFirstOrNull() override suspend fun bitpos(key: K, state: Boolean, start: Long): Long? = ops.bitpos(key, state, start).awaitFirstOrNull() override suspend fun bitpos(key: K, state: Boolean, start: Long, end: Long): Long? = ops.bitpos(key, state, start, end).awaitFirstOrNull() override suspend fun bitopAnd(destination: K, vararg keys: K): Long? = ops.bitopAnd(destination, *keys).awaitFirstOrNull() override suspend fun bitopNot(destination: K, source: K): Long? = ops.bitopNot(destination, source).awaitFirstOrNull() override suspend fun bitopOr(destination: K, vararg keys: K): Long? = ops.bitopOr(destination, *keys).awaitFirstOrNull() override suspend fun bitopXor(destination: K, vararg keys: K): Long? = ops.bitopXor(destination, *keys).awaitFirstOrNull() override suspend fun decr(key: K): Long? = ops.decr(key).awaitFirstOrNull() override suspend fun decrby(key: K, amount: Long): Long? = ops.decrby(key, amount).awaitFirstOrNull() override suspend fun get(key: K): V? = ops.get(key).awaitFirstOrNull() override suspend fun getbit(key: K, offset: Long): Long? = ops.getbit(key, offset).awaitFirstOrNull() override suspend fun getrange(key: K, start: Long, end: Long): V? = ops.getrange(key, start, end).awaitFirstOrNull() override suspend fun getset(key: K, value: V): V? = ops.getset(key, value).awaitFirstOrNull() override suspend fun incr(key: K): Long? = ops.incr(key).awaitFirstOrNull() override suspend fun incrby(key: K, amount: Long): Long? = ops.incrby(key, amount).awaitFirstOrNull() override suspend fun incrbyfloat(key: K, amount: Double): Double? = ops.incrbyfloat(key, amount).awaitFirstOrNull() override fun mget(vararg keys: K): Flow<KeyValue<K, V>> = ops.mget(*keys).asFlow() override suspend fun mset(map: Map<K, V>): String? = ops.mset(map).awaitFirstOrNull() override suspend fun msetnx(map: Map<K, V>): Boolean? = ops.msetnx(map).awaitFirstOrNull() override suspend fun set(key: K, value: V): String? = ops.set(key, value).awaitFirstOrNull() override suspend fun set(key: K, value: V, setArgs: SetArgs): String? = ops.set(key, value, setArgs).awaitFirstOrNull() override suspend fun setbit(key: K, offset: Long, value: Int): Long? = ops.setbit(key, offset, value).awaitFirstOrNull() override suspend fun setex(key: K, seconds: Long, value: V): String? = ops.setex(key, seconds, value).awaitFirstOrNull() override suspend fun psetex(key: K, milliseconds: Long, value: V): String? = ops.psetex(key, milliseconds, value).awaitFirstOrNull() override suspend fun setnx(key: K, value: V): Boolean? = ops.setnx(key, value).awaitFirstOrNull() override suspend fun setrange(key: K, offset: Long, value: V): Long? = ops.setrange(key, offset, value).awaitFirstOrNull() override suspend fun stralgoLcs(strAlgoArgs: StrAlgoArgs): StringMatchResult? = ops.stralgoLcs(strAlgoArgs).awaitFirstOrNull() override suspend fun strlen(key: K): Long? = ops.strlen(key).awaitFirstOrNull() }
apache-2.0
78918127793f0cba9c4175c82f5c6733
46.427184
158
0.726919
3.783888
false
false
false
false
albertoruibal/karballo
karballo-jvm/src/test/kotlin/karballo/SearchEngineMinimumTimeTest.kt
1
1527
package karballo import karballo.search.* import org.junit.Before import org.junit.Test class SearchEngineMinimumTimeTest { lateinit var config: Config lateinit var searchEngine: SearchEngine var endTime: Long = 0 @Before @Throws(Exception::class) fun setUp() { config = Config() searchEngine = SearchEngineThreaded(config) } @Test fun testMinimumTime() { searchEngine.board.fen = "rq2r1k1/5pp1/p7/4bNP1/1p2P2P/5Q2/PP4K1/5R1R w - -" searchEngine.go(SearchParameters[500]) try { Thread.sleep(1000) } catch (e: InterruptedException) { e.printStackTrace() } searchEngine.board.doMove(searchEngine.bestMove) searchEngine.setObserver(object : SearchObserver { override fun info(info: SearchStatusInfo) { println("info " + info.toString()) } override fun bestMove(bestMove: Int, ponder: Int) { println("bestMove " + Move.toString(bestMove)) endTime = System.nanoTime() } }) val time1m = System.currentTimeMillis() val time1 = System.nanoTime() searchEngine.go(SearchParameters[1]) try { Thread.sleep(100) } catch (e: InterruptedException) { e.printStackTrace() } println("Time startTime = " + (searchEngine.startTime - time1m) + " mS") println("Time elapsed = " + (endTime - time1) + " nS") } }
mit
849808d735a9e87de6ede279df30c50e
26.763636
84
0.588081
4.172131
false
true
false
false
albertoruibal/karballo
karballo-common/src/main/kotlin/karballo/bitboard/BitboardAttacks.kt
1
8875
package karballo.bitboard import karballo.Board import karballo.Color import karballo.log.Logger import karballo.util.Utils /** * Discover attacks to squares */ open class BitboardAttacks internal constructor() { var rook: LongArray var bishop: LongArray var knight: LongArray var king: LongArray var pawn: Array<LongArray> internal fun squareAttackedAux(square: Long, shift: Int, border: Long): Long { var s = square if (s and border == 0L) { if (shift > 0) { s = s shl shift } else { s = s ushr (-shift) } return s } return 0 } internal fun squareAttackedAuxSlider(square: Long, shift: Int, border: Long): Long { var s = square var ret: Long = 0 while (s and border == 0L) { if (shift > 0) { s = s shl shift } else { s = s ushr (-shift) } ret = ret or s } return ret } init { logger.debug("Generating attack tables...") val time1 = Utils.instance.currentTimeMillis() rook = LongArray(64) bishop = LongArray(64) knight = LongArray(64) king = LongArray(64) pawn = Array(2) { LongArray(64) } var square: Long = 1 var i = 0 while (square != 0L) { rook[i] = squareAttackedAuxSlider(square, +8, BitboardUtils.b_u) or squareAttackedAuxSlider(square, -8, BitboardUtils.b_d) or squareAttackedAuxSlider(square, -1, BitboardUtils.b_r) or squareAttackedAuxSlider(square, +1, BitboardUtils.b_l) bishop[i] = squareAttackedAuxSlider(square, +9, BitboardUtils.b_u or BitboardUtils.b_l) or squareAttackedAuxSlider(square, +7, BitboardUtils.b_u or BitboardUtils.b_r) or squareAttackedAuxSlider(square, -7, BitboardUtils.b_d or BitboardUtils.b_l) or squareAttackedAuxSlider(square, -9, BitboardUtils.b_d or BitboardUtils.b_r) knight[i] = squareAttackedAux(square, +17, BitboardUtils.b2_u or BitboardUtils.b_l) or squareAttackedAux(square, +15, BitboardUtils.b2_u or BitboardUtils.b_r) or squareAttackedAux(square, -15, BitboardUtils.b2_d or BitboardUtils.b_l) or squareAttackedAux(square, -17, BitboardUtils.b2_d or BitboardUtils.b_r) or squareAttackedAux(square, +10, BitboardUtils.b_u or BitboardUtils.b2_l) or squareAttackedAux(square, +6, BitboardUtils.b_u or BitboardUtils.b2_r) or squareAttackedAux(square, -6, BitboardUtils.b_d or BitboardUtils.b2_l) or squareAttackedAux(square, -10, BitboardUtils.b_d or BitboardUtils.b2_r) pawn[Color.W][i] = squareAttackedAux(square, 7, BitboardUtils.b_u or BitboardUtils.b_r) or squareAttackedAux(square, 9, BitboardUtils.b_u or BitboardUtils.b_l) pawn[Color.B][i] = squareAttackedAux(square, -7, BitboardUtils.b_d or BitboardUtils.b_l) or squareAttackedAux(square, -9, BitboardUtils.b_d or BitboardUtils.b_r) king[i] = squareAttackedAux(square, +8, BitboardUtils.b_u) or squareAttackedAux(square, -8, BitboardUtils.b_d) or squareAttackedAux(square, -1, BitboardUtils.b_r) or squareAttackedAux(square, +1, BitboardUtils.b_l) or squareAttackedAux(square, +9, BitboardUtils.b_u or BitboardUtils.b_l) or squareAttackedAux(square, +7, BitboardUtils.b_u or BitboardUtils.b_r) or squareAttackedAux(square, -7, BitboardUtils.b_d or BitboardUtils.b_l) or squareAttackedAux(square, -9, BitboardUtils.b_d or BitboardUtils.b_r) square = square shl 1 i++ } val time2 = Utils.instance.currentTimeMillis() logger.debug("Generated attack tables in " + (time2 - time1) + "ms") } /** * Discover attacks to squares using magics: expensive version */ fun isSquareAttacked(board: Board, square: Long, white: Boolean): Boolean { return isIndexAttacked(board, BitboardUtils.square2Index(square), white) } fun areSquaresAttacked(board: Board, squares: Long, white: Boolean): Boolean { var s = squares while (s != 0L) { val square = BitboardUtils.lsb(s) val attacked = isIndexAttacked(board, BitboardUtils.square2Index(square), white) if (attacked) { return true } s = s xor square } return false } /** * Discover attacks to squares using magics: cheap version */ fun isIndexAttacked(board: Board, index: Int, white: Boolean): Boolean { if (index < 0 || index > 63) { return false } val others = if (white) board.blacks else board.whites val all = board.all if (pawn[if (white) Color.W else Color.B][index] and board.pawns and others != 0L) { return true } else if (king[index] and board.kings and others != 0L) { return true } else if (knight[index] and board.knights and others != 0L) { return true } else if (getRookAttacks(index, all) and (board.rooks or board.queens) and others != 0L) { return true } else if (getBishopAttacks(index, all) and (board.bishops or board.queens) and others != 0L) { return true } return false } /** * Discover attacks to squares using magics: cheap version */ fun getIndexAttacks(board: Board, index: Int): Long { if (index < 0 || index > 63) { return 0 } val all = board.all return board.blacks and pawn[Color.W][index] or (board.whites and pawn[Color.B][index]) and board.pawns or (king[index] and board.kings) or (knight[index] and board.knights) or (getRookAttacks(index, all) and (board.rooks or board.queens)) or (getBishopAttacks(index, all) and (board.bishops or board.queens)) } fun getXrayAttacks(board: Board, index: Int, all: Long): Long { if (index < 0 || index > 63) { return 0 } return getRookAttacks(index, all) and (board.rooks or board.queens) or (getBishopAttacks(index, all) and (board.bishops or board.queens)) and all } /** * without magic bitboards, too expensive, but uses less memory */ open fun getRookAttacks(index: Int, all: Long): Long { return getRookShiftAttacks(BitboardUtils.index2Square(index), all) } open fun getBishopAttacks(index: Int, all: Long): Long { return getBishopShiftAttacks(BitboardUtils.index2Square(index), all) } fun getRookShiftAttacks(square: Long, all: Long): Long { return checkSquareAttackedAux(square, all, +8, BitboardUtils.b_u) or checkSquareAttackedAux(square, all, -8, BitboardUtils.b_d) or checkSquareAttackedAux(square, all, -1, BitboardUtils.b_r) or checkSquareAttackedAux(square, all, +1, BitboardUtils.b_l) } fun getBishopShiftAttacks(square: Long, all: Long): Long { return checkSquareAttackedAux(square, all, +9, BitboardUtils.b_u or BitboardUtils.b_l) or checkSquareAttackedAux(square, all, +7, BitboardUtils.b_u or BitboardUtils.b_r) or checkSquareAttackedAux(square, all, -7, BitboardUtils.b_d or BitboardUtils.b_l) or checkSquareAttackedAux(square, all, -9, BitboardUtils.b_d or BitboardUtils.b_r) } /** * Attacks for sliding pieces */ private fun checkSquareAttackedAux(square: Long, all: Long, shift: Int, border: Long): Long { var s = square var ret: Long = 0 while (s and border == 0L) { if (shift > 0) { s = s shl shift } else { s = s ushr (-shift) } ret = ret or s // If we collide with other piece if (s and all != 0L) { break } } return ret } companion object { private val logger = Logger.getLogger("BitboardAttacks") /** * If disabled, does not use Magic Bitboards, improves loading speed in GWT * and avoids memory crashes in mobile browsers */ var USE_MAGIC = true internal var instance: BitboardAttacks? = null fun getInstance(): BitboardAttacks { if (instance == null) { if (USE_MAGIC) { instance = BitboardAttacksMagic() } else { instance = BitboardAttacks() } } return instance!! } } }
mit
86eb78c141fa1ad0502d9eec8d35e8e1
38.802691
343
0.589746
3.809013
false
false
false
false
icarumbas/bagel
core/src/ru/icarumbas/bagel/engine/systems/velocity/FlyingSystem.kt
1
3197
package ru.icarumbas.bagel.engine.systems.velocity import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.Family import com.badlogic.ashley.systems.IteratingSystem import com.badlogic.gdx.math.Vector2 import ru.icarumbas.bagel.engine.components.velocity.FlyComponent import ru.icarumbas.bagel.engine.world.RoomWorld import ru.icarumbas.bagel.utils.AI import ru.icarumbas.bagel.utils.body import ru.icarumbas.bagel.utils.fly import ru.icarumbas.bagel.utils.inView class FlyingSystem( private val playerEntity: Entity, private val rm: RoomWorld ) : IteratingSystem(Family.all(FlyComponent::class.java).get()) { private val velocity = Vector2() override fun processEntity(entity: Entity, deltaTime: Float) { if (entity.inView(rm)) { val distanceHor = Math.abs(body[playerEntity].body.position.x - body[entity].body.position.x) val distanceVert = Math.abs(body[playerEntity].body.position.y - body[entity].body.position.y) var k = distanceHor.div(distanceVert) var k2 = 1f if (distanceVert > distanceHor) { k2 = distanceVert.div(distanceHor) k = 1f } when { AI[entity].isTargetRight && AI[entity].isTargetHigher -> { velocity.set(fly[entity].speed.div(k2), fly[entity].speed.div(k)) if (fly[entity].lastRight) body[entity].body.setLinearVelocity(-.3f, 0f) if (fly[entity].lastUp) body[entity].body.setLinearVelocity(0f, -.3f) fly[entity].lastRight = false fly[entity].lastUp = false } !AI[entity].isTargetRight && !AI[entity].isTargetHigher -> { velocity.set(-fly[entity].speed.div(k2), -fly[entity].speed.div(k)) if (!fly[entity].lastRight) body[entity].body.setLinearVelocity(.3f, 0f) if (!fly[entity].lastUp) body[entity].body.setLinearVelocity(0f, .3f) fly[entity].lastRight = true fly[entity].lastUp = true } AI[entity].isTargetRight && !AI[entity].isTargetHigher -> { velocity.set(fly[entity].speed.div(k2), -fly[entity].speed.div(k)) if (fly[entity].lastRight) body[entity].body.setLinearVelocity(-.3f, 0f) if (!fly[entity].lastUp) body[entity].body.setLinearVelocity(0f, .3f) fly[entity].lastRight = false fly[entity].lastUp = true } !AI[entity].isTargetRight && AI[entity].isTargetHigher -> { velocity.set(-fly[entity].speed.div(k2), fly[entity].speed.div(k)) if (!fly[entity].lastRight) body[entity].body.setLinearVelocity(.3f, 0f) if (fly[entity].lastUp) body[entity].body.setLinearVelocity(0f, -.3f) fly[entity].lastRight = true fly[entity].lastUp = false } } body[entity].body.applyLinearImpulse(velocity, body[entity].body.localPoint2, true) } } }
apache-2.0
a9a8d4cc6726029dd59f1b9486d5563b
43.416667
106
0.590241
3.884569
false
false
false
false
pawegio/KAndroid
kandroid/src/main/kotlin/com/pawegio/kandroid/KActivity.kt
1
1651
/* * Copyright 2015-2016 Paweł Gajda * * 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. */ @file:Suppress("NOTHING_TO_INLINE") package com.pawegio.kandroid import android.app.Activity import android.content.pm.ActivityInfo import android.content.res.Configuration import android.os.Bundle import android.support.annotation.IdRes import android.view.View @Deprecated("Use findViewById() instead", ReplaceWith("findViewById()")) inline fun <reified T : View> Activity.find(@IdRes id: Int): T = findViewById(id) inline fun <reified T : Any> Activity.startActivityForResult(requestCode: Int, options: Bundle? = null, action: String? = null) = startActivityForResult(IntentFor<T>(this).setAction(action), requestCode, options) inline fun Activity.lockCurrentScreenOrientation() { requestedOrientation = when (resources.configuration.orientation) { Configuration.ORIENTATION_LANDSCAPE -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE else -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT } } inline fun Activity.unlockScreenOrientation() { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR }
apache-2.0
d51f416b9293af515a284b7357b70df0
37.395349
129
0.767273
4.296875
false
true
false
false
bachhuberdesign/deck-builder-gwent
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/cardviewer/CardDetailController.kt
1
2836
package com.bachhuberdesign.deckbuildergwent.features.cardviewer import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bachhuberdesign.deckbuildergwent.MainActivity import com.bachhuberdesign.deckbuildergwent.R import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card import com.bachhuberdesign.deckbuildergwent.inject.module.ActivityModule import com.bachhuberdesign.deckbuildergwent.util.inflate import com.bluelinelabs.conductor.Controller import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.controller_card_detail.view.* import javax.inject.Inject /** * @author Eric Bachhuber * @version 1.0.0 * @since 1.0.0 */ class CardDetailController : Controller, CardDetailMvpContract { constructor(cardId: Int) { this.cardId = cardId } constructor(args: Bundle) : super() companion object { @JvmStatic val TAG: String = CardDetailController::class.java.name } @Inject lateinit var presenter: CardDetailPresenter var cardId: Int = 0 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val view = container.inflate(R.layout.controller_card_detail) (activity as MainActivity).persistedComponent .activitySubcomponent(ActivityModule(activity!!)) .inject(this) view.card_image.transitionName = "imageTransition$cardId" view.card_name_text.transitionName = "nameTransition$cardId" return view } override fun onAttach(view: View) { super.onAttach(view) presenter.attach(this) presenter.loadCard(cardId) } override fun onDetach(view: View) { super.onDetach(view) presenter.detach() } override fun onSaveInstanceState(outState: Bundle) { // TODO: Save cardId here super.onSaveInstanceState(outState) } override fun onCardLoaded(card: Card) { activity?.title = card.name Glide.with(activity!!) .load(Uri.parse("file:///android_asset/cards/${card.iconUrl}")) .fitCenter() .dontAnimate() .into(view!!.card_image) view!!.card_name_text.text = card.name view!!.card_description_text.text = card.description view!!.card_flavor_text.text = card.flavorText view!!.card_group_text.text = card.cardType.toString() view!!.card_faction_text.text = card.faction.toString() view!!.card_rarity_text.text = card.rarity.toString() view!!.card_lane_text.text = card.lane.toString() view!!.card_craft_text.text = "${card.scrap} / ${card.scrapPremium}" view!!.card_mill_text.text = "${card.mill} / ${card.millPremium}" } }
apache-2.0
a7dfd6c2215effc95c9483acf37eca2c
30.522222
85
0.683709
4.316591
false
false
false
false
HendraAnggrian/kota
kota-gridlayout-v7/src/layouts/WidgetsV7Grid.kt
1
871
@file:Suppress("NOTHING_TO_INLINE", "UNUSED") package kota import android.app.Dialog import android.content.Context import android.support.v4.app.Fragment import android.support.v7.widget.GridLayout inline fun Context.supportGridLayout(init: (@KotaDsl _GridLayoutV7).() -> Unit): GridLayout = _GridLayoutV7(this).apply(init) inline fun android.app.Fragment.supportGridLayout(init: (@KotaDsl _GridLayoutV7).() -> Unit): GridLayout = _GridLayoutV7(activity).apply(init) inline fun Fragment.supportGridLayout(init: (@KotaDsl _GridLayoutV7).() -> Unit): GridLayout = _GridLayoutV7(context!!).apply(init) inline fun Dialog.supportGridLayout(init: (@KotaDsl _GridLayoutV7).() -> Unit): GridLayout = _GridLayoutV7(context).apply(init) inline fun ViewRoot.supportGridLayout(init: (@KotaDsl _GridLayoutV7).() -> Unit): GridLayout = _GridLayoutV7(getContext()).apply(init).add()
apache-2.0
e59cb0756fa401c5b92089a4a6004965
61.285714
142
0.769231
3.629167
false
false
false
false
google/ksp
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/TypeParameterReferenceProcessor.kt
1
2629
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.processor import com.google.devtools.ksp.getClassDeclarationByName import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassifierReference import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSPropertyDeclaration import com.google.devtools.ksp.symbol.KSTypeReference import com.google.devtools.ksp.symbol.Origin open class TypeParameterReferenceProcessor : AbstractTestProcessor() { val results = mutableListOf<String>() val collector = ReferenceCollector() val references = mutableSetOf<KSTypeReference>() override fun process(resolver: Resolver): List<KSAnnotated> { val files = resolver.getNewFiles() files.forEach { it.accept(collector, references) } val sortedReferences = references.filter { it.element is KSClassifierReference && it.origin == Origin.KOTLIN } .sortedBy { (it.element as KSClassifierReference).referencedName() } for (i in sortedReferences) { val r = i.resolve() results.add("${r.declaration.qualifiedName?.asString()}: ${r.isMarkedNullable}") } val libFoo = resolver.getClassDeclarationByName("LibFoo")!! libFoo.declarations.filterIsInstance<KSPropertyDeclaration>().forEach { results.add(it.type.toString()) } val javaLib = resolver.getClassDeclarationByName("JavaLib")!! javaLib.declarations.filterIsInstance<KSFunctionDeclaration>().forEach { results.add(it.returnType.toString()) } val srj = resolver.getClassDeclarationByName("SelfReferencingJava")!! srj.asStarProjectedType().declaration.typeParameters.single().bounds .forEach { results.add(it.resolve().toString()) } return emptyList() } override fun toResult(): List<String> { return results } }
apache-2.0
3e9332e51576b419d3e52d4a66bd2362
42.098361
120
0.730316
4.604203
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/intentions/wiki/ChangeExplicitToWikiLinkIntention.kt
1
2161
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.intentions.wiki import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.IncorrectOperationException import com.vladsch.md.nav.actions.handlers.util.PsiEditContext import com.vladsch.md.nav.intentions.Intention import com.vladsch.md.nav.psi.element.MdExplicitLink import com.vladsch.md.nav.psi.element.MdFile import com.vladsch.md.nav.psi.util.MdPsiImplUtil import com.vladsch.md.nav.util.FileRef import com.vladsch.md.nav.util.PsiElementPredicate class ChangeExplicitToWikiLinkIntention : Intention(), LowPriorityAction { @Throws(IncorrectOperationException::class) override fun processIntention(element: PsiElement, project: Project, editor: Editor, editContext: PsiEditContext) { if (element !is MdExplicitLink) return val resolvedElement = resolveElement<MdFile>(element.linkRefElement) MdPsiImplUtil.changeToWikiLink(element, resolvedElement != null && resolvedElement.isWikiPage) } override fun getElementPredicate(): PsiElementPredicate { return PsiElementPredicate { element -> when (element) { is MdExplicitLink -> { val containingFile = element.containingFile if (containingFile is MdFile && containingFile.isWikiPage && MdPsiImplUtil.isWikiLinkEquivalent(element)) { val resolvedElement = resolveElement<PsiFile>(element.linkRefElement) if (resolvedElement != null) { val targetRef = FileRef(resolvedElement) targetRef.isUnderWikiDir && FileRef(containingFile).wikiDir == targetRef.wikiDir } else false } else false } else -> false } } } }
apache-2.0
b96564bf31529a0b1e63ffde8b9172b8
48.113636
177
0.699213
4.791574
false
false
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/backup/serializer/TrackTypeAdapter.kt
1
1775
package eu.kanade.tachiyomi.data.backup.serializer import com.github.salomonbrys.kotson.typeAdapter import com.google.gson.TypeAdapter import com.google.gson.stream.JsonToken import eu.kanade.tachiyomi.data.database.models.TrackImpl /** * JSON Serializer used to write / read [TrackImpl] to / from json */ object TrackTypeAdapter { private const val SYNC = "s" private const val REMOTE = "r" private const val TITLE = "t" private const val LAST_READ = "l" private const val TRACKING_URL = "u" fun build(): TypeAdapter<TrackImpl> { return typeAdapter { write { beginObject() name(TITLE) value(it.title) name(SYNC) value(it.sync_id) name(REMOTE) value(it.remote_id) name(LAST_READ) value(it.last_chapter_read) name(TRACKING_URL) value(it.tracking_url) endObject() } read { val track = TrackImpl() beginObject() while (hasNext()) { if (peek() == JsonToken.NAME) { val name = nextName() when (name) { TITLE -> track.title = nextString() SYNC -> track.sync_id = nextInt() REMOTE -> track.remote_id = nextInt() LAST_READ -> track.last_chapter_read = nextInt() TRACKING_URL -> track.tracking_url = nextString() } } } endObject() track } } } }
apache-2.0
50088cbd6becd352e004e0c2aaac7804
30.157895
77
0.469859
5
false
false
false
false
alashow/music-android
modules/common-ui-components/src/main/java/tm/alashow/ui/TimedVisibility.kt
1
1729
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.ui import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** * Delays visibility of given [content] for [delayMillis]. */ @Composable fun Delayed(delayMillis: Long = 200, modifier: Modifier = Modifier, content: @Composable () -> Unit) { TimedVisibility(delayMillis = delayMillis, visibility = false, modifier = modifier, content = content) } /** * Changes visibility of given [content] after [delayMillis] to opposite of initial [visibility]. */ @OptIn(ExperimentalAnimationApi::class) @Composable fun TimedVisibility(delayMillis: Long = 4000, visibility: Boolean = true, modifier: Modifier = Modifier, content: @Composable () -> Unit) { var visible by remember { mutableStateOf(visibility) } val coroutine = rememberCoroutineScope() DisposableEffect(Unit) { val job = coroutine.launch { delay(delayMillis) visible = !visible } onDispose { job.cancel() } } AnimatedVisibility(visible = visible, modifier = modifier, enter = fadeIn(), exit = fadeOut()) { content() } }
apache-2.0
a942375b7b36e6f7621ece69097efc0f
32.25
139
0.742626
4.685637
false
false
false
false
GlimpseFramework/glimpse-framework
api/src/main/kotlin/glimpse/gles/GLES.kt
1
7022
package glimpse.gles import glimpse.Color import glimpse.Matrix import glimpse.Point import glimpse.Vector import glimpse.shaders.ProgramHandle import glimpse.shaders.ShaderHandle import glimpse.shaders.ShaderType import glimpse.textures.TextureHandle import glimpse.textures.TextureMagnificationFilter import glimpse.textures.TextureMinificationFilter import glimpse.textures.TextureWrapping import java.io.InputStream import java.nio.FloatBuffer import java.nio.IntBuffer /** * GLES facade interface. */ interface GLES { /** * Rendering viewport. */ var viewport: Viewport /** * Clear color value. */ var clearColor: Color /** * Clear depth value. */ var clearDepth: Float /** * Depth test status. */ var isDepthTest: Boolean /** * Depth test function. */ var depthTestFunction: DepthTestFunction /** * Blending status. */ var isBlend: Boolean /** * Blending function. * First element indicates source blending factor. * Second element indicates destination blending factor. */ var blendFunction: Pair<BlendFactor, BlendFactor> /** * Face culling status. */ var isCullFace: Boolean /** * Face culling mode. */ var cullFaceMode: CullFaceMode /** * Clears depth buffer. * Further rendering will be done on top of rendered image. */ fun clearDepthBuffer(): Unit /** * Clears color buffer. * The [viewport] will be filled with the [clearColor]. */ fun clearColorBuffer(): Unit /** * Creates an empty [ShaderHandle]. */ fun createShader(shaderType: ShaderType): ShaderHandle /** * Compiles a shader from [source]. */ fun compileShader(shaderHandle: ShaderHandle, source: String): Unit /** * Deletes a shader. */ fun deleteShader(shaderHandle: ShaderHandle): Unit /** * Gets shader compilation status. */ fun getShaderCompileStatus(shaderHandle: ShaderHandle): Boolean /** * Gets shader compilation log. */ fun getShaderLog(shaderHandle: ShaderHandle): String /** * Creates an empty [ProgramHandle]. */ fun createProgram(): ProgramHandle /** * Adds a shader to a program. */ fun attachShader(programHandle: ProgramHandle, shaderHandle: ShaderHandle): Unit /** * Links a shader program. */ fun linkProgram(programHandle: ProgramHandle): Unit /** * Starts using given shader program. */ fun useProgram(programHandle: ProgramHandle): Unit /** * Deletes a shader program. */ fun deleteProgram(programHandle: ProgramHandle): Unit /** * Gets shader program linking status. */ fun getProgramLinkStatus(programHandle: ProgramHandle): Boolean /** * Gets shader program linking log. */ fun getProgramLog(programHandle: ProgramHandle): String /** * Gets a location of a shader uniform with the given [name]. */ fun getUniformLocation(handle: ProgramHandle, name: String): UniformLocation /** * Gets a location of a shader attribute with the given [name]. */ fun getAttributeLocation(handle: ProgramHandle, name: String): AttributeLocation /** * Sets a uniform [float] value. */ fun uniformFloat(location: UniformLocation, float: Float): Unit /** * Sets uniform [floats]. */ fun uniformFloats(location: UniformLocation, floats: FloatArray): Unit /** * Sets a uniform [int] value. */ fun uniformInt(location: UniformLocation, int: Int): Unit /** * Sets uniform [ints]. */ fun uniformInts(location: UniformLocation, ints: IntArray): Unit /** * Sets a uniform [matrix] value. */ fun uniformMatrix(location: UniformLocation, matrix: Matrix): Unit = uniformMatrix16f(location, matrix._16f) /** * Sets a uniform `mat4` value. */ fun uniformMatrix16f(location: UniformLocation, _16f: Array<Float>): Unit /** * Sets a uniform [vector] value. */ fun uniformVector(location: UniformLocation, vector: Vector): Unit = uniform4f(location, vector._4f) /** * Sets a uniform [vectors] value. */ fun uniformVectors(location: UniformLocation, vectors: List<Vector>): Unit = uniform4f(location, vectors.flatMap { it._4f.toList() }.toTypedArray(), vectors.size) /** * Sets a uniform [point] value. */ fun uniformPoint(location: UniformLocation, point: Point): Unit = uniform4f(location, point._4f) /** * Sets a uniform [points] value. */ fun uniformPoints(location: UniformLocation, points: List<Point>): Unit = uniform4f(location, points.flatMap { it._4f.toList() }.toTypedArray(), points.size) /** * Sets a uniform [color] value. */ fun uniformColor(location: UniformLocation, color: Color): Unit = uniform4f(location, color._4f) /** * Sets a uniform [colors] value.poinpointsts */ fun uniformColors(location: UniformLocation, colors: List<Color>): Unit = uniform4f(location, colors.flatMap { it._4f.toList() }.toTypedArray(), colors.size) /** * Sets a [count] number of uniform `vec4` values. */ fun uniform4f(location: UniformLocation, _4f: Array<Float>, count: Int = 1): Unit /** * Creates a shader attribute buffer with floats arranged in vectors of [vectorSize]. */ fun createAttributeFloatArray(location: AttributeLocation, buffer: FloatBuffer, vectorSize: Int): BufferHandle /** * Creates a shader attribute buffer with integers arranged in vectors of [vectorSize]. */ fun createAttributeIntArray(location: AttributeLocation, buffer: IntBuffer, vectorSize: Int): BufferHandle /** * Deletes a shader attribute buffer. */ fun deleteAttributeArray(handle: BufferHandle): Unit /** * Enables given attribute. */ fun enableAttributeArray(location: AttributeLocation): Unit /** * Disables given attribute. */ fun disableAttributeArray(location: AttributeLocation): Unit /** * Texture minification filter. */ var textureMinificationFilter: TextureMinificationFilter /** * Texture magnification filter. */ var textureMagnificationFilter: TextureMagnificationFilter /** * Texture wrapping strategy along U and V coordinates. */ var textureWrapping: Pair<TextureWrapping, TextureWrapping> /** * Generates an empty [TextureHandle]. */ fun generateTexture(): TextureHandle = generateTextures(1)[0] /** * Generates an array of empty [TextureHandle]s. */ fun generateTextures(count: Int): Array<TextureHandle> /** * Deletes given texture. */ fun deleteTexture(handle: TextureHandle): Unit = deleteTextures(1, arrayOf(handle)) /** * Deletes given textures. */ fun deleteTextures(count: Int, handles: Array<TextureHandle>): Unit /** * Binds a 2-dimensional texture. */ fun bindTexture2D(handle: TextureHandle): Unit /** * Loads a 2-dimensional texture image from [inputStream]. * * @param inputStream Image input stream. * @param fileName Image file name with extension. * @param withMipmap Mipmapping mode. */ fun textureImage2D(inputStream: InputStream, fileName: String, withMipmap: Boolean): Unit /** * Selects an [index] of an active texture. */ fun activeTexture(index: Int): Unit /** * Draws triangles. */ fun drawTriangles(verticesCount: Int): Unit }
apache-2.0
2eb2b28ba986c5ce77f5df110fc9b7a5
22.174917
111
0.710909
3.958286
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/test/java/com/ichi2/anki/servicemodel/UpgradeGesturesToControlsTestNoParam.kt
1
3602
/* * Copyright (c) 2022 Brayan Oliveira <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.servicemodel import android.content.SharedPreferences import androidx.core.content.edit import androidx.test.ext.junit.runners.AndroidJUnit4 import com.ichi2.anki.RobolectricTest import com.ichi2.anki.servicelayer.PreferenceUpgradeService.PreferenceUpgrade.Companion.upgradeVersionPrefKey import com.ichi2.anki.servicelayer.PreferenceUpgradeService.PreferenceUpgrade.UpgradeGesturesToControls import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers import org.junit.Before import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import timber.log.Timber @RunWith(AndroidJUnit4::class) class UpgradeGesturesToControlsTestNoParam : RobolectricTest() { private val changedKeys = HashSet<String>() private lateinit var prefs: SharedPreferences private lateinit var instance: UpgradeGesturesToControls @Before override fun setUp() { super.setUp() prefs = super.getPreferences() instance = UpgradeGesturesToControls() prefs.registerOnSharedPreferenceChangeListener { _, key -> run { Timber.i("added key $key"); changedKeys.add(key) } } } @Test @Ignore("flaky in CI") fun test_preferences_not_opened_happy_path() { // if the user has not opened the gestures, then nothing should be mapped assertThat(prefs.contains(PREF_KEY_VOLUME_DOWN), equalTo(false)) assertThat(prefs.contains(PREF_KEY_VOLUME_UP), equalTo(false)) upgradeAllGestures() // ensure that no settings were added to the preferences assertThat(changedKeys, Matchers.contains(upgradeVersionPrefKey)) } @Test @Ignore("flaky in CI") fun test_preferences_opened_happy_path() { // the default is that the user has not mapped the gesture, but has opened the screen // so they are set to NOTHING which had "0" as value prefs.edit { putString(PREF_KEY_VOLUME_UP, "0") } prefs.edit { putString(PREF_KEY_VOLUME_DOWN, "0") } assertThat(prefs.contains(PREF_KEY_VOLUME_DOWN), equalTo(true)) assertThat(prefs.contains(PREF_KEY_VOLUME_UP), equalTo(true)) upgradeAllGestures() // ensure that no settings were added to the preferences assertThat(changedKeys, Matchers.contains(upgradeVersionPrefKey, PREF_KEY_VOLUME_DOWN, PREF_KEY_VOLUME_UP)) assertThat("Volume gestures are removed", prefs.contains(PREF_KEY_VOLUME_DOWN), equalTo(false)) assertThat("Volume gestures are removed", prefs.contains(PREF_KEY_VOLUME_UP), equalTo(false)) } private fun upgradeAllGestures() { changedKeys.clear() instance.performUpgrade(prefs) } companion object { const val PREF_KEY_VOLUME_UP = "gestureVolumeUp" const val PREF_KEY_VOLUME_DOWN = "gestureVolumeDown" } }
gpl-3.0
8fdd7e6aba7ba09dad7767ca3c66ed61
39.022222
125
0.728484
4.188372
false
true
false
false
wcaokaze/cac2er
src/main/kotlin/com/wcaokaze/io/CacheIOStream.kt
1
4464
package com.wcaokaze.io import com.wcaokaze.cac2er.CacheUniformizer import com.wcaokaze.cac2er.Cacheable import com.wcaokaze.cac2er.Dependence import java.io.* import kotlin.reflect.KClass import kotlin.reflect.KProperty1 import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.memberProperties import kotlin.reflect.full.primaryConstructor private val TYPE_CODE_NULL = 0 private val TYPE_CODE_SERIALIZABLE = 1 private val TYPE_CODE_CACHEABLE = 2 private val TYPE_CODE_STRING = 3 private val TYPE_CODE_BYTE = 4 private val TYPE_CODE_SHORT = 5 private val TYPE_CODE_CHAR = 6 private val TYPE_CODE_INT = 7 private val TYPE_CODE_LONG = 8 private val TYPE_CODE_FLOAT = 9 private val TYPE_CODE_DOUBLE = 10 private val TYPE_CODE_BOOLEAN = 11 internal class CacheOutputStream( outputStream: OutputStream, val uniformizer: CacheUniformizer, val dependence: Dependence ) : ObjectOutputStream(outputStream) { fun writeAny(obj: Any?) { when { obj == null -> writeByte(TYPE_CODE_NULL) obj is String -> { writeByte(TYPE_CODE_STRING) writeUTF(obj) } obj is Byte -> { writeByte(TYPE_CODE_BYTE) writeByte(obj.toInt()) } obj is Short -> { writeByte(TYPE_CODE_SHORT) writeShort(obj.toInt()) } obj is Char -> { writeByte(TYPE_CODE_CHAR) writeChar(obj.toInt()) } obj is Int -> { writeByte(TYPE_CODE_INT) writeInt(obj) } obj is Long -> { writeByte(TYPE_CODE_LONG) writeLong(obj) } obj is Float -> { writeByte(TYPE_CODE_FLOAT) writeFloat(obj) } obj is Double -> { writeByte(TYPE_CODE_DOUBLE) writeDouble(obj) } obj is Boolean -> { writeByte(TYPE_CODE_BOOLEAN) writeBoolean(obj) } obj::class.hasAnnotation<Cacheable>() -> { writeByte(TYPE_CODE_CACHEABLE) writeCacheable(obj) } else -> { writeByte(TYPE_CODE_SERIALIZABLE) writeObject(obj) } } } private fun writeCacheable(obj: Any) { val clazz = obj::class val annotation = clazz.findAnnotation<Cacheable>() ?: throw IllegalArgumentException("Not cacheable: ${obj::class}") writeUTF(clazz.java.name) writeInt(annotation.versionUID) for (prop in clazz.memberProperties.sortedBy { it.name }) { // actual `prop` is not KProperty1<Any, *>, but here the first type // argument is only used to statically type-check for receiver of the // property. `obj` can be the receiver for `prop` here. @Suppress("UNCHECKED_CAST") val value = (prop as KProperty1<Any, *>).get(obj) writeAny(value) } } } internal class CacheInputStream(inputStream: InputStream, val parentFile: File) : ObjectInputStream(inputStream) { fun readAny(): Any? = when (readByte().toInt()) { TYPE_CODE_NULL -> null TYPE_CODE_STRING -> readUTF() TYPE_CODE_BYTE -> readByte() TYPE_CODE_SHORT -> readShort() TYPE_CODE_CHAR -> readChar() TYPE_CODE_INT -> readInt() TYPE_CODE_LONG -> readLong() TYPE_CODE_FLOAT -> readFloat() TYPE_CODE_DOUBLE -> readDouble() TYPE_CODE_BOOLEAN -> readBoolean() TYPE_CODE_CACHEABLE -> readCacheable() TYPE_CODE_SERIALIZABLE -> readObject() else -> throw AssertionError() } private fun readCacheable(): Any { val className = readUTF() val clazz = Class.forName(className).kotlin val annotation = clazz.findAnnotation<Cacheable>() ?: throw InvalidClassException("Not cacheable: $clazz") val versionUID = readInt() if (versionUID != annotation.versionUID) { throw InvalidClassException("versionUID mismatched" + "(binary: $versionUID, class: ${annotation.versionUID})") } val constructor = clazz.primaryConstructor ?: throw InvalidClassException( "can not determine the primary constructor: $clazz" ) val args = constructor.parameters .sortedBy { it.name } .map { it to readAny() } .toMap() return constructor.callBy(args) } } private inline fun <reified A : Annotation> KClass<*>.hasAnnotation() = java.getAnnotation(A::class.java) != null
mit
edb9ccb88d085000be8a78f4c1bec1a1
26.219512
79
0.618056
4.137164
false
false
false
false
youkai-app/Youkai
app/src/main/kotlin/app/youkai/data/models/LibraryEntry.kt
1
2369
package app.youkai.data.models import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.github.jasminb.jsonapi.Links import com.github.jasminb.jsonapi.annotations.Relationship import com.github.jasminb.jsonapi.annotations.RelationshipLinks import com.github.jasminb.jsonapi.annotations.Type @Type("libraryEntries") @JsonIgnoreProperties(ignoreUnknown = true) class LibraryEntry : BaseJsonModel(JsonType("libraryEntries")) { companion object FieldNames { val STATUS = "status" val PROGRESS = "progress" val RECONSUMING = "reconsuming" val RECONSUME_COUNT = "reconsumeCount" val NOTES = "notes" val PRIVATE = "private" val UPDATED_AT = "updatedAt" val RATING = "rating" val RATING_TWENTY = "ratingTwenty" val USER = "user" val ANIME = "anime" val MANGA = "manga" val REVIEW = "review" val REACTION = "mediaReaction" val MEDIA = "media" } var status: String? = null var progress: Int? = null var reconsuming: Boolean? = null var reconsumeCount: Int? = null var notes: String? = null var private: Boolean? = null var updatedAt: String? = null var rating: String? = null var ratingTwenty: Int? = null @Relationship("user") var user: User? = null @RelationshipLinks("user") var userLinks: Links? = null @Relationship("anime") var anime: Anime? = null @RelationshipLinks("anime") var animeLinks: Links? = null @Relationship("manga") var manga: Manga? = null @RelationshipLinks("manga") var mangaLinks: Links? = null @Relationship("review") var review: Review? = null @RelationshipLinks("review") var reviewLinks: Links? = null @Relationship("mediaReaction") var reaction: Reaction? = null @RelationshipLinks("mediaReaction") var reactionLinks: Links? = null /* Are returned by the API but aren't implemented. @Relationship("unit") var unit: IDEK? = null @RelationshipLinks("unit") var unitLinks: Links? = null @Relationship("nextUnit") var nextUnit: IDEK? = null @RelationshipLinks("nextUnit") var nextUnitLinks: IDEK? = null @Relationship("drama") var drama: Drama? = null @RelationshipLinks("drama") var dramaLinks: Links? = null */ }
gpl-3.0
af51e62cb0292cec27fb8c4c57bded09
22.939394
67
0.655129
4.15614
false
false
false
false
FHannes/intellij-community
platform/diff-impl/tests/com/intellij/diff/HeavyDiffTestCase.kt
3
1404
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff import com.intellij.openapi.project.Project import com.intellij.testFramework.fixtures.IdeaProjectTestFixture import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory import com.intellij.testFramework.runInEdtAndWait abstract class HeavyDiffTestCase : DiffTestCase() { var projectFixture: IdeaProjectTestFixture? = null var project: Project? = null override fun setUp() { super.setUp() projectFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getTestName()).fixture projectFixture!!.setUp() project = projectFixture!!.project } override fun tearDown() { projectFixture?.tearDown() project = null super.tearDown() } override fun runBare() { runInEdtAndWait { super.runBare() } } }
apache-2.0
e9e53954e00b57b0be4e6b455965caeb
28.893617
107
0.747863
4.603279
false
true
false
false
dafi/photoshelf
tumblr-ui-core/src/main/java/com/ternaryop/photoshelf/tumblr/ui/core/adapter/switcher/AdapterSwitcher.kt
1
2391
package com.ternaryop.photoshelf.tumblr.ui.core.adapter.switcher import android.content.Context import android.os.Parcelable import androidx.preference.PreferenceManager import androidx.recyclerview.widget.RecyclerView import com.ternaryop.photoshelf.tumblr.ui.core.adapter.ViewType private const val PREF_VIEW_TYPE = "photo_adapter_view_type" class AdapterSwitcher<T : RecyclerView.Adapter<RecyclerView.ViewHolder>>( val context: Context, val adapterGroup: AdapterGroup<T>, val onSwitchView: OnSwitchView<T>? ) { var viewType: ViewType private set private val layoutStateMap = HashMap<ViewType, Parcelable?>() init { viewType = loadViewType(context, adapterGroup.config.prefNamePrefix) onSwitched(null) } fun switchView(viewType: ViewType) { if (viewType == this.viewType) { return } saveState() this.viewType = viewType onSwitched(adapterGroup.adapter) restoreState() } private fun onSwitched(adapter: T?) { when (viewType) { ViewType.List -> adapterGroup.createListAdapter(context, adapter) ViewType.Grid -> adapterGroup.createGridAdapter(context, adapter) } onSwitchView?.onSwitched(this, viewType) } fun toggleView() { val viewType = if (viewType == ViewType.List) { ViewType.Grid } else { ViewType.List } saveViewType(context, adapterGroup.config.prefNamePrefix, viewType) switchView(viewType) } private fun saveState() { layoutStateMap[viewType] = adapterGroup.recyclerView.layoutManager?.onSaveInstanceState() } private fun restoreState() { adapterGroup.recyclerView.layoutManager?.onRestoreInstanceState(layoutStateMap[viewType]) } companion object { fun loadViewType(context: Context, prefNamePrefix: String): ViewType { return ViewType.load( PreferenceManager.getDefaultSharedPreferences(context), prefNamePrefix + PREF_VIEW_TYPE ) } fun saveViewType(context: Context, prefNamePrefix: String, viewType: ViewType) { PreferenceManager.getDefaultSharedPreferences(context).edit().also { viewType.save(it, prefNamePrefix + PREF_VIEW_TYPE) }.apply() } } }
mit
2d142e304d4cdaeef3d29490104d2c70
30.051948
97
0.662066
4.869654
false
false
false
false
natanieljr/droidmate
project/pcComponents/core/src/main/kotlin/org/droidmate/api/JavaAPI.kt
1
2943
package org.droidmate.api import com.natpryce.konfig.CommandLineOption import kotlinx.coroutines.runBlocking import org.droidmate.command.ExploreCommandBuilder import org.droidmate.configuration.ConfigurationWrapper import org.droidmate.device.android_sdk.Apk import org.droidmate.explorationModel.ModelFeatureI import org.droidmate.explorationModel.factory.AbstractModel import org.droidmate.explorationModel.factory.DefaultModelProvider import org.droidmate.explorationModel.factory.ModelProvider import org.droidmate.explorationModel.interaction.State import org.droidmate.explorationModel.interaction.Widget import org.droidmate.misc.FailableExploration @Suppress("unused") //TODO we should have at least a test calling the API methods object JavaAPI { @JvmStatic fun config(args: Array<String>, vararg options: CommandLineOption): ConfigurationWrapper = ExplorationAPI.config(args, *options) @JvmStatic fun customCommandConfig(args: Array<String>, vararg options: CommandLineOption): ConfigurationWrapper = ExplorationAPI.customCommandConfig(args, *options) @JvmStatic fun defaultReporter(cfg: ConfigurationWrapper): List<ModelFeatureI> = ExplorationAPI.defaultReporter(cfg) @JvmStatic fun buildFromConfig(cfg: ConfigurationWrapper) = ExploreCommandBuilder.fromConfig(cfg) @JvmStatic @Deprecated("use the new model-provider mechanism", replaceWith= ReplaceWith("DefaultModelProvider()","import org.droidmate.explorationModel.factory.DefaultModelProvider")) fun defaultModelProvider(@Suppress("UNUSED_PARAMETER") cfg: ConfigurationWrapper) = DefaultModelProvider() @JvmStatic @JvmOverloads fun instrument(args: Array<String> = emptyArray()) = runBlocking { ExplorationAPI.instrument(args) } @JvmStatic fun instrument(cfg: ConfigurationWrapper) = runBlocking { ExplorationAPI.instrument(cfg) } @JvmStatic @JvmOverloads fun<M: AbstractModel<S, W>, S: State<W>,W: Widget> explore( cfg: ConfigurationWrapper, commandBuilder: ExploreCommandBuilder? = null, watcher: List<ModelFeatureI>? = null, modelProvider: ModelProvider<M>? = null ) = runBlocking { ExplorationAPI.explore(cfg, commandBuilder, watcher, modelProvider) } @JvmStatic @JvmOverloads fun inline(args: Array<String> = emptyArray()) { runBlocking { ExplorationAPI.inline(args) } } @JvmStatic fun inline(cfg: ConfigurationWrapper) { runBlocking { ExplorationAPI.inline(cfg) } } @JvmStatic @JvmOverloads fun inlineAndExplore( args: Array<String> = emptyArray(), commandBuilder: ExploreCommandBuilder? = null, watcher: List<ModelFeatureI>? = null): Map<Apk, FailableExploration> = runBlocking { ExplorationAPI.inlineAndExplore(args, commandBuilder, watcher) } }
gpl-3.0
b0087413d6c3b5c3ea493924ac05a0bf
34.46988
128
0.734625
4.73913
false
true
false
false
Light-Team/ModPE-IDE-Source
languages/language-javascript/src/main/kotlin/com/brackeys/ui/language/javascript/styler/JavaScriptStyler.kt
1
10940
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.brackeys.ui.language.javascript.styler import android.util.Log import com.brackeys.ui.language.base.model.SyntaxScheme import com.brackeys.ui.language.base.span.StyleSpan import com.brackeys.ui.language.base.span.SyntaxHighlightSpan import com.brackeys.ui.language.base.styler.LanguageStyler import com.brackeys.ui.language.base.utils.StylingResult import com.brackeys.ui.language.base.utils.StylingTask import com.brackeys.ui.language.javascript.lexer.JavaScriptLexer import com.brackeys.ui.language.javascript.lexer.JavaScriptToken import java.io.IOException import java.io.StringReader import java.util.regex.Pattern class JavaScriptStyler private constructor() : LanguageStyler { companion object { private const val TAG = "JavaScriptStyler" private val METHOD = Pattern.compile("(?<=(function)) (\\w+)") private var javaScriptStyler: JavaScriptStyler? = null fun getInstance(): JavaScriptStyler { return javaScriptStyler ?: JavaScriptStyler().also { javaScriptStyler = it } } } private var task: StylingTask? = null override fun execute(sourceCode: String, syntaxScheme: SyntaxScheme): List<SyntaxHighlightSpan> { val syntaxHighlightSpans = mutableListOf<SyntaxHighlightSpan>() val sourceReader = StringReader(sourceCode) val lexer = JavaScriptLexer(sourceReader) // FIXME flex doesn't support positive lookbehind val matcher = METHOD.matcher(sourceCode) matcher.region(0, sourceCode.length) while (matcher.find()) { val styleSpan = StyleSpan(syntaxScheme.methodColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, matcher.start(), matcher.end()) syntaxHighlightSpans.add(syntaxHighlightSpan) } while (true) { try { when (lexer.advance()) { JavaScriptToken.LONG_LITERAL, JavaScriptToken.INTEGER_LITERAL, JavaScriptToken.FLOAT_LITERAL, JavaScriptToken.DOUBLE_LITERAL -> { val styleSpan = StyleSpan(syntaxScheme.numberColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JavaScriptToken.EQEQ, JavaScriptToken.NOTEQ, JavaScriptToken.OROR, JavaScriptToken.PLUSPLUS, JavaScriptToken.MINUSMINUS, JavaScriptToken.LT, JavaScriptToken.LTLT, JavaScriptToken.LTEQ, JavaScriptToken.LTLTEQ, JavaScriptToken.GT, JavaScriptToken.GTGT, JavaScriptToken.GTGTGT, JavaScriptToken.GTEQ, JavaScriptToken.GTGTEQ, JavaScriptToken.GTGTGTEQ, JavaScriptToken.AND, JavaScriptToken.ANDAND, JavaScriptToken.PLUSEQ, JavaScriptToken.MINUSEQ, JavaScriptToken.MULTEQ, JavaScriptToken.DIVEQ, JavaScriptToken.ANDEQ, JavaScriptToken.OREQ, JavaScriptToken.XOREQ, JavaScriptToken.MODEQ, JavaScriptToken.LPAREN, JavaScriptToken.RPAREN, JavaScriptToken.LBRACE, JavaScriptToken.RBRACE, JavaScriptToken.LBRACK, JavaScriptToken.RBRACK, JavaScriptToken.EQ, JavaScriptToken.NOT, JavaScriptToken.TILDE, JavaScriptToken.QUEST, JavaScriptToken.COLON, JavaScriptToken.PLUS, JavaScriptToken.MINUS, JavaScriptToken.MULT, JavaScriptToken.DIV, JavaScriptToken.OR, JavaScriptToken.XOR, JavaScriptToken.MOD, JavaScriptToken.ELLIPSIS, JavaScriptToken.ARROW -> { val styleSpan = StyleSpan(syntaxScheme.operatorColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JavaScriptToken.SEMICOLON, JavaScriptToken.COMMA, JavaScriptToken.DOT -> { continue // skip } JavaScriptToken.FUNCTION, JavaScriptToken.PROTOTYPE, JavaScriptToken.DEBUGGER, JavaScriptToken.SUPER, JavaScriptToken.THIS, JavaScriptToken.ASYNC, JavaScriptToken.AWAIT, JavaScriptToken.EXPORT, JavaScriptToken.FROM, JavaScriptToken.EXTENDS, JavaScriptToken.FINAL, JavaScriptToken.IMPLEMENTS, JavaScriptToken.NATIVE, JavaScriptToken.PRIVATE, JavaScriptToken.PROTECTED, JavaScriptToken.PUBLIC, JavaScriptToken.STATIC, JavaScriptToken.SYNCHRONIZED, JavaScriptToken.THROWS, JavaScriptToken.TRANSIENT, JavaScriptToken.VOLATILE, JavaScriptToken.YIELD, JavaScriptToken.DELETE, JavaScriptToken.NEW, JavaScriptToken.IN, JavaScriptToken.INSTANCEOF, JavaScriptToken.TYPEOF, JavaScriptToken.OF, JavaScriptToken.WITH, JavaScriptToken.BREAK, JavaScriptToken.CASE, JavaScriptToken.CATCH, JavaScriptToken.CONTINUE, JavaScriptToken.DEFAULT, JavaScriptToken.DO, JavaScriptToken.ELSE, JavaScriptToken.FINALLY, JavaScriptToken.FOR, JavaScriptToken.GOTO, JavaScriptToken.IF, JavaScriptToken.IMPORT, JavaScriptToken.PACKAGE, JavaScriptToken.RETURN, JavaScriptToken.SWITCH, JavaScriptToken.THROW, JavaScriptToken.TRY, JavaScriptToken.WHILE, JavaScriptToken.CONST, JavaScriptToken.VAR, JavaScriptToken.LET -> { val styleSpan = StyleSpan(syntaxScheme.keywordColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JavaScriptToken.CLASS, JavaScriptToken.INTERFACE, JavaScriptToken.ENUM, JavaScriptToken.BOOLEAN, JavaScriptToken.BYTE, JavaScriptToken.CHAR, JavaScriptToken.DOUBLE, JavaScriptToken.FLOAT, JavaScriptToken.INT, JavaScriptToken.LONG, JavaScriptToken.SHORT, JavaScriptToken.VOID -> { val styleSpan = StyleSpan(syntaxScheme.typeColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JavaScriptToken.TRUE, JavaScriptToken.FALSE, JavaScriptToken.NULL, JavaScriptToken.NAN, JavaScriptToken.UNDEFINED -> { val styleSpan = StyleSpan(syntaxScheme.langConstColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JavaScriptToken.DOUBLE_QUOTED_STRING, JavaScriptToken.SINGLE_QUOTED_STRING, JavaScriptToken.SINGLE_BACKTICK_STRING -> { val styleSpan = StyleSpan(syntaxScheme.stringColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JavaScriptToken.LINE_COMMENT, JavaScriptToken.BLOCK_COMMENT -> { val styleSpan = StyleSpan(syntaxScheme.commentColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JavaScriptToken.IDENTIFIER, JavaScriptToken.WHITESPACE, JavaScriptToken.BAD_CHARACTER -> { continue } JavaScriptToken.EOF -> { break } } } catch (e: IOException) { Log.e(TAG, e.message, e) break } } return syntaxHighlightSpans } override fun enqueue(sourceCode: String, syntaxScheme: SyntaxScheme, stylingResult: StylingResult) { task?.cancelTask() task = StylingTask( doAsync = { execute(sourceCode, syntaxScheme) }, onSuccess = stylingResult ) task?.executeTask() } override fun cancel() { task?.cancelTask() task = null } }
apache-2.0
13539fbf07e9aa476bdf1fdef1968f9c
42.416667
114
0.545978
5.891222
false
false
false
false
soniccat/android-taskmanager
storagemanager/src/main/java/com/example/alexeyglushkov/cachemanager/preference/PreferenceStorage.kt
1
2040
package com.example.alexeyglushkov.cachemanager.preference import android.content.Context import android.content.SharedPreferences import com.example.alexeyglushkov.cachemanager.Storage import com.example.alexeyglushkov.cachemanager.StorageEntry import com.example.alexeyglushkov.cachemanager.StorageMetadata import com.example.alexeyglushkov.tools.ContextProvider /** * Created by alexeyglushkov on 04.09.16. */ class PreferenceStorage(private val name: String, private val contextProvider: ContextProvider) : Storage { @Throws(Exception::class) override fun put(key: String, value: Any, metadata: StorageMetadata?) { val editor = writePreference if (value is Int) { editor.putInt(key, value) } else if (value is Long) { editor.putLong(key, value) } editor.commit() } override fun getValue(key: String): Any? { return readPreference.all[key] } override fun createMetadata(): StorageMetadata { throw NotImplementedError("StorageMetadata isn't supported in PreferenceStorage") } override fun getMetadata(key: String): StorageMetadata? { return null } @Throws(Exception::class) override fun remove(key: String) { val editor = writePreference editor.remove(key) editor.commit() } override fun getEntry(key: String): StorageEntry? { return null } override fun getEntries(): List<StorageEntry> { return emptyList() } @Throws(Exception::class) override fun removeAll() { val editor = writePreference editor.clear() editor.commit() } //// private val writePreference: SharedPreferences.Editor private get() = context.getSharedPreferences(name, Context.MODE_PRIVATE).edit() private val readPreference: SharedPreferences private get() = context.getSharedPreferences(name, Context.MODE_PRIVATE) private val context: Context private get() = contextProvider.context!! }
mit
267ed3b208660a26344844071a477e12
28.57971
107
0.688235
4.822695
false
false
false
false
cout970/Magneticraft
ignore/test/integration/jei/kiln/KilnRecipeWrapper.kt
2
1229
package integration.jei.kiln import com.cout970.magneticraft.api.registries.machines.kiln.IKilnRecipe import mezz.jei.api.ingredients.IIngredients import mezz.jei.api.recipe.IRecipeWrapper import net.minecraft.client.Minecraft import net.minecraftforge.fluids.FluidStack /** * Created by cout970 on 24/08/2016. */ class KilnRecipeWrapper(val recipe: IKilnRecipe) : IRecipeWrapper { override fun drawAnimations(minecraft: Minecraft, recipeWidth: Int, recipeHeight: Int) = Unit override fun drawInfo(minecraft: Minecraft, recipeWidth: Int, recipeHeight: Int, mouseX: Int, mouseY: Int) = Unit override fun getTooltipStrings(mouseX: Int, mouseY: Int): MutableList<String>? = mutableListOf() override fun getFluidInputs(): MutableList<FluidStack>? = mutableListOf() override fun handleClick(minecraft: Minecraft, mouseX: Int, mouseY: Int, mouseButton: Int): Boolean = false override fun getOutputs(): MutableList<Any?>? = mutableListOf(recipe.itemOutput, recipe.blockOutput) override fun getFluidOutputs(): MutableList<FluidStack>? = mutableListOf() override fun getInputs(): MutableList<Any?>? = mutableListOf(recipe.input) override fun getIngredients(ingredients: IIngredients?) {} }
gpl-2.0
2388bbd643fc1bab6364ff06980b464b
38.677419
117
0.771359
4.312281
false
false
false
false
trivago/Heimdall.droid
library/src/main/java/de/rheinfabrik/heimdall2/OAuth2AccessToken.kt
2
1728
package de.rheinfabrik.heimdall2 import com.google.gson.annotations.SerializedName import java.io.Serializable import java.util.Calendar data class OAuth2AccessToken( /** * REQUIRED * The type of the token issued as described in https://tools.ietf.org/html/rfc6749#section-7.1. * Value is case insensitive. */ @SerializedName("token_type") val tokenType: String = "", /** * REQUIRED * The access token issued by the authorization server. */ @SerializedName("access_token") val accessToken: String = "", /** * OPTIONAL * The refresh token, which can be used to obtain new * access tokens using the same authorization grant as described * in https://tools.ietf.org/html/rfc6749#section-6. */ @SerializedName("refresh_token") val refreshToken: String? = null, /** * RECOMMENDED * The lifetime in seconds of the access token. For * example, the value "3600" denotes that the access token will * expire in one hour from the time the response was generated. * If omitted, the authorization server SHOULD provide the * expiration time via other means or document the default value. */ @SerializedName("expires_in") val expiresIn: Int? = null, /** * The expiration date used by Heimdall. */ @SerializedName("heimdall_expiration_date") val expirationDate: Calendar? = null ) : Serializable { // Public API /** * Returns whether the access token expired or not. * * @return True if expired. Otherwise false. */ fun isExpired(): Boolean = expirationDate != null && Calendar.getInstance().after(expirationDate) }
apache-2.0
205c121b1643f5f3d689beb2b8fcb919
27.327869
100
0.653356
4.352645
false
false
false
false
nemerosa/ontrack
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/sync/SCMCatalogImportJob.kt
1
1558
package net.nemerosa.ontrack.extension.scm.catalog.sync import net.nemerosa.ontrack.extension.scm.SCMJobs import net.nemerosa.ontrack.job.Job import net.nemerosa.ontrack.job.JobKey import net.nemerosa.ontrack.job.JobRegistration import net.nemerosa.ontrack.job.JobRun import net.nemerosa.ontrack.job.Schedule import net.nemerosa.ontrack.model.settings.CachedSettingsService import net.nemerosa.ontrack.model.support.JobProvider import org.springframework.stereotype.Component /** * Importing the SCM catalog entries as Ontrack projects */ @Component class SCMCatalogImportJob( private val cachedSettingsService: CachedSettingsService, private val scmCatalogImportService: SCMCatalogImportService, ) : JobProvider { override fun getStartingJobs(): Collection<JobRegistration> = listOf( JobRegistration.of( createSCMCatalogImportJob() ).withSchedule(Schedule.EVERY_DAY) ) private fun createSCMCatalogImportJob() = object : Job { override fun isDisabled(): Boolean = !cachedSettingsService.getCachedSettings(SCMCatalogSyncSettings::class.java).syncEnabled override fun getKey(): JobKey = SCMJobs.category .getType("catalog").withName("SCM Catalog") .getKey("import") override fun getDescription(): String = "Importing the SCM Catalog as projects" override fun getTask() = JobRun { listener -> scmCatalogImportService.importCatalog { listener.message(it) } } } }
mit
c8e80f84961562f4a16179b076c8017f
31.479167
100
0.718228
4.706949
false
false
false
false
luisrovirosa/Tennis-Refactoring-Kata
kotlin/src/main/kotlin/TennisGame2.kt
2
2842
class TennisGame2(private val player1Name: String, private val player2Name: String) : TennisGame { var P1point: Int = 0 var P2point: Int = 0 var P1res: String = "" var P2res: String = "" override fun getScore(): String { var score = "" if (P1point == P2point && P1point < 4) { if (P1point == 0) score = "Love" if (P1point == 1) score = "Fifteen" if (P1point == 2) score = "Thirty" score += "-All" } if (P1point == P2point && P1point >= 3) score = "Deuce" if (P1point > 0 && P2point == 0) { if (P1point == 1) P1res = "Fifteen" if (P1point == 2) P1res = "Thirty" if (P1point == 3) P1res = "Forty" P2res = "Love" score = "$P1res-$P2res" } if (P2point > 0 && P1point == 0) { if (P2point == 1) P2res = "Fifteen" if (P2point == 2) P2res = "Thirty" if (P2point == 3) P2res = "Forty" P1res = "Love" score = "$P1res-$P2res" } if (P1point > P2point && P1point < 4) { if (P1point == 2) P1res = "Thirty" if (P1point == 3) P1res = "Forty" if (P2point == 1) P2res = "Fifteen" if (P2point == 2) P2res = "Thirty" score = "$P1res-$P2res" } if (P2point > P1point && P2point < 4) { if (P2point == 2) P2res = "Thirty" if (P2point == 3) P2res = "Forty" if (P1point == 1) P1res = "Fifteen" if (P1point == 2) P1res = "Thirty" score = "$P1res-$P2res" } if (P1point > P2point && P2point >= 3) { score = "Advantage player1" } if (P2point > P1point && P1point >= 3) { score = "Advantage player2" } if (P1point >= 4 && P2point >= 0 && P1point - P2point >= 2) { score = "Win for player1" } if (P2point >= 4 && P1point >= 0 && P2point - P1point >= 2) { score = "Win for player2" } return score } fun SetP1Score(number: Int) { for (i in 0 until number) { P1Score() } } fun SetP2Score(number: Int) { for (i in 0 until number) { P2Score() } } fun P1Score() { P1point++ } fun P2Score() { P2point++ } override fun wonPoint(player: String) { if (player === "player1") P1Score() else P2Score() } }
mit
dcfb009c265a6dec807f79ebb03cb23e
23.721739
98
0.403941
3.457421
false
false
false
false
goodwinnk/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/search/GithubPullRequestSearchQuery.kt
1
5183
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.search import org.jetbrains.plugins.github.api.data.GithubIssueState import org.jetbrains.plugins.github.api.search.GithubIssueSearchSort import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder import org.jetbrains.plugins.github.exceptions.GithubParseException import java.text.ParseException import java.text.SimpleDateFormat class GithubPullRequestSearchQuery(private val terms: List<Term<*>>) { fun buildApiSearchQuery(searchQueryBuilder: GithubApiSearchQueryBuilder) { for (term in terms) { when (term) { is Term.QueryPart -> { searchQueryBuilder.query(term.apiValue) } is Term.Qualifier -> { searchQueryBuilder.qualifier(term.apiName, term.apiValue) } } } } fun isEmpty() = terms.isEmpty() companion object { private val DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd") @Throws(GithubParseException::class) fun parseFromString(string: String): GithubPullRequestSearchQuery { val result = mutableListOf<Term<*>>() val terms = string.split(' ') for (term in terms) { if (term.isEmpty()) continue val colonIdx = term.indexOf(':') if (colonIdx < 0) { result.add(Term.QueryPart(term)) } else { try { result.add(QualifierName.valueOf(term.substring(0, colonIdx)).createTerm(term.substring(colonIdx + 1))) } catch (e: IllegalArgumentException) { result.add(Term.QueryPart(term)) } } } return GithubPullRequestSearchQuery(result) } } @Suppress("EnumEntryName") enum class QualifierName(val apiName: String) { state("state") { override fun createTerm(value: String) = Term.Qualifier.Enum.from<GithubIssueState>(this, value) }, assignee("assignee") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) }, author("author") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) }, after("created") { override fun createTerm(value: String) = Term.Qualifier.Date.After.from(this, value) }, before("created") { override fun createTerm(value: String) = Term.Qualifier.Date.Before.from(this, value) }, sortBy("sort") { override fun createTerm(value: String) = Term.Qualifier.Enum.from<GithubIssueSearchSort>(this, value) }; abstract fun createTerm(value: String): Term<*> } /** * Part of search query (search term) */ sealed class Term<T : Any>(protected val value: T) { abstract val apiValue: String? class QueryPart(value: String) : Term<String>(value) { override val apiValue = this.value } sealed class Qualifier<T : Any>(name: QualifierName, value: T) : Term<T>(value) { val apiName: String = name.apiName class Simple(name: QualifierName, value: String) : Qualifier<String>(name, value) { override val apiValue = this.value } class Enum<T : kotlin.Enum<T>>(name: QualifierName, value: T) : Qualifier<kotlin.Enum<T>>(name, value) { override val apiValue = this.value.name companion object { inline fun <reified T : kotlin.Enum<T>> from(name: QualifierName, value: String): Term<*> { try { return Qualifier.Enum(name, enumValueOf<T>(value)) } catch (e: IllegalArgumentException) { throw GithubParseException( "Can't parse $name from $value. Should be one of [${enumValues<T>().joinToString { it.name }}]", e) } } } } sealed class Date(name: QualifierName, value: java.util.Date) : Qualifier<java.util.Date>(name, value) { protected fun formatDate(): String = DATE_FORMAT.format(this.value) companion object { private fun getDate(name: QualifierName, value: String): java.util.Date { try { return DATE_FORMAT.parse(value) } catch (e: ParseException) { throw GithubParseException("Could not parse date for $name from $value. Should match the pattern ${DATE_FORMAT.toPattern()}", e) } } } class Before(name: QualifierName, value: java.util.Date) : Date(name, value) { override val apiValue = "<${formatDate()}" companion object { fun from(name: QualifierName, value: String): Term<*> { return Qualifier.Date.Before(name, Date.getDate(name, value)) } } } class After(name: QualifierName, value: java.util.Date) : Date(name, value) { override val apiValue = ">${formatDate()}" companion object { fun from(name: QualifierName, value: String): Term<*> { return Qualifier.Date.After(name, Date.getDate(name, value)) } } } } } } }
apache-2.0
ad549244a6f5b18264c06b22ca83886f
34.027027
140
0.618175
4.381234
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/animate/serialization/AnLibrarySerializer.kt
1
13175
package com.soywiz.korge.animate.serialization import com.soywiz.kds.iterators.* import com.soywiz.kmem.* import com.soywiz.korge.animate.* import com.soywiz.korge.view.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.color.* import com.soywiz.korim.format.* import com.soywiz.korio.file.* import com.soywiz.korio.serialization.json.* import com.soywiz.korio.stream.* import com.soywiz.korma.geom.* suspend fun AnLibrary.writeTo(file: VfsFile, config: AnLibrarySerializer.Config = AnLibrarySerializer.Config()) { //println("writeTo") val format = PNG val props = ImageEncodingProps(quality = config.compression) file.write(AnLibrarySerializer.gen(this, config = config, externalWriters = AnLibrarySerializer.ExternalWriters( writeAtlas = { index, atlas -> //showImageAndWait(atlas) file.withExtension("ani.$index.png").writeBitmap(atlas, format, props) }, writeSound = { index, soundData -> file.withExtension("ani.$index.mp3").write(soundData) } ))) } object AnLibrarySerializer { class ExternalWriters( val writeAtlas: suspend (index: Int, bitmap: Bitmap) -> Unit, val writeSound: suspend (index: Int, soundData: ByteArray) -> Unit ) class Config( val compression: Double = 1.0, val keepPaths: Boolean = false, val mipmaps: Boolean = true, val smoothInterpolation: Boolean = true ) suspend fun gen(library: AnLibrary, config: Config = Config(), externalWriters: ExternalWriters): ByteArray = MemorySyncStreamToByteArray { write(this, library, config, externalWriters) } suspend fun write(s: SyncStream, library: AnLibrary, config: Config = Config(), externalWriters: ExternalWriters) = s.writeLibrary(library, config, externalWriters) private fun SyncStream.writeRect(r: Rectangle) { writeS_VL((r.x * 20).toInt()) writeS_VL((r.y * 20).toInt()) writeS_VL((r.width * 20).toInt()) writeS_VL((r.height * 20).toInt()) } private fun SyncStream.writeIRect(r: IRectangleInt) { writeS_VL(r.x) writeS_VL(r.y) writeS_VL(r.width) writeS_VL(r.height) } suspend private fun SyncStream.writeLibrary(lib: AnLibrary, config: Config, externalWriters: ExternalWriters) { writeStringz(AniFile.MAGIC, 8) writeU_VL(AniFile.VERSION) writeU_VL(lib.msPerFrame) writeU_VL(lib.width) writeU_VL(lib.height) writeU_VL( 0 .insert(config.mipmaps, 0) .insert(!config.smoothInterpolation, 1) ) // Allocate Strings val strings = OptimizedStringAllocator() lib.symbolsById.fastForEach { symbol -> strings.add(symbol.name) when (symbol) { is AnSymbolMovieClip -> { for (ss in symbol.states) { strings.add(ss.key) //strings.add(ss.value.state.name) strings.add(ss.value.subTimeline.nextState) for (timeline in ss.value.subTimeline.timelines) { for (entry in timeline.entries) { strings.add(entry.second.name) } } for (action in ss.value.subTimeline.actions.objects) { when (action) { is AnEventAction -> { strings.add(action.event) } } } } } is AnTextFieldSymbol -> { strings.add(symbol.initialHtml) } } } strings.finalize() // String pool writeU_VL(strings.strings.size) for (str in strings.strings.drop(1)) writeStringVL(str!!) // Atlases val atlasBitmaps = listOf( lib.symbolsById.filterIsInstance<AnSymbolShape>().map { it.textureWithBitmap?.bitmapSlice?.bmpBase }, lib.symbolsById.filterIsInstance<AnSymbolMorphShape>().flatMap { it.texturesWithBitmap.entries.map { it.second.bitmapSlice.bmpBase } } ).flatMap { it }.filterNotNull().distinct() val atlasBitmapsToId = atlasBitmaps.withIndex().map { it.value to it.index }.toMap() writeU_VL(atlasBitmaps.size) for ((atlas, index) in atlasBitmapsToId) { externalWriters.writeAtlas(index, atlas) } val soundsToId = lib.symbolsById.filterIsInstance<AnSymbolSound>().withIndex().map { it.value to it.index }.toMap() writeU_VL(soundsToId.size) for ((sound, index) in soundsToId) { externalWriters.writeSound(index, sound.dataBytes ?: byteArrayOf()) } // Symbols var morphShapeCount = 0 var shapeCount = 0 var movieClipCount = 0 var totalFrameCount = 0 var totalTimelines = 0 writeU_VL(lib.symbolsById.size) for (symbol in lib.symbolsById) { writeU_VL(symbol.id) writeU_VL(strings[symbol.name]) when (symbol) { is AnSymbolEmpty -> { writeU_VL(AniFile.SYMBOL_TYPE_EMPTY) } is AnSymbolSound -> { writeU_VL(AniFile.SYMBOL_TYPE_SOUND) writeU_VL(soundsToId[symbol]!!) } is AnTextFieldSymbol -> { writeU_VL(AniFile.SYMBOL_TYPE_TEXT) writeU_VL(strings[symbol.initialHtml]) writeRect(symbol.bounds) } is AnSymbolShape -> { shapeCount++ writeU_VL(AniFile.SYMBOL_TYPE_SHAPE) writeF32LE(symbol.textureWithBitmap!!.scale.toFloat()) writeU_VL(atlasBitmapsToId[symbol.textureWithBitmap!!.bitmapSlice.bmpBase]!!) writeIRect(symbol.textureWithBitmap!!.bitmapSlice.bounds) writeRect(symbol.bounds) val path = symbol.path if (config.keepPaths && path != null) { writeU_VL(1) writeU_VL(path.commands.size) for (cmd in path.commands) write8(cmd) writeU_VL(path.data.size) for (v in path.data) writeF32LE(v.toFloat()) } else { writeU_VL(0) } } is AnSymbolMorphShape -> { morphShapeCount++ writeU_VL(AniFile.SYMBOL_TYPE_MORPH_SHAPE) val entries = symbol.texturesWithBitmap.entries writeU_VL(entries.size) for ((ratio1000, textureWithBitmap) in entries) { writeU_VL(ratio1000) writeF32LE(textureWithBitmap.scale.toFloat()) writeU_VL(atlasBitmapsToId[textureWithBitmap.bitmapSlice.bmpBase]!!) writeRect(textureWithBitmap.bounds) writeIRect(textureWithBitmap.bitmapSlice.bounds) } } is AnSymbolBitmap -> { writeU_VL(AniFile.SYMBOL_TYPE_BITMAP) } is AnSymbolMovieClip -> { movieClipCount++ // val totalDepths: Int, val totalFrames: Int, val totalUids: Int, val totalTime: Int writeU_VL(AniFile.SYMBOL_TYPE_MOVIE_CLIP) val hasNinePatchRect = (symbol.ninePatch != null) write8( 0 .insert(hasNinePatchRect, 0) ) val limits = symbol.limits writeU_VL(limits.totalDepths) writeU_VL(limits.totalFrames) writeU_VL(limits.totalTime.millisecondsInt) // uids writeU_VL(limits.totalUids) for (uidInfo in symbol.uidInfo) { writeU_VL(uidInfo.characterId) writeStringVL(if (uidInfo.extraProps.isNotEmpty()) Json.stringify(uidInfo.extraProps) else "") } val symbolStates = symbol.states.map { it.value.subTimeline }.toList().distinct() val symbolStateToIndex = symbolStates.withIndex().map { it.value to it.index }.toMap() if (hasNinePatchRect) { writeRect(symbol.ninePatch!!) } // states writeU_VL(symbolStates.size) for (ss in symbolStates) { //writeU_VL(strings[ss.name]) writeU_VL(ss.totalTime.microseconds.toInt()) write8(0.insert(ss.nextStatePlay, 0)) writeU_VL(strings[ss.nextState]) var lastFrameTimeMs = 0 //val actionsPerTime = ss.actions.entries.filter { it.second !is AnEventAction }.groupBy { it.first } val actionsPerTime = ss.actions.entries.groupBy { it.first } writeU_VL(actionsPerTime.size) for ((timeInMicro, actions) in actionsPerTime) { val timeInMs = timeInMicro / 1000 writeU_VL(timeInMs - lastFrameTimeMs) // @TODO: Use time deltas and/or frame indices lastFrameTimeMs = timeInMs writeU_VL(actions.size) for (actionInfo in actions) { val action = actionInfo.second when (action) { is AnPlaySoundAction -> { write8(0) writeU_VL(action.soundId) } is AnEventAction -> { write8(1) writeU_VL(strings[action.event]) } else -> TODO() } } } for (timeline in ss.timelines) { totalTimelines++ val frames = timeline.entries var lastUid = -1 var lastName: String? = null var lastColorTransform: ColorTransform = ColorTransform() var lastMatrix: Matrix = Matrix() var lastClipDepth = -1 var lastRatio = 0.0 var lastBlendMode = BlendMode.INHERIT writeU_VL(frames.size) var lastFrameTime = 0 for ((frameTime, frame) in frames) { val storeFrameTime = frameTime / 1000 totalFrameCount++ //println(frameTime) writeU_VL(storeFrameTime - lastFrameTime) // @TODO: Use time deltas and/or frame indices lastFrameTime = storeFrameTime val ct = frame.colorTransform val m = frame.transform val hasUid = frame.uid != lastUid val hasName = frame.name != lastName val hasColorTransform = ct != lastColorTransform val hasBlendMode = frame.blendMode != lastBlendMode val hasAlpha = ( (ct.mR == lastColorTransform.mR) && (ct.mG == lastColorTransform.mG) && (ct.mB == lastColorTransform.mB) && (ct.mA != lastColorTransform.mA) && (ct.aR == lastColorTransform.aR) && (ct.aG == lastColorTransform.aG) && (ct.aB == lastColorTransform.aB) && (ct.aA == lastColorTransform.aA) ) val hasClipDepth = frame.clipDepth != lastClipDepth val hasRatio = frame.ratio != lastRatio val hasMatrix = m != lastMatrix write8( 0 .insert(hasUid, 0) .insert(hasName, 1) .insert(hasColorTransform, 2) .insert(hasMatrix, 3) .insert(hasClipDepth, 4) .insert(hasRatio, 5) .insert(hasAlpha, 6) .insert(hasBlendMode, 7) ) if (hasUid) writeU_VL(frame.uid) if (hasClipDepth) write16LE(frame.clipDepth) if (hasName) writeU_VL(strings[frame.name]) if (hasAlpha) { write8((ct.mA * 255.0).toInt().clamp(0x00, 0xFF)) } else if (hasColorTransform) { val hasMR = ct.mR != lastColorTransform.mR val hasMG = ct.mG != lastColorTransform.mG val hasMB = ct.mB != lastColorTransform.mB val hasMA = ct.mA != lastColorTransform.mA val hasAR = ct.aR != lastColorTransform.aR val hasAG = ct.aG != lastColorTransform.aG val hasAB = ct.aB != lastColorTransform.aB val hasAA = ct.aA != lastColorTransform.aA write8( 0 .insert(hasMR, 0) .insert(hasMG, 1) .insert(hasMB, 2) .insert(hasMA, 3) .insert(hasAR, 4) .insert(hasAG, 5) .insert(hasAB, 6) .insert(hasAA, 7) ) if (hasMR) write8((ct.mR.clamp(0.0, 1.0) * 255.0).toInt()) if (hasMG) write8((ct.mG.clamp(0.0, 1.0) * 255.0).toInt()) if (hasMB) write8((ct.mB.clamp(0.0, 1.0) * 255.0).toInt()) if (hasMA) write8((ct.mA.clamp(0.0, 1.0) * 255.0).toInt()) if (hasAR) write8(ct.aR.clamp(-255, +255) / 2) if (hasAG) write8(ct.aG.clamp(-255, +255) / 2) if (hasAB) write8(ct.aB.clamp(-255, +255) / 2) if (hasAA) write8(ct.aA.clamp(-255, +255) / 2) } if (hasMatrix) { val hasMatrixA = m.a != lastMatrix.a val hasMatrixB = m.b != lastMatrix.b val hasMatrixC = m.c != lastMatrix.c val hasMatrixD = m.d != lastMatrix.d val hasMatrixTX = m.tx != lastMatrix.tx val hasMatrixTY = m.ty != lastMatrix.ty write8( 0 .insert(hasMatrixA, 0) .insert(hasMatrixB, 1) .insert(hasMatrixC, 2) .insert(hasMatrixD, 3) .insert(hasMatrixTX, 4) .insert(hasMatrixTY, 5) ) if (hasMatrixA) writeS_VL((m.a * 16384).toInt()) if (hasMatrixB) writeS_VL((m.b * 16384).toInt()) if (hasMatrixC) writeS_VL((m.c * 16384).toInt()) if (hasMatrixD) writeS_VL((m.d * 16384).toInt()) if (hasMatrixTX) writeS_VL((m.tx * 20).toInt()) if (hasMatrixTY) writeS_VL((m.ty * 20).toInt()) } if (hasRatio) write8((frame.ratio * 255).toInt().clamp(0, 255)) if (hasBlendMode) { write8(frame.blendMode.ordinal) } lastUid = frame.uid lastName = frame.name lastColorTransform = frame.colorTransform lastMatrix = m lastClipDepth = frame.clipDepth lastRatio = frame.ratio lastBlendMode = frame.blendMode } } } // namedStates writeU_VL(symbol.states.size) for ((name, ssi) in symbol.states) { val stateIndex = symbolStateToIndex[ssi.subTimeline] ?: 0 writeU_VL(strings[name]) writeU_VL(ssi.startTime.millisecondsInt) writeU_VL(stateIndex) } } } } if (true) { //println("totalTimelines: $totalTimelines") //println("totalFrameCount: $totalFrameCount") //println("shapeCount: $shapeCount") //println("morphShapeCount: $morphShapeCount") //println("movieClipCount: $movieClipCount") } // End of symbols } }
apache-2.0
9b81db86af5921fbf8de7cc1b2fd10fc
31.291667
137
0.631347
3.225214
false
false
false
false
cashapp/sqldelight
dialects/postgresql/src/main/kotlin/app/cash/sqldelight/dialects/postgresql/PostgreSqlTypeResolver.kt
1
6653
package app.cash.sqldelight.dialects.postgresql import app.cash.sqldelight.dialect.api.DialectType import app.cash.sqldelight.dialect.api.IntermediateType import app.cash.sqldelight.dialect.api.PrimitiveType import app.cash.sqldelight.dialect.api.PrimitiveType.BLOB import app.cash.sqldelight.dialect.api.PrimitiveType.INTEGER import app.cash.sqldelight.dialect.api.PrimitiveType.REAL import app.cash.sqldelight.dialect.api.PrimitiveType.TEXT import app.cash.sqldelight.dialect.api.QueryWithResults import app.cash.sqldelight.dialect.api.TypeResolver import app.cash.sqldelight.dialect.api.encapsulatingType import app.cash.sqldelight.dialects.postgresql.PostgreSqlType.BIG_INT import app.cash.sqldelight.dialects.postgresql.PostgreSqlType.SMALL_INT import app.cash.sqldelight.dialects.postgresql.PostgreSqlType.TIMESTAMP import app.cash.sqldelight.dialects.postgresql.PostgreSqlType.TIMESTAMP_TIMEZONE import app.cash.sqldelight.dialects.postgresql.grammar.psi.PostgreSqlDeleteStmtLimited import app.cash.sqldelight.dialects.postgresql.grammar.psi.PostgreSqlInsertStmt import app.cash.sqldelight.dialects.postgresql.grammar.psi.PostgreSqlTypeName import app.cash.sqldelight.dialects.postgresql.grammar.psi.PostgreSqlUpdateStmtLimited import com.alecstrong.sql.psi.core.psi.SqlAnnotatedElement import com.alecstrong.sql.psi.core.psi.SqlCreateTableStmt import com.alecstrong.sql.psi.core.psi.SqlFunctionExpr import com.alecstrong.sql.psi.core.psi.SqlStmt import com.alecstrong.sql.psi.core.psi.SqlTypeName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.asTypeName class PostgreSqlTypeResolver(private val parentResolver: TypeResolver) : TypeResolver by parentResolver { override fun definitionType(typeName: SqlTypeName): IntermediateType = with(typeName) { check(this is PostgreSqlTypeName) val type = IntermediateType( when { smallIntDataType != null -> PostgreSqlType.SMALL_INT intDataType != null -> PostgreSqlType.INTEGER bigIntDataType != null -> PostgreSqlType.BIG_INT numericDataType != null -> PostgreSqlType.NUMERIC approximateNumericDataType != null -> REAL stringDataType != null -> TEXT uuidDataType != null -> PostgreSqlType.UUID smallSerialDataType != null -> PostgreSqlType.SMALL_INT serialDataType != null -> PostgreSqlType.INTEGER bigSerialDataType != null -> PostgreSqlType.BIG_INT dateDataType != null -> { when (dateDataType!!.firstChild.text) { "DATE" -> PostgreSqlType.DATE "TIME" -> PostgreSqlType.TIME "TIMESTAMP" -> if (dateDataType!!.node.getChildren(null).any { it.text == "WITH" }) TIMESTAMP_TIMEZONE else TIMESTAMP "TIMESTAMPTZ" -> TIMESTAMP_TIMEZONE "INTERVAL" -> PostgreSqlType.INTERVAL else -> throw IllegalArgumentException("Unknown date type ${dateDataType!!.text}") } } jsonDataType != null -> TEXT booleanDataType != null -> PrimitiveType.BOOLEAN blobDataType != null -> BLOB else -> throw IllegalArgumentException("Unknown kotlin type for sql type ${this.text}") }, ) if (node.getChildren(null).map { it.text }.takeLast(2) == listOf("[", "]")) { return IntermediateType( object : DialectType { override val javaType = Array::class.asTypeName().parameterizedBy(type.javaType) override fun prepareStatementBinder(columnIndex: String, value: CodeBlock) = CodeBlock.of("bindObject($columnIndex, %L)\n", value) override fun cursorGetter(columnIndex: Int, cursorName: String) = CodeBlock.of("$cursorName.getArray<%T>($columnIndex)", type.javaType) }, ) } return type } override fun functionType(functionExpr: SqlFunctionExpr): IntermediateType? { return functionExpr.postgreSqlFunctionType() ?: parentResolver.functionType(functionExpr) } private fun SqlFunctionExpr.postgreSqlFunctionType() = when (functionName.text.lowercase()) { "greatest" -> encapsulatingType(exprList, PrimitiveType.INTEGER, REAL, TEXT, BLOB) "concat" -> encapsulatingType(exprList, TEXT) "substring" -> IntermediateType(TEXT).nullableIf(resolvedType(exprList[0]).javaType.isNullable) "coalesce", "ifnull" -> encapsulatingType(exprList, SMALL_INT, PostgreSqlType.INTEGER, INTEGER, BIG_INT, REAL, TEXT, BLOB) "max" -> encapsulatingType(exprList, SMALL_INT, PostgreSqlType.INTEGER, INTEGER, BIG_INT, REAL, TEXT, BLOB).asNullable() "min" -> encapsulatingType(exprList, BLOB, TEXT, SMALL_INT, INTEGER, PostgreSqlType.INTEGER, BIG_INT, REAL).asNullable() "date_trunc" -> encapsulatingType(exprList, TIMESTAMP_TIMEZONE, TIMESTAMP) "now" -> IntermediateType(TIMESTAMP_TIMEZONE) else -> null } override fun queryWithResults(sqlStmt: SqlStmt): QueryWithResults? { sqlStmt.insertStmt?.let { insert -> check(insert is PostgreSqlInsertStmt) insert.returningClause?.let { return object : QueryWithResults { override var statement: SqlAnnotatedElement = insert override val select = it override val pureTable = insert.tableName } } } sqlStmt.updateStmtLimited?.let { update -> check(update is PostgreSqlUpdateStmtLimited) update.returningClause?.let { return object : QueryWithResults { override var statement: SqlAnnotatedElement = update override val select = it override val pureTable = update.qualifiedTableName.tableName } } } sqlStmt.deleteStmtLimited?.let { delete -> check(delete is PostgreSqlDeleteStmtLimited) delete.returningClause?.let { return object : QueryWithResults { override var statement: SqlAnnotatedElement = delete override val select = it override val pureTable = delete.qualifiedTableName?.tableName } } } return parentResolver.queryWithResults(sqlStmt) } override fun simplifyType(intermediateType: IntermediateType): IntermediateType { // Primary key columns are non null always. val columnDef = intermediateType.column ?: return intermediateType val tableDef = columnDef.parent as? SqlCreateTableStmt ?: return intermediateType tableDef.tableConstraintList.forEach { if (columnDef.columnName.name in it.indexedColumnList.mapNotNull { it.columnName?.name }) { return intermediateType.asNonNullable() } } return parentResolver.simplifyType(intermediateType) } }
apache-2.0
05864db7430bccc6d2457fc07dd2c0e5
46.863309
129
0.729295
4.547505
false
true
false
false
wendigo/chrome-reactive-kotlin
src/main/kotlin/pl/wendigo/chrome/api/tracing/Domain.kt
1
11053
package pl.wendigo.chrome.api.tracing import kotlinx.serialization.json.Json /** * TracingDomain represents Tracing protocol domain request/response operations and events that can be captured. * * This API is marked as experimental in protocol definition and can change in the future. * @link Protocol [Tracing](https://chromedevtools.github.io/devtools-protocol/tot/Tracing) domain documentation. */ @pl.wendigo.chrome.protocol.Experimental class TracingDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) : pl.wendigo.chrome.protocol.Domain("Tracing", """""", connection) { /** * Stop trace events collection. * * @link Protocol [Tracing#end](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-end) method documentation. */ fun end(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Tracing.end", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Gets supported tracing categories. * * @link Protocol [Tracing#getCategories](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-getCategories) method documentation. */ fun getCategories(): io.reactivex.rxjava3.core.Single<GetCategoriesResponse> = connection.request("Tracing.getCategories", null, GetCategoriesResponse.serializer()) /** * Record a clock sync marker in the trace. * * @link Protocol [Tracing#recordClockSyncMarker](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-recordClockSyncMarker) method documentation. */ fun recordClockSyncMarker(input: RecordClockSyncMarkerRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Tracing.recordClockSyncMarker", Json.encodeToJsonElement(RecordClockSyncMarkerRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Request a global memory dump. * * @link Protocol [Tracing#requestMemoryDump](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-requestMemoryDump) method documentation. */ fun requestMemoryDump(input: RequestMemoryDumpRequest): io.reactivex.rxjava3.core.Single<RequestMemoryDumpResponse> = connection.request("Tracing.requestMemoryDump", Json.encodeToJsonElement(RequestMemoryDumpRequest.serializer(), input), RequestMemoryDumpResponse.serializer()) /** * Start trace events collection. * * @link Protocol [Tracing#start](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-start) method documentation. */ fun start(input: StartRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Tracing.start", Json.encodeToJsonElement(StartRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Returns observable capturing all Tracing.bufferUsage events. */ fun bufferUsage(): io.reactivex.rxjava3.core.Flowable<BufferUsageEvent> = connection.events("Tracing.bufferUsage", BufferUsageEvent.serializer()) /** * Contains an bucket of collected trace events. When tracing is stopped collected events will be send as a sequence of dataCollected events followed by tracingComplete event. */ fun dataCollected(): io.reactivex.rxjava3.core.Flowable<DataCollectedEvent> = connection.events("Tracing.dataCollected", DataCollectedEvent.serializer()) /** * Signals that tracing is stopped and there is no trace buffers pending flush, all data were delivered via dataCollected events. */ fun tracingComplete(): io.reactivex.rxjava3.core.Flowable<TracingCompleteEvent> = connection.events("Tracing.tracingComplete", TracingCompleteEvent.serializer()) /** * Returns list of dependant domains that should be enabled prior to enabling this domain. */ override fun getDependencies(): List<pl.wendigo.chrome.protocol.Domain> { return arrayListOf( pl.wendigo.chrome.api.io.IODomain(connection), ) } } /** * Represents response frame that is returned from [Tracing#getCategories](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-getCategories) operation call. * Gets supported tracing categories. * * @link [Tracing#getCategories](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-getCategories) method documentation. * @see [TracingDomain.getCategories] */ @kotlinx.serialization.Serializable data class GetCategoriesResponse( /** * A list of supported tracing categories. */ val categories: List<String> ) /** * Represents request frame that can be used with [Tracing#recordClockSyncMarker](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-recordClockSyncMarker) operation call. * * Record a clock sync marker in the trace. * @link [Tracing#recordClockSyncMarker](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-recordClockSyncMarker) method documentation. * @see [TracingDomain.recordClockSyncMarker] */ @kotlinx.serialization.Serializable data class RecordClockSyncMarkerRequest( /** * The ID of this clock sync marker */ val syncId: String ) /** * Represents request frame that can be used with [Tracing#requestMemoryDump](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-requestMemoryDump) operation call. * * Request a global memory dump. * @link [Tracing#requestMemoryDump](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-requestMemoryDump) method documentation. * @see [TracingDomain.requestMemoryDump] */ @kotlinx.serialization.Serializable data class RequestMemoryDumpRequest( /** * Enables more deterministic results by forcing garbage collection */ val deterministic: Boolean? = null, /** * Specifies level of details in memory dump. Defaults to "detailed". */ val levelOfDetail: MemoryDumpLevelOfDetail? = null ) /** * Represents response frame that is returned from [Tracing#requestMemoryDump](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-requestMemoryDump) operation call. * Request a global memory dump. * * @link [Tracing#requestMemoryDump](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-requestMemoryDump) method documentation. * @see [TracingDomain.requestMemoryDump] */ @kotlinx.serialization.Serializable data class RequestMemoryDumpResponse( /** * GUID of the resulting global memory dump. */ val dumpGuid: String, /** * True iff the global memory dump succeeded. */ val success: Boolean ) /** * Represents request frame that can be used with [Tracing#start](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-start) operation call. * * Start trace events collection. * @link [Tracing#start](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-start) method documentation. * @see [TracingDomain.start] */ @kotlinx.serialization.Serializable data class StartRequest( /** * Category/tag filter */ @Deprecated(message = "") val categories: String? = null, /** * Tracing options */ @Deprecated(message = "") val options: String? = null, /** * If set, the agent will issue bufferUsage events at this interval, specified in milliseconds */ val bufferUsageReportingInterval: Double? = null, /** * Whether to report trace events as series of dataCollected events or to save trace to a stream (defaults to `ReportEvents`). */ val transferMode: String? = null, /** * Trace data format to use. This only applies when using `ReturnAsStream` transfer mode (defaults to `json`). */ val streamFormat: StreamFormat? = null, /** * Compression format to use. This only applies when using `ReturnAsStream` transfer mode (defaults to `none`) */ val streamCompression: StreamCompression? = null, /** * */ val traceConfig: TraceConfig? = null, /** * Base64-encoded serialized perfetto.protos.TraceConfig protobuf message When specified, the parameters `categories`, `options`, `traceConfig` are ignored. (Encoded as a base64 string when passed over JSON) */ val perfettoConfig: String? = null ) /** * * * @link [Tracing#bufferUsage](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#event-bufferUsage) event documentation. */ @kotlinx.serialization.Serializable data class BufferUsageEvent( /** * A number in range [0..1] that indicates the used size of event buffer as a fraction of its total size. */ val percentFull: Double? = null, /** * An approximate number of events in the trace log. */ val eventCount: Double? = null, /** * A number in range [0..1] that indicates the used size of event buffer as a fraction of its total size. */ val value: Double? = null ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Tracing" override fun eventName() = "bufferUsage" } /** * Contains an bucket of collected trace events. When tracing is stopped collected events will be send as a sequence of dataCollected events followed by tracingComplete event. * * @link [Tracing#dataCollected](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#event-dataCollected) event documentation. */ @kotlinx.serialization.Serializable data class DataCollectedEvent( /** * */ val value: List<kotlinx.serialization.json.JsonElement> ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Tracing" override fun eventName() = "dataCollected" } /** * Signals that tracing is stopped and there is no trace buffers pending flush, all data were delivered via dataCollected events. * * @link [Tracing#tracingComplete](https://chromedevtools.github.io/devtools-protocol/tot/Tracing#event-tracingComplete) event documentation. */ @kotlinx.serialization.Serializable data class TracingCompleteEvent( /** * Indicates whether some trace data is known to have been lost, e.g. because the trace ring buffer wrapped around. */ val dataLossOccurred: Boolean, /** * A handle of the stream that holds resulting trace data. */ val stream: pl.wendigo.chrome.api.io.StreamHandle? = null, /** * Trace data format of returned stream. */ val traceFormat: StreamFormat? = null, /** * Compression format of returned stream. */ val streamCompression: StreamCompression? = null ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Tracing" override fun eventName() = "tracingComplete" }
apache-2.0
20fb49754d74a5a99fe4f45381e86805
36.85274
361
0.725414
4.361878
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowFlattenDims.kt
1
5100
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute import org.nd4j.ir.OpNamespace import org.nd4j.samediff.frameworkimport.argDescriptorType import org.nd4j.samediff.frameworkimport.findOp import org.nd4j.samediff.frameworkimport.ir.IRAttribute import org.nd4j.samediff.frameworkimport.isNd4jTensorName import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder import org.nd4j.samediff.frameworkimport.process.MappingProcess import org.nd4j.samediff.frameworkimport.rule.MappingRule import org.nd4j.samediff.frameworkimport.rule.attribute.ArgDescriptorConstant import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType import org.nd4j.samediff.frameworkimport.rule.attribute.FlattenDims import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor import org.tensorflow.framework.* @MappingRule("tensorflow","flattendims","attribute") class TensorflowFlattenDims(mappingNamesToPerform: Map<String, String>, transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>) : FlattenDims<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType>(mappingNamesToPerform, transformerArgs) { override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> { return TensorflowIRAttr(inputAttributeValue = attributeValueType, inputAttributeDef = attrDef) } override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> { TODO("Not yet implemented") } override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowTensorName(name, opDef) } override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isNd4jTensorName(name,nd4jOpDescriptor) } override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowAttributeName(name, opDef) } override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isOutputFrameworkAttributeName(name,nd4jOpDescriptor) } override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return argDescriptorType(name,nd4jOpDescriptor) } override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef) } }
apache-2.0
6272cd89fcbf1721e0e86dd01c131202
60.457831
221
0.771569
4.961089
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/utils/StructFieldsExpander.kt
2
5358
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.utils import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.LeafPsiElement import org.rust.ide.annotator.calculateMissingFields import org.rust.ide.utils.template.buildAndRunTemplate import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.knownItems import org.rust.lang.core.resolve.ref.deepResolve import org.rust.openapiext.createSmartPointer fun addMissingFieldsToStructLiteral( factory: RsPsiFactory, editor: Editor?, structLiteral: RsStructLiteral, recursive: Boolean = false ) { val declaration = structLiteral.path.reference?.deepResolve() as? RsFieldsOwner ?: return val body = structLiteral.structLiteralBody val fieldsToAdd = calculateMissingFields(body, declaration) val defaultValueBuilder = RsDefaultValueBuilder(declaration.knownItems, body.containingMod, factory, recursive) val addedFields = defaultValueBuilder.fillStruct( body, declaration.fields, fieldsToAdd, structLiteral.getLocalVariableVisibleBindings() ) editor?.buildAndRunTemplate(body, addedFields.mapNotNull { it.expr?.createSmartPointer() }) } fun expandStructFields(factory: RsPsiFactory, patStruct: RsPatStruct) { val declaration = patStruct.path.reference?.deepResolve() as? RsFieldsOwner ?: return val hasTrailingComma = patStruct.rbrace.getPrevNonCommentSibling()?.elementType == RsElementTypes.COMMA patStruct.patRest?.delete() val existingFields = patStruct.patFieldList val bodyFieldNames = existingFields.map { it.kind.fieldName }.toSet() val missingFields = declaration.fields .filter { it.name !in bodyFieldNames } .map { factory.createPatField(it.name!!.escapeIdentifierIfNeeded()) } if (existingFields.isEmpty()) { addFieldsToPat(factory, patStruct, missingFields, hasTrailingComma) return } val fieldPositions = declaration.fields.withIndex().associate { it.value.name!! to it.index } var insertedFieldsAmount = 0 for (missingField in missingFields) { val missingFieldPosition = fieldPositions[missingField.kind.fieldName]!! for (existingField in existingFields) { val existingFieldPosition = fieldPositions[existingField.kind.fieldName] ?: continue if (missingFieldPosition < existingFieldPosition) { patStruct.addBefore(missingField, existingField) patStruct.addAfter(factory.createComma(), existingField.getPrevNonCommentSibling()) insertedFieldsAmount++ break } } } addFieldsToPat(factory, patStruct, missingFields.drop(insertedFieldsAmount), hasTrailingComma) } fun expandTupleStructFields(factory: RsPsiFactory, editor: Editor?, patTuple: RsPatTupleStruct) { val declaration = patTuple.path.reference?.deepResolve() as? RsFieldsOwner ?: return val hasTrailingComma = patTuple.rparen.getPrevNonCommentSibling()?.elementType == RsElementTypes.COMMA val bodyFields = patTuple.childrenOfType<RsPatIdent>() val missingFieldsAmount = declaration.fields.size - bodyFields.size addFieldsToPat(factory, patTuple, createTupleStructMissingFields(factory, missingFieldsAmount), hasTrailingComma) patTuple.patRest?.delete() editor?.buildAndRunTemplate(patTuple, patTuple.childrenOfType<RsPatBinding>().map { it.createSmartPointer() }) } private fun createTupleStructMissingFields(factory: RsPsiFactory, amount: Int): List<RsPatBinding> { val missingFields = ArrayList<RsPatBinding>(amount) for (i in 0 until amount) { missingFields.add(factory.createPatBinding("_$i")) } return missingFields } private fun addFieldsToPat(factory: RsPsiFactory, pat: RsPat, fields: List<PsiElement>, hasTrailingComma: Boolean) { var anchor = determineOrCreateAnchor(factory, pat) for (missingField in fields) { pat.addAfter(missingField, anchor) // Do not insert comma if we are in the middle of pattern // since it will cause double comma in patterns with a trailing comma. if (fields.last() == missingField) { if (anchor.nextSibling?.getNextNonCommentSibling() !is RsPatRest) { pat.addAfter(factory.createComma(), anchor.nextSibling) } } else { pat.addAfter(factory.createComma(), anchor.nextSibling) } anchor = anchor.nextSibling.nextSibling } if (!hasTrailingComma) { anchor.delete() } } private fun determineOrCreateAnchor(factory: RsPsiFactory, pat: RsPat): PsiElement { val patRest = pat.childrenOfType<RsPatRest>().firstOrNull() if (patRest != null) { // Picking prev sibling of '..' as anchor allows us to fill the pattern starting from '..' position // instead of filling pattern starting from the end. return patRest.getPrevNonCommentSibling()!! } val lastElementInBody = pat.lastChild.getPrevNonCommentSibling()!! return if (lastElementInBody !is LeafPsiElement) { pat.addAfter(factory.createComma(), lastElementInBody) lastElementInBody.nextSibling } else { lastElementInBody } }
mit
54a62e29a33de54be935041493209dfe
42.918033
117
0.724337
4.607051
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/actions/diagnostic/CreateNewGithubIssue.kt
2
6160
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.actions.diagnostic import com.intellij.ide.BrowserUtil import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.Experiments import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.SystemInfo import com.intellij.util.io.URLUtil import org.rust.cargo.project.model.cargoProjects import org.rust.cargo.project.settings.RustProjectSettingsService.MacroExpansionEngine import org.rust.cargo.project.settings.rustSettings import org.rust.cargo.runconfig.hasCargoProject import org.rust.cargo.toolchain.impl.RustcVersion import org.rust.ide.experiments.EnabledInStable import org.rust.ide.experiments.RsExperiments import org.rust.lang.core.psi.isRustFile import org.rust.openapiext.plugin import org.rust.openapiext.virtualFile import kotlin.reflect.full.hasAnnotation import kotlin.reflect.full.memberProperties class CreateNewGithubIssue : DumbAwareAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.project?.hasCargoProject == true } override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val pluginVersion = plugin().version val toolchainVersion = project.cargoProjects.allProjects .asSequence() .mapNotNull { it.rustcInfo?.version } .firstOrNull() ?.displayText val ideNameAndVersion = ideNameAndVersion val os = SystemInfo.getOsNameAndVersion() val macroExpansionState = when (project.rustSettings.macroExpansionEngine) { MacroExpansionEngine.DISABLED -> "disabled" else -> "enabled" } val additionalExperimentalFeatures = additionalExperimentalFeatures val codeSnippet = e.getData(PlatformDataKeys.EDITOR)?.codeExample.orEmpty() val environmentInfo = buildEnvironmentInfo( pluginVersion, toolchainVersion, ideNameAndVersion, os, macroExpansionState, additionalExperimentalFeatures ) val body = ISSUE_TEMPLATE.format(environmentInfo, codeSnippet) val link = "https://github.com/intellij-rust/intellij-rust/issues/new?body=${URLUtil.encodeURIComponent(body)}" BrowserUtil.browse(link) } companion object { private val ISSUE_TEMPLATE = """ <!-- Hello and thank you for the issue! If you would like to report a bug, we have added some points below that you can fill out. Feel free to remove all the irrelevant text to request a new feature. --> ## Environment %s ## Problem description ## Steps to reproduce %s <!-- Please include as much of your codebase as needed to reproduce the error. If the relevant files are large, please provide a link to a public repository or a [Gist](https://gist.github.com/). --> """.trimIndent() private fun buildEnvironmentInfo( pluginVersion: String, toolchainVersion: String?, ideNameAndVersion: String, os: String, macroExpansionState: String, additionalExperimentalFeatures: String?, ): String = """ * **IntelliJ Rust plugin version:** $pluginVersion * **Rust toolchain version:** $toolchainVersion * **IDE name and version:** $ideNameAndVersion * **Operating system:** $os * **Macro expansion:** $macroExpansionState ${additionalExperimentalFeatures?.let { "* **Additional experimental features:** $it" }.orEmpty()} """.trimEnd().trimIndent() private val ideNameAndVersion: String get() { val appInfo = ApplicationInfo.getInstance() val appName = appInfo.fullApplicationName val editionName = ApplicationNamesInfo.getInstance().editionName val ideVersion = appInfo.build.toString() return buildString { append(appName) if (editionName != null) { append(" ") append(editionName) } append(" (") append(ideVersion) append(")") } } /** Collects additional (disabled in stable releases) experimental features enabled by user */ private val additionalExperimentalFeatures: String? get() = with(Experiments.getInstance()) { RsExperiments::class.memberProperties .filterNot { it.hasAnnotation<EnabledInStable>() } .mapNotNull { it.call() as? String } .filter { isFeatureEnabled(it) } .takeIf { it.isNotEmpty() } ?.joinToString(", ") } private val RustcVersion.displayText: String get() = buildString { append(semver.parsedVersion) if (commitHash != null) { append(" (") append(commitHash.take(9)) if (commitDate != null) { append(" ") append(commitDate) } append(")") } append(" ") append(host) } private val Editor.codeExample: String get() { if (document.virtualFile?.isRustFile != true) return "" val selectedCode = selectionModel.selectedText ?: return "" return "```rust\n$selectedCode\n```" } } }
mit
fa358693f6031bf140d61991c279ae93
37.5
128
0.603734
5.446508
false
false
false
false
kiruto/debug-bottle
components/src/main/kotlin/com/exyui/android/debugbottle/components/bubbles/services/__DTBubble.kt
1
2070
package com.exyui.android.debugbottle.components.bubbles.services import android.content.Context import android.content.Intent import com.exyui.android.debugbottle.components.bubbles.__BubbleLayout import com.exyui.android.debugbottle.components.bubbles.__BubblesManager import com.exyui.android.debugbottle.components.bubbles.__OnBubbleStatusChangeCallback /** * Created by yuriel on 9/23/16. */ internal abstract class __DTBubble(protected val bubblesManager: __BubblesManager) { abstract val TAG: String protected var view: __BubbleLayout? = null open val position = Pair(60, 20) private var appContext: Context? = null companion object { val INTENT_ACTION = "com.exyui.android.debugbottle.components.bubbles.services.DTBubble" val KEY_IS_RUNNING = "KEY_IS_RUNNING" val KEY_TAG = "KEY_TAG" } fun create(context: Context): Boolean { if (!bubblesManager.bounded) { return false } else { onCreate(context.applicationContext) return true } } fun destroy(context: Context) { onDestroy(context.applicationContext) } protected open fun onCreate(context: Context) { view = onCreateView(context) view?.attach(position.first, position.second) appContext = context // send a broadcast to notify ui changes notify(appContext?: return) } protected open fun onDestroy(context: Context) { view?.remove() } // Send a broadcast to update ui protected fun notify(context: Context? = appContext) { val intent = Intent(INTENT_ACTION) intent.putExtra(KEY_TAG, TAG) intent.putExtra(KEY_IS_RUNNING, isRunning()) context?.sendBroadcast(intent) } protected fun __BubbleLayout.remove() { bubblesManager.removeBubble(this) } protected fun __BubbleLayout.attach(x: Int, y: Int) { bubblesManager.addBubble(this, x, y) } abstract fun onCreateView(context: Context): __BubbleLayout abstract fun isRunning(): Boolean }
apache-2.0
cbe2f779a46f4a8b6e4e22ded63c8c63
30.861538
96
0.679227
4.303534
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/receivers/NotificationPublisher.kt
1
7237
package com.habitrpg.android.habitica.receivers import android.app.Notification import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.SharedPreferences import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import androidx.core.content.edit import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.TaskRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.extensions.withImmutableFlag import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.helpers.TaskAlarmManager import com.habitrpg.android.habitica.models.tasks.Task import com.habitrpg.android.habitica.models.tasks.TaskType import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.MainActivity import io.reactivex.rxjava3.functions.BiFunction import java.util.Calendar import java.util.Date import java.util.Random import javax.inject.Inject @Suppress("DEPRECATION") // https://gist.github.com/BrandonSmith/6679223 class NotificationPublisher : BroadcastReceiver() { @Inject lateinit var taskRepository: TaskRepository @Inject lateinit var userRepository: UserRepository @Inject lateinit var sharedPreferences: SharedPreferences private var wasInjected = false private var context: Context? = null override fun onReceive(context: Context, intent: Intent) { this.context = context if (!wasInjected) { wasInjected = true HabiticaBaseApplication.userComponent?.inject(this) } var wasInactive = false // Show special notification if user hasn't logged in for a week if (sharedPreferences.getLong("lastAppLaunch", Date().time) < (Date().time - 604800000L)) { wasInactive = true sharedPreferences.edit { putBoolean("preventDailyReminder", true) } } else { TaskAlarmManager.scheduleDailyReminder(context) } val checkDailies = intent.getBooleanExtra(CHECK_DAILIES, false) if (checkDailies) { taskRepository.getTasks(TaskType.DAILY).firstElement().zipWith( userRepository.getUser().firstElement(), BiFunction<List<Task>, User, Pair<List<Task>, User>> { tasks, user -> return@BiFunction Pair(tasks, user) } ).subscribe( { pair -> var showNotifications = false for (task in pair.first) { if (task.checkIfDue()) { showNotifications = true break } } if (showNotifications) { notify(intent, buildNotification(wasInactive, pair.second.authentication?.timestamps?.createdAt)) } }, RxErrorHandler.handleEmptyError() ) } else { notify(intent, buildNotification(wasInactive)) } } private fun notify(intent: Intent, notification: Notification?) { val notificationManager = context?.let { NotificationManagerCompat.from(it) } val id = intent.getIntExtra(NOTIFICATION_ID, 0) notification?.let { notificationManager?.notify(id, it) } } private fun buildNotification(wasInactive: Boolean, registrationDate: Date? = null): Notification? { val thisContext = context ?: return null val notification: Notification val builder = NotificationCompat.Builder(thisContext, "default") builder.setContentTitle(thisContext.getString(R.string.reminder_title)) var notificationText = getRandomDailyTip() if (registrationDate != null) { val registrationCal = Calendar.getInstance() registrationCal.time = registrationDate val todayCal = Calendar.getInstance() val isSameDay = ( registrationCal.get(Calendar.YEAR) == todayCal.get(Calendar.YEAR) && registrationCal.get(Calendar.DAY_OF_YEAR) == todayCal.get(Calendar.DAY_OF_YEAR) ) val isPreviousDay = ( registrationCal.get(Calendar.YEAR) == todayCal.get(Calendar.YEAR) && registrationCal.get(Calendar.DAY_OF_YEAR) == (todayCal.get(Calendar.DAY_OF_YEAR) - 1) ) if (isSameDay) { builder.setContentTitle(thisContext.getString(R.string.same_day_reminder_title)) notificationText = thisContext.getString(R.string.same_day_reminder_text) } else if (isPreviousDay) { builder.setContentTitle(thisContext.getString(R.string.next_day_reminder_title)) notificationText = thisContext.getString(R.string.next_day_reminder_text) } } if (wasInactive) { builder.setContentText(thisContext.getString(R.string.week_reminder_title)) notificationText = thisContext.getString(R.string.week_reminder_text) } builder.setStyle(NotificationCompat.BigTextStyle().bigText(notificationText)) builder.setSmallIcon(R.drawable.ic_gryphon_white) val notificationIntent = Intent(thisContext, MainActivity::class.java) notificationIntent.putExtra("notificationIdentifier", "daily_reminder") notificationIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val intent = PendingIntent.getActivity( thisContext, 0, notificationIntent, withImmutableFlag(0) ) builder.setContentIntent(intent) builder.color = ContextCompat.getColor(thisContext, R.color.brand_300) notification = builder.build() notification.defaults = notification.defaults or Notification.DEFAULT_LIGHTS notification.flags = notification.flags or (Notification.FLAG_AUTO_CANCEL or Notification.FLAG_SHOW_LIGHTS) return notification } private fun getRandomDailyTip(): String { val thisContext = context ?: return "" val index = Random().nextInt(4) return when (index) { 0 -> thisContext.getString(R.string.daily_tip_0) 1 -> thisContext.getString(R.string.daily_tip_1) 2 -> thisContext.getString(R.string.daily_tip_2) 3 -> thisContext.getString(R.string.daily_tip_3) 4 -> thisContext.getString(R.string.daily_tip_4) 5 -> thisContext.getString(R.string.daily_tip_5) 6 -> thisContext.getString(R.string.daily_tip_6) 7 -> thisContext.getString(R.string.daily_tip_7) 8 -> thisContext.getString(R.string.daily_tip_8) 9 -> thisContext.getString(R.string.daily_tip_9) else -> "" } } companion object { var NOTIFICATION_ID = "notification-id" var CHECK_DAILIES = "check-dailies" } }
gpl-3.0
aaa9a8c9a8dc846a12b5bb81b9df406a
41.822485
121
0.65856
4.789543
false
false
false
false
wealthfront/magellan
magellan-sample-advanced/src/main/java/com/wealthfront/magellan/sample/advanced/paymentinfo/PaymentMethodSelectionStep.kt
1
1370
package com.wealthfront.magellan.sample.advanced.paymentinfo import android.content.Context import com.wealthfront.magellan.core.Step import com.wealthfront.magellan.sample.advanced.R import com.wealthfront.magellan.sample.advanced.databinding.PaymentMethodMenuBinding class PaymentMethodSelectionStep( private val paymentMethodJourney: PaymentInfoJourney ) : Step<PaymentMethodMenuBinding>(PaymentMethodMenuBinding::inflate) { private lateinit var creditCardSelected: () -> Unit override fun onShow(context: Context, binding: PaymentMethodMenuBinding) { when (paymentMethodJourney.paymentMethod) { is PaymentMethod.CreditCard -> { val cardNumber = (paymentMethodJourney.paymentMethod!! as PaymentMethod.CreditCard).cardNumber binding.creditCard.text = "Use existing card $cardNumber" creditCardSelected = { paymentMethodJourney.paymentMethodCollected(paymentMethodJourney.paymentMethod!!) } } null -> { binding.creditCard.text = "Add new credit card" creditCardSelected = { binding.paymentMethodMenu.clearCheck() paymentMethodJourney.goToCreditCardDetails() } } } binding.paymentMethodMenu.setOnCheckedChangeListener { _, checkedId -> if (checkedId == R.id.creditCard) { creditCardSelected() } } } }
apache-2.0
43d9a9eeeb6f8203639552e67206ecbc
34.128205
91
0.725547
5.150376
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/timeline/ViewItem.kt
1
4123
/* * Copyright (c) 2017 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.timeline import android.content.Context import android.database.Cursor import org.andstatus.app.R import org.andstatus.app.actor.ActorsLoader import org.andstatus.app.context.MyContext import org.andstatus.app.origin.Origin import org.andstatus.app.timeline.meta.Timeline import org.andstatus.app.timeline.meta.TimelineType import org.andstatus.app.util.IsEmpty import org.andstatus.app.util.MyStringBuilder import org.andstatus.app.util.RelativeTime import org.andstatus.app.util.StringUtil import java.util.* open class ViewItem<T : ViewItem<T>> protected constructor(private val isEmptyIn: Boolean, val updatedDate: Long) : IsEmpty { private val children: MutableList<T> = ArrayList() private var parent: ViewItem<*>? = EmptyViewItem.EMPTY protected var insertedDate: Long = 0 open fun getId(): Long { return 0 } open fun getDate(): Long { return 0 } fun getChildren(): MutableCollection<T> { return children } open fun duplicates(timeline: Timeline, preferredOrigin: Origin, other: T): DuplicationLink { return DuplicationLink.NONE } val isCollapsed: Boolean get() = childrenCount > 0 fun collapse(child: T) { getChildren().addAll(child.getChildren()) child.getChildren().clear() getChildren().add(child) } open fun fromCursor(myContext: MyContext, cursor: Cursor): T { return getEmpty(TimelineType.UNKNOWN) } open fun matches(filter: TimelineFilter): Boolean { return true } override val isEmpty: Boolean get() = isEmptyIn protected val childrenCount: Int get() = if (isEmpty) 0 else Integer.max(getParent().childrenCount, getChildren().size) fun setParent(parent: ViewItem<*>?) { this.parent = parent } fun getParent(): ViewItem<*> { return parent ?: EmptyViewItem.EMPTY } fun getTopmostId(): Long { return if (getParent().isEmpty) getId() else getParent().getId() } protected fun getMyStringBuilderWithTime(context: Context, showReceivedTime: Boolean): MyStringBuilder { val difference = RelativeTime.getDifference(context, updatedDate) val builder: MyStringBuilder = MyStringBuilder.of(difference) if (showReceivedTime && updatedDate > RelativeTime.SOME_TIME_AGO && insertedDate > updatedDate) { val receivedDifference = RelativeTime.getDifference(context, insertedDate) if (receivedDifference != difference) { builder.withSpace("(" + StringUtil.format(context, R.string.received_sometime_ago, receivedDifference) + ")") } } return builder } open fun addActorsToLoad(loader: ActorsLoader) { // Empty } open fun setLoadedActors(loader: ActorsLoader) { // Empty } override fun hashCode(): Int { val result = java.lang.Long.hashCode(getId()) return 31 * result + java.lang.Long.hashCode(getDate()) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val that = other as T return getId() == that.getId() && getDate() == that.getDate() } companion object { fun <T : ViewItem<T>> getEmpty(timelineType: TimelineType): T { return ViewItemType.fromTimelineType(timelineType).emptyViewItem as T } } }
apache-2.0
2f4d897a87d45155d6355ac6c4e7e601
32.795082
125
0.677662
4.481522
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/lang/type/LuaString.kt
2
1965
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.lang.type import java.util.regex.Pattern /** * * Created by tangzx on 2016/12/25. */ class LuaString { var start: Int = 0 var end: Int = 0 var value = "" val length: Int get() = end - start companion object { /** * 获取 lua 字符串的内容, * "value" * 'value' * [[value]] * @param text string element * @return value of String */ fun getContent(text: String): LuaString { val content = LuaString() if (text.startsWith("[")) { val pattern = Pattern.compile("\\[(=*)\\[([\\s\\S]*)]\\1]") val matcher = pattern.matcher(text) if (matcher.find()) { val contentString = matcher.group(2) content.start = matcher.start(2) content.end = matcher.end(2) content.value = contentString } } else { content.start = 1 content.end = text.length - 1 if (content.end > content.start) content.value = text.substring(content.start, content.end) else content.end = content.start } return content } } }
apache-2.0
38fec534a729a61a52c22526d207b6a5
28.953846
78
0.548023
4.288546
false
false
false
false
world-federation-of-advertisers/panel-exchange-client
src/main/kotlin/org/wfanet/panelmatch/common/beam/Minus.kt
1
1612
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.common.beam import org.apache.beam.sdk.transforms.PTransform import org.apache.beam.sdk.values.PCollection import org.apache.beam.sdk.values.PCollectionList /** * Finds items in a PCollection which do not exist in another PCollection. Keep this as a PTransform * for Scala compatibility. */ class Minus<T : Any> : PTransform<PCollectionList<T>, PCollection<T>>() { override fun expand(input: PCollectionList<T>): PCollection<T> { val items: List<PCollection<T>> = input.all require(items.size == 2) { "Found ${items.size} elements. Only PCollection with 2 elements is allowed." } val firstItems = items[0] val otherItems = items[1] return firstItems .map("MapLeft") { kvOf(it, 1) } .join(otherItems.map("MapRight") { kvOf(it, 2) }, "Join") { key: T, lefts: Iterable<Int>, rights: Iterable<Int> -> if (lefts.iterator().hasNext() && !rights.iterator().hasNext()) yield(key) } } }
apache-2.0
565114cd5e51595cb051c15229a1eef5
36.488372
100
0.698511
3.740139
false
false
false
false
GavinThePacMan/daysuntil
app/src/main/kotlin/com/gpacini/daysuntil/data/images/ImageHelper.kt
2
2508
package com.gpacini.daysuntil.data.images import android.content.ContentResolver import android.graphics.Bitmap import android.net.Uri import android.provider.MediaStore import rx.Observable import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream /** * Created by gavinpacini on 10/10/15. * * A simple helper class which makes interfacing with the file system for event images easier */ class ImageHelper { companion object Factory { private val instanceImageHelper: ImageHelper by lazy { ImageHelper() } fun getInstance(): ImageHelper { return instanceImageHelper } } var filePath: String? = null fun init(filePath: String) { this.filePath = filePath } fun with(uuid: String?): String { return "file://${filePath}/${uuid}.jpg" } fun withCrop(uuid: String?): String { return "file://${filePath}/${uuid}_crop.jpg" } fun getBitmap(contentResolver: ContentResolver, fullImageLocation: Uri?) : Observable<Bitmap> { return Observable.fromCallable { MediaStore.Images.Media.getBitmap(contentResolver, fullImageLocation) } } fun saveImage(bmp: Bitmap?, bmpCrop: Bitmap?, uuid: String?) : Observable<Boolean> { return Observable.fromCallable { val folder = File(filePath) val imageFile = File(filePath + "/${uuid}.jpg") val imageFileCrop = File(filePath + "/${uuid}_crop.jpg") if (!folder.exists()) { folder.mkdir() } if (!imageFile.exists()) { imageFile.createNewFile() } if (!imageFileCrop.exists()) { imageFileCrop.createNewFile() } FileOutputStream(imageFile).use { bmp?.compress(Bitmap.CompressFormat.JPEG, 85, it) } FileOutputStream(imageFileCrop).use { bmpCrop?.compress(Bitmap.CompressFormat.JPEG, 85, it) } } } fun deleteImage(uuid: String?) : Observable<Boolean> { return Observable.fromCallable { val imageFile = File(filePath + "/${uuid}.jpg") val imageFileCrop = File(filePath + "/${uuid}_crop.jpg") if (!imageFile.exists() || !imageFileCrop.exists()){ throw FileNotFoundException() } imageFile.delete() && imageFileCrop.delete() } } }
apache-2.0
584b5f064a9340b909eef6cbfb361b98
26.877778
99
0.595694
4.841699
false
false
false
false
stfalcon-studio/uaroads_android
app/src/main/java/com/stfalcon/new_uaroads_android/common/database/models/TrackRealm.kt
1
1308
/* * Copyright (c) 2017 stfalcon.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stfalcon.new_uaroads_android.common.database.models import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey /* * Created by Anton Bevza on 4/25/17. */ open class TrackRealm : RealmObject() { companion object { val STATUS_NOT_SENT = 0 val STATUS_SENT = 1 val STATUS_IS_RECODING = 2 val STATUS_IS_SENDING = 3 } @PrimaryKey open var id: String = "" open var distance = 0 open var timestamp: Long = 0 open var comment: String? = null open var status = STATUS_IS_RECODING open var points: RealmList<PointRealm> = RealmList() open var autoRecord: Int = 0 }
apache-2.0
175ad51dbe4ba872c7ed23c8c8041d32
28.066667
78
0.683486
3.881306
false
false
false
false
wax911/AniTrendApp
app/src/main/java/com/mxt/anitrend/view/activity/index/LoginActivity.kt
1
8897
package com.mxt.anitrend.view.activity.index import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.work.Data import androidx.work.OneTimeWorkRequest import androidx.work.WorkInfo import androidx.work.WorkManager import com.mxt.anitrend.R import com.mxt.anitrend.base.custom.activity.ActivityBase import com.mxt.anitrend.base.custom.async.WebTokenRequest import com.mxt.anitrend.databinding.ActivityLoginBinding import com.mxt.anitrend.model.api.retro.WebFactory import com.mxt.anitrend.model.entity.anilist.User import com.mxt.anitrend.presenter.base.BasePresenter import com.mxt.anitrend.presenter.widget.WidgetPresenter import com.mxt.anitrend.util.* import com.mxt.anitrend.util.graphql.GraphUtil import com.mxt.anitrend.worker.AuthenticatorWorker import timber.log.Timber /** * Created by max on 2017/11/03. * Authentication activity */ class LoginActivity : ActivityBase<User, BasePresenter>(), View.OnClickListener { private lateinit var binding: ActivityLoginBinding private var model: User? = null private val workInfoObserver = Observer<WorkInfo> { workInfo -> if (workInfo != null && workInfo.state.isFinished) { val outputData = workInfo.outputData if (outputData.getBoolean(KeyUtil.arg_model, false)) { viewModel.params.putParcelable(KeyUtil.arg_graph_params, GraphUtil.getDefaultQuery(false)) viewModel.requestData(KeyUtil.USER_CURRENT_REQ, applicationContext) } else { if (!TextUtils.isEmpty(outputData.getString(KeyUtil.arg_uri_error)) && !TextUtils.isEmpty(outputData.getString(KeyUtil.arg_uri_error_description))) NotifyUtil.createAlerter(this@LoginActivity, outputData.getString(KeyUtil.arg_uri_error)!!, outputData.getString(KeyUtil.arg_uri_error_description)!!, R.drawable.ic_warning_white_18dp, R.color.colorStateOrange, KeyUtil.DURATION_LONG) else NotifyUtil.createAlerter(this@LoginActivity, R.string.login_error_title, R.string.text_error_auth_login, R.drawable.ic_warning_white_18dp, R.color.colorStateRed, KeyUtil.DURATION_LONG) binding.widgetFlipper.showPrevious() } } } /** * Some activities may have custom themes and if that's the case * override this method and set your own theme style, also if you wish * to apply the default navigation bar style for light themes * @see ActivityBase.configureActivity */ override fun configureActivity() { setTheme(if (CompatUtil.isLightTheme(Settings(this).theme)) R.style.AppThemeLight_Translucent else R.style.AppThemeDark_Translucent) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_login) setPresenter(BasePresenter(applicationContext)) setViewModel(true) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) binding.onClickListener = this onActivityReady() } /** * Make decisions, check for permissions or fire background threads from this method * N.B. Must be called after onPostCreate */ override fun onActivityReady() { if (presenter.settings.isAuthenticated) finish() else checkNewIntent(intent) } override fun updateUI() { if (presenter.settings.isNotificationEnabled) JobSchedulerUtil.scheduleJob(applicationContext) createApplicationShortcuts() finish() } private fun createApplicationShortcuts() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { val SHORTCUT_MY_ANIME_BUNDLE = Bundle() SHORTCUT_MY_ANIME_BUNDLE.putString(KeyUtil.arg_mediaType, KeyUtil.ANIME) SHORTCUT_MY_ANIME_BUNDLE.putString(KeyUtil.arg_userName, model?.name) val SHORTCUT_MY_MANGA_BUNDLE = Bundle() SHORTCUT_MY_MANGA_BUNDLE.putString(KeyUtil.arg_mediaType, KeyUtil.MANGA) SHORTCUT_MY_MANGA_BUNDLE.putString(KeyUtil.arg_userName, model?.name) val SHORTCUT_PROFILE_BUNDLE = Bundle() SHORTCUT_PROFILE_BUNDLE.putString(KeyUtil.arg_userName, model?.name) ShortcutUtil.createShortcuts(this@LoginActivity, ShortcutUtil.ShortcutBuilder() .setShortcutType(KeyUtil.SHORTCUT_NOTIFICATION) .build(), ShortcutUtil.ShortcutBuilder() .setShortcutType(KeyUtil.SHORTCUT_MY_ANIME) .setShortcutParams(SHORTCUT_MY_ANIME_BUNDLE) .build(), ShortcutUtil.ShortcutBuilder() .setShortcutType(KeyUtil.SHORTCUT_MY_MANGA) .setShortcutParams(SHORTCUT_MY_MANGA_BUNDLE) .build(), ShortcutUtil.ShortcutBuilder() .setShortcutType(KeyUtil.SHORTCUT_PROFILE) .setShortcutParams(SHORTCUT_PROFILE_BUNDLE) .build()) } } override fun makeRequest() { } override fun onChanged(model: User?) { this.model = model if (isAlive && model != null) { presenter.database.currentUser = model updateUI() } } override fun onClick(view: View) { when (view.id) { R.id.auth_sign_in -> if (binding.widgetFlipper.displayedChild == WidgetPresenter.CONTENT_STATE) { binding.widgetFlipper.showNext() try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(WebFactory.API_AUTH_LINK))) } catch (e: Exception) { e.printStackTrace() Timber.tag(TAG).e(e.localizedMessage) NotifyUtil.makeText(this, R.string.text_unknown_error, Toast.LENGTH_SHORT).show() } } else NotifyUtil.makeText(this, R.string.busy_please_wait, Toast.LENGTH_SHORT).show() R.id.container -> if (binding.widgetFlipper.displayedChild != WidgetPresenter.LOADING_STATE) finish() else NotifyUtil.makeText(this, R.string.busy_please_wait, Toast.LENGTH_SHORT).show() } } override fun showError(error: String) { if (isAlive) { WebTokenRequest.invalidateInstance(applicationContext) NotifyUtil.createAlerter(this, getString(R.string.text_error_auth_login), error, R.drawable.ic_warning_white_18dp, R.color.colorStateRed, KeyUtil.DURATION_LONG) binding.widgetFlipper.showPrevious() Timber.tag(TAG).e(error) } } override fun showEmpty(message: String) { if (isAlive) { WebTokenRequest.invalidateInstance(applicationContext) NotifyUtil.createAlerter(this, getString(R.string.text_error_auth_login), message, R.drawable.ic_warning_white_18dp, R.color.colorStateOrange, KeyUtil.DURATION_LONG) binding.widgetFlipper.showPrevious() Timber.tag(TAG).w(message) } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) if (!presenter.settings.isAuthenticated) checkNewIntent(intent) } private fun checkNewIntent(intent: Intent?) { if (intent != null && intent.data != null) { if (isAlive) { if (binding.widgetFlipper.displayedChild == WidgetPresenter.CONTENT_STATE) binding.widgetFlipper.showNext() val workerInputData = Data.Builder() .putString(KeyUtil.arg_model, intent.data.toString()) .build() val authenticatorWorker = OneTimeWorkRequest.Builder(AuthenticatorWorker::class.java) .addTag(KeyUtil.WorkAuthenticatorTag) .setInputData(workerInputData) .build() WorkManager.getInstance(applicationContext).enqueue(authenticatorWorker) WorkManager.getInstance(applicationContext).getWorkInfoByIdLiveData(authenticatorWorker.id) .observe(this, workInfoObserver) } } } }
lgpl-3.0
14ac1e99302b3361be9d6cc1944660d3
40.189815
163
0.630774
4.719894
false
false
false
false
BrandonWilliamsCS/DulyNoted-Android
DulyNoted/app/src/main/java/com/brandonwilliamscs/dulynoted/view/components/ResponseAreaSpec.kt
1
2399
package com.brandonwilliamscs.dulynoted.view.components import com.brandonwilliamscs.dulynoted.R import com.brandonwilliamscs.dulynoted.model.Guess import com.brandonwilliamscs.dulynoted.model.music.PitchClass import com.brandonwilliamscs.dulynoted.util.conditionally import com.brandonwilliamscs.dulynoted.view.components.keyboard.Keyboard import com.brandonwilliamscs.dulynoted.view.events.KeyPressEvent import com.brandonwilliamscs.dulynoted.view.events.UserIntent import com.brandonwilliamscs.dulynoted.view.events.UserIntentEvent import com.facebook.litho.ComponentContext import com.facebook.litho.ComponentLayout import com.facebook.litho.EventHandler import com.facebook.litho.Row import com.facebook.litho.annotations.* import com.facebook.yoga.YogaAlign import com.facebook.yoga.YogaJustify /** * Displays the "response" part of a flashcard. This may be any supported format. * Created by Brandon on 9/15/2017. */ @LayoutSpec(events = arrayOf(UserIntentEvent::class), isPureRender = true) class ResponseAreaSpec { companion object { @JvmStatic @OnCreateLayout fun onCreateLayout(c: ComponentContext, @Prop(optional = true) currentGuess: Guess?): ComponentLayout = Row.create(c) .child(Keyboard.create(c) .startPitchClass(PitchClass.C) .conditionally(currentGuess != null) { val colorRes = if (currentGuess!!.isCorrect) R.color.correctAnswer else R.color.incorrectAnswer keyHighlight(Pair(currentGuess!!.value, colorRes)) } .count(12) .keyPressHandler(ResponseArea.onKeyPress(c)) .withLayout() .heightPercent(100f)) .justifyContent(YogaJustify.CENTER) .alignItems(YogaAlign.FLEX_END) .build() @JvmStatic @OnEvent(KeyPressEvent::class) fun onKeyPress( @Suppress("UNUSED_PARAMETER") c: ComponentContext, @Prop userIntentHandler: EventHandler<UserIntentEvent>, @FromEvent pitchClass: PitchClass ) { ResponseArea.dispatchUserIntentEvent( userIntentHandler, UserIntent.GuessAnswer(pitchClass) ) } } }
apache-2.0
b3c9bafc1260339d670d0e7000fca0e3
41.087719
123
0.657357
4.346014
false
false
false
false
elect86/jAssimp
src/main/kotlin/assimp/format/config.kt
2
34540
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2017, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package assimp.format import assimp.AiMatrix4x4 /** ########################################################################### * LIBRARY SETTINGS * General, global settings * ########################################################################### */ object AiConfig { /** @brief Enables time measurements. * * If enabled, measures the time needed for each part of the loading process (i.e. IO time, importing, * postprocessing, ..) and dumps these timings to the DefaultLogger. See the @link perf Performance * Page@endlink for more information on this topic. * * Property type: bool. Default value: false. */ val GLOB_MEASURE_TIME = "GLOB_MEASURE_TIME" /** @brief A hint to assimp to favour speed against import quality. * * Enabling this option may result in faster loading, but it needn't. * It represents just a hint to loaders and post-processing steps to use faster code paths, if possible. * This property is expected to be an integer, != 0 stands for true. The default value is 0. */ val FAVOUR_SPEED = "FAVOUR_SPEED" /** @brief Specifies whether the Android JNI asset extraction is supported. * * Turn on this option if you want to manage assets in native Android application without having to keep * the internal directory and asset manager pointer. */ val ANDROID_JNI_ASSIMP_MANAGER_SUPPORT = false /** @brief Specifies the xfile use double for real values of float * * Property type: Bool. Default value: false. */ val EXPORT_XFILE_64BIT = false /** ########################################################################### * POST PROCESSING SETTINGS * valious stuff to fine-tune the behavior of a specific post processing step. * ########################################################################### */ object PP { /** @brief Maximum bone count per mesh for the SplitbyBoneCount step. * * Meshes are split until the maximum number of bones is reached. The default * value is AI_SBBC_DEFAULT_MAX_BONES, which may be altered at * compile-time. * Property data type: integer. */ val SBBC_MAX_BONES = "PP_SBBC_MAX_BONES" object CT { /** @brief Specifies the maximum angle that may be between two vertex tangents that their tangents and * bi-tangents are smoothed. * * This applies to the CalcTangentSpace-Step. The angle is specified in degrees. The maximum value is 175. * Property type: float. Default value: 45 degrees */ val MAX_SMOOTHING_ANGLE = "PP_CT_MAX_SMOOTHING_ANGLE" /** @brief Source UV channel for tangent space computation. * * The specified channel must exist or an error will be raised. * Property type: integer. Default value: 0 */ val TEXTURE_CHANNEL_INDEX = "PP_CT_TEXTURE_CHANNEL_INDEX" } /** @brief Specifies the maximum angle that may be between two face normals at the same vertex position * that their are smoothed together. * * Sometimes referred to as 'crease angle'. * This applies to the GenSmoothNormals-Step. The angle is specified in degrees, so 180 is PI. * The default value is 175 degrees (all vertex normals are smoothed). The maximum value is 175, too. * Property type: float. * Warning: setting this option may cause a severe loss of performance. The performance is unaffected if * the AI_CONFIG_FAVOUR_SPEED flag is set but the output quality may be reduced. */ val GSN_MAX_SMOOTHING_ANGLE = "PP_GSN_MAX_SMOOTHING_ANGLE" /** @brief Configures the #aiProcess_RemoveRedundantMaterials step to keep materials matching a name in * a given list. * * This is a list of 1 to n strings, ' ' serves as delimiter character. * Identifiers containing whitespaces must be enclosed in *single* quotation marks. For example:<tt> * "keep-me and_me_to anotherMaterialToBeKept \'name with whitespace\'"</tt>. * If a material matches on of these names, it will not be modified or removed by the postprocessing step * nor will other materials be replaced by a reference to it. <br> * This option might be useful if you are using some magic material names to pass additional semantics through * the content pipeline. This ensures they won't be optimized away, but a general optimization is still * performed for materials not contained in the list. * Property type: String. Default value: n/a * @note Linefeeds, tabs or carriage returns are treated as whitespace. * Material names are case sensitive. */ val RRM_EXCLUDE_LIST = "PP_RRM_EXCLUDE_LIST" object PTV { /** @brief Configures the AiProcess_PreTransformVertices step to keep the scene hierarchy. Meshes are moved * to worldspace, but no optimization is performed (read: meshes with equal materials are not joined. * The total number of meshes won't change). * * This option could be of use for you if the scene hierarchy contains important additional information which * you intend to parse. * For rendering, you can still render all meshes in the scene without any transformations. * Property type: bool. Default value: false. */ val KEEP_HIERARCHY = "PP_PTV_KEEP_HIERARCHY" /** @brief Configures the AiProcess_PreTransformVertices step to normalize all vertex components into * the [-1, 1] range. That is, a bounding box for the whole scene is computed, the maximum component is taken * and all meshes are scaled appropriately (uniformly of course!). * This might be useful if you don't know the spatial dimension of the input data */ val NORMALIZE = "PP_PTV_NORMALIZE" /** @brief Configures the #aiProcess_PreTransformVertices step to use a users defined matrix as the scene root * node transformation before transforming vertices. * Property type: bool. Default value: false. */ val ADD_ROOT_TRANSFORMATION = "PP_PTV_ADD_ROOT_TRANSFORMATION" /** @brief Configures the AiProcess_PreTransformVertices step to use a users defined matrix as the scene root * node transformation before transforming vertices. This property correspond to the 'a1' component * of the transformation matrix. * Property type: aiMatrix4x4. */ val ROOT_TRANSFORMATION = "PP_PTV_ROOT_TRANSFORMATION" } /** @brief Configures the AiProcess_FindDegenerates step to remove degenerated primitives from * the import - immediately. * * The default behaviour converts degenerated triangles to lines and degenerated lines to points. * See the documentation to the AiProcess_FindDegenerates step for a detailed example of the valious ways * to get rid of these lines and points if you don't want them. * Property type: bool. Default value: false. */ val FD_REMOVE = "PP_FD_REMOVE" /** @brief Configures the #aiProcess_OptimizeGraph step to preserve nodes matching a name in a given list. * * This is a list of 1 to n strings, ' ' serves as delimiter character. * Identifiers containing whitespaces must be enclosed in *single* quotation marks. For example:<tt> * "keep-me and_me_to anotherNodeToBeKept \'name with whitespace\'"</tt>. * If a node matches on of these names, it will not be modified or removed by the postprocessing step.<br> * This option might be useful if you are using some magic node names to pass additional semantics through * the content pipeline. This ensures they won't be optimized away, but a general optimization is still * performed for nodes not contained in the list. * Property type: String. Default value: n/a * @note Linefeeds, tabs or carriage returns are treated as whitespace. Node names are case sensitive. */ val OG_EXCLUDE_LIST = "PP_OG_EXCLUDE_LIST" object SLM { /** @brief Set the maximum number of triangles in a mesh. * * This is used by the "SplitLargeMeshes" PostProcess-Step to determine whether a mesh must be split or not. * @note The default value is 1_000_000. Property type: integer. */ val TRIANGLE_LIMIT = "PP_SLM_TRIANGLE_LIMIT" /** @brief Set the maximum number of vertices in a mesh. * * This is used by the "SplitLargeMeshes" PostProcess-Step to determine whether a mesh must be split or not. * @note The default value is 1_000_000. Property type: integer. */ val VERTEX_LIMIT = "PP_SLM_VERTEX_LIMIT" } /** @brief Set the maximum number of bones affecting a single vertex * * This is used by the #aiProcess_LimitBoneWeights PostProcess-Step. * @note The default value is 0x4 * Property type: integer.*/ val LBW_MAX_WEIGHTS = "PP_LBW_MAX_WEIGHTS" /** @brief Lower the deboning threshold in order to remove more bones. * * This is used by the #aiProcess_Debone PostProcess-Step. * @note The default value is 1f * Property type: float.*/ val DB_THRESHOLD = "PP_DB_THRESHOLD" /** @brief Require all bones qualify for deboning before removing any * * This is used by the #aiProcess_Debone PostProcess-Step. * @note The default value is 0 * Property type: bool.*/ val DB_ALL_OR_NONE = "PP_DB_ALL_OR_NONE" /** @brief Set the size of the post-transform vertex cache to optimize the vertices for. * This configures the AiProcess_ImproveCacheLocality step. * * The size is given in vertices. Of course you can't know how the vertex format will exactly look like after * the import returns, but you can still guess what your meshes will probably have. * @note The default value is 12. That results in slight performance improvements for most nVidia/AMD cards * since 2002. * Property type: integer. */ val ICL_PTCACHE_SIZE = "PP_ICL_PTCACHE_SIZE" /** @brief Enumerates components of the aiScene and aiMesh data structures that can be excluded from the import * using the AiProcess_RemoveComponent step. * * See the documentation to AiProcess_RemoveComponent for more details. */ enum class AiComponent(val i: Int) { /** Normal vectors */ NORMALS(0x2), /** Tangents and bitangents go always together ... */ TANGENTS_AND_BITANGENTS(0x4), /** ALL color sets * Use aiComponent_COLORn(N) to specify the N'th set */ COLORS(0x8), /** ALL texture UV sets * aiComponent_TEXCOORDn(N) to specify the N'th set */ TEXCOORDS(0x10), /** Removes all bone weights from all meshes. * The scenegraph nodes corresponding to the bones are NOT removed. * use the AiProcess_OptimizeGraph step to do this */ BONEWEIGHTS(0x20), /** Removes all node animations (aiScene::mAnimations). * The corresponding scenegraph nodes are NOT removed. * use the AiProcess_OptimizeGraph step to do this */ ANIMATIONS(0x40), /** Removes all embedded textures (aiScene::mTextures) */ TEXTURES(0x80), /** Removes all light sources (aiScene::mLights). * The corresponding scenegraph nodes are NOT removed. * use the #aiProcess_OptimizeGraph step to do this */ LIGHTS(0x100), /** Removes all cameras (aiScene::mCameras). * The corresponding scenegraph nodes are NOT removed. * use the #aiProcess_OptimizeGraph step to do this */ CAMERAS(0x200), /** Removes all meshes (aiScene::mMeshes). */ MESHES(0x400), /** Removes all materials. One default material will be generated, so aiScene::mNumMaterials will be 1. */ MATERIALS(0x800); companion object { /** Remove a specific color channel 'n' */ fun COLORSn(n: Int) = 1 shl (n + 20) /** Remove a specific UV channel 'n' */ fun TEXCOORDSn(n: Int) = 1 shl (n + 25) } } /** @brief Input parameter to the #aiProcess_RemoveComponent step: * Specifies the parts of the data structure to be removed. * * See the documentation to this step for further details. The property is expected to be an integer, * a bitwise combination of the AiComponent flags defined above in this header. The default value is 0. * Important: if no valid mesh is remaining after the step has been executed (e.g you thought it was funny * to specify ALL of the flags defined above) the import FAILS. Mainly because there is no data to work * on anymore ... */ val RVC_FLAGS = "PP_RVC_FLAGS" /** @brief Input parameter to the #aiProcess_SortByPType step: * Specifies which primitive types are removed by the step. * * This is a bitwise combination of the aiPrimitiveType flags. * Specifying all of them is illegal, of course. A typical use would be to exclude all line and point meshes * from the import. This is an integer property, its default value is 0. */ val SBP_REMOVE = "PP_SBP_REMOVE" /** @brief Input parameter to the AiProcess_FindInvalidData step: * Specifies the floating-point accuracy for animation values. The step checks for animation tracks where all * frame values are absolutely equal and removes them. This tweakable controls the epsilon for floating-point * comparisons - two keys are considered equal if the invaliant abs(n0 - n1) > epsilon holds true for * all vector respectively quaternion components. The default value is 0.f - comparisons are exact then. */ val FID_ANIM_ACCURACY = "PP_FID_ANIM_ACCURACY" object UvTrafo { /** TransformUVCoords evaluates UV scalings */ val SCALING = 0x1 /** TransformUVCoords evaluates UV rotations */ val ROTATION = 0x2 /** TransformUVCoords evaluates UV translation */ val TRANSLATION = 0x4 /** Everything baked together -> default value */ val ALL = SCALING or ROTATION or TRANSLATION } /** @brief Input parameter to the AiProcess_TransformUVCoords step: * Specifies which UV transformations are evaluated. * * This is a bitwise combination of the AI_UVTR property, of course). * By default all transformations are enabled (AI_UVTRAFO.ALL). */ val TUV_EVALUATE = "PP_TUV_EVALUATE" } /** ########################################################################### * IMPORTER SETTINGS * valious stuff to fine-tune the behaviour of specific importer plugins. * ########################################################################### */ object Import { /** @brief Global setting to disable generation of skeleton dummy meshes * * Skeleton dummy meshes are generated as a visualization aid in cases which the input data contains no geometry, * but only animation data. * Property data type: bool. Default value: false */ val NO_SKELETON_MESHES = "IMPORT_NO_SKELETON_MESHES" /** @brief Set the vertex animation keyframe to be imported * * ASSIMP does not support vertex keyframes (only bone animation is supported). * The library reads only one frame of models with vertex animations. * By default this is the first frame. * \note The default value is 0. This option applies to all importers. * However, it is also possible to override the global setting for a specific loader. You can use the * AI_CONFIG_IMPORT_*_KEYFRAME options (where * is a placeholder for the file format for which you * want to override the global setting). * Property type: integer. */ val GLOBAL_KEYFRAME = "IMPORT_GLOBAL_KEYFRAME" object Mdl { /** @brief Sets the colormap (= palette) to be used to decode embedded textures in MDL (Quake or 3DGS) files. * * This must be a valid path to a file. The file is 768 (256*3) bytes large and contains RGB triplets * for each of the 256 palette entries. * The default value is colormap.lmp. If the file is not found, a default palette (from Quake 1) is used. * Property type: string. */ val COLORMAP = "IMPORT_MDL_COLORMAP" val KEYFRAME = "IMPORT_MDL_KEYFRAME" } object Fbx { object Read { /** @brief Set whether the fbx importer will merge all geometry layers present in the source file or * take only the first. * * The default value is true (1). Property type: bool */ val ALL_GEOMETRY_LAYERS = "IMPORT_FBX_READ_ALL_GEOMETRY_LAYERS" /** @brief Set whether the fbx importer will read all materials present in the source file or take only * the referenced materials. * * This is void unless IMPORT.FBX_READ_MATERIALS = true * * The default value is false (0). Property type: bool */ val ALL_MATERIALS = "IMPORT_FBX_READ_ALL_MATERIALS" /** @brief Set whether the fbx importer will read materials. * * The default value is true (1). Property type: bool */ val MATERIALS = "IMPORT_FBX_READ_MATERIALS" /** @brief Set whether the fbx importer will read embedded textures. * * The default value is true (1). Property type: bool */ val TEXTURES = "IMPORT_FBX_READ_TEXTURES" /** @brief Set whether the fbx importer will read cameras. * * The default value is true (1). Property type: bool */ val CAMERAS = "IMPORT_FBX_READ_CAMERAS" /** @brief Set whether the fbx importer will read light sources. * * The default value is true (1). Property type: bool */ val LIGHTS = "IMPORT_FBX_READ_LIGHTS" /** @brief Set whether the fbx importer will read animations. * * The default value is true (1). Property type: bool */ val ANIMATIONS = "IMPORT_FBX_READ_ANIMATIONS" } /** @brief Set whether the fbx importer will act in strict mode in which only FBX 2013 is supported and * any other sub formats are rejected. FBX 2013 is the primary target for the importer, so this format * is best supported and well-tested. * * The default value is false (0). Property type: bool */ val STRICT_MODE = "IMPORT_FBX_STRICT_MODE" /** @brief Set whether the fbx importer will preserve pivot points for transformations (as extra nodes). * If set to false, pivots and offsets will be evaluated whenever possible. * * The default value is true (1). Property type: bool */ val PRESERVE_PIVOTS = "IMPORT_FBX_PRESERVE_PIVOTS" /** @brief Specifies whether the importer will drop empty animation curves or animation curves which match * the bind pose transformation over their entire defined range. * * The default value is true (1). Property type: bool */ val OPTIMIZE_EMPTY_ANIMATION_CURVES = "IMPORT_FBX_OPTIMIZE_EMPTY_ANIMATION_CURVES" /** @brief Set whether the fbx importer will search for embedded loaded textures, where no embedded texture * data is provided. * * The default value is false (0). Property type: bool */ val SEARCH_EMBEDDED_TEXTURES = "IMPORT_FBX_SEARCH_EMBEDDED_TEXTURES" } object Md3 { val KEYFRAME = "IMPORT_MD3_KEYFRAME" /** @brief Tells the MD3 loader which skin files to load. * * When loading MD3 files, Assimp checks whether a file [md3_file_name]_[skin_name].skin is existing. * These files are used by Quake III to be able to assign different skins (e.g. red and blue team) to models. * 'default', 'red', 'blue' are typical skin names. * Property type: String. Default value: "default". */ val SKIN_NAME = "IMPORT_MD3_SKIN_NAME" /** @brief Specify the Quake 3 shader file to be used for a particular MD3 file. This can also be a search path. * * By default Assimp's behaviour is as follows: * If a MD3 file <tt>any_path/models/any_q3_subdir/model_name/file_name.md3</tt> is loaded, the library tries * to locate the corresponding shader file in <tt>any_path/scripts/model_name.shader</tt>. This property * overrides this behaviour. It can either specify a full path to the shader to be loaded or alternatively * the path (relative or absolute) to the directory where the shaders for all MD3s to be loaded reside. * Assimp attempts to open <tt>IMPORT_MD3_SHADER_SRC/model_name.shader</tt> first, * <tt>IMPORT_MD3_SHADER_SRC/file_name.shader</tt> is the fallback file. Note that IMPORT_MD3_SHADER_SRC should * have a terminal (back)slash. * Property type: String. Default value: n/a. */ val SHADER_SRC = "IMPORT_MD3_SHADER_SRC" /** @brief Configures the M3D loader to detect and process multi-part Quake player models. * * These models usually consist of 3 files, lower.md3, upper.md3 and head.md3. If this property is set to true, * Assimp will try to load and combine all three files if one of them is loaded. * Property type: bool. Default value: true. */ val HANDLE_MULTIPART = "IMPORT_MD3_HANDLE_MULTIPART" } val MD2_KEYFRAME = "IMPORT_MD2_KEYFRAME" val MDC_KEYFRAME = -1 val SMD_KEYFRAME = -1 val UNREAL_KEYFRAME = -1 object Ac { /** @brief Configures the AC loader to collect all surfaces which have the "Backface cull" flag set * in separate meshes. * * Property type: bool. Default value: true. */ val SEPARATE_BFCULL = "IMPORT_AC_SEPARATE_BFCULL" /** @brief Configures whether the AC loader evaluates subdivision surfaces ( indicated by the presence * of the 'subdiv' attribute in the file). By default, Assimp performs the subdivision using the standard * Catmull-Clark algorithm * * Property type: bool. Default value: true. */ val EVAL_SUBDIVISION = "IMPORT_AC_EVAL_SUBDIVISION" } /** @brief Configures the UNREAL 3D loader to separate faces with different surface flags * (e.g. two-sided vs. single-sided). * * Property type: bool. Default value: true. */ val UNREAL_HANDLE_FLAGS = "UNREAL_HANDLE_FLAGS" /** @brief Configures the terragen import plugin to compute uv's for terrains, if not given. * Furthermore a default texture is assigned. * * UV coordinates for terrains are so simple to compute that you'll usually want to compute them on your own, * if you need them. This option is intended for model viewers which want to offer an easy way to apply * textures to terrains. * Property type: bool. Default value: false. */ val TER_MAKE_UVS = "IMPORT_TER_MAKE_UVS" /** @brief Configures the ASE loader to always reconstruct normal vectors basing on the smoothing groups loaded * from the file. * * Some ASE files have carry invalid normals, other don't. * Property type: bool. Default value: true. */ val ASE_RECONSTRUCT_NORMALS = "IMPORT_ASE_RECONSTRUCT_NORMALS" /** @brief Configures the LWO loader to load just one layer from the model. * * LWO files consist of layers and in some cases it could be useful to load only one of them. This property can * be either a string - which specifies the name of the layer - or an integer - the index of the layer. If the * property is not set the whole LWO model is loaded. Loading fails if the requested layer is not available. * The layer index is zero-based and the layer name may not be empty.<br> * Property type: Integer. Default value: all layers are loaded. */ val LWO_ONE_LAYER_ONLY = "IMPORT_LWO_ONE_LAYER_ONLY" /** @brief Configures the MD5 loader to not load the MD5ANIM file for a MD5MESH file automatically. * * The default strategy is to look for a file with the same name but the MD5ANIM extension * in the same directory. If it is found, it is loaded and combined with the MD5MESH file. * This configuration option can be used to disable this behaviour. * * Property type: bool. Default value: false. */ val MD5_NO_ANIM_AUTOLOAD = "IMPORT_MD5_NO_ANIM_AUTOLOAD" object Lws { /** @brief Defines the begin of the time range for which the LWS loader evaluates animations and computes * AiNodeAnim's. * * Assimp provides full conversion of LightWave's envelope system, including pre and post conditions. * The loader computes linearly subsampled animation chanels with the frame rate given in the LWS file. * This property defines the start time. Note: animation channels are only generated if a node has at least * one envelope with more tan one key assigned. This property. is given in frames, '0' is the first frame. * By default, if this property is not set, the importer takes the animation start from the input LWS * file ('FirstFrame' line)<br> * Property type: Integer. Default value: taken from file. * * @see AI_CONFIG_IMPORT_LWS_ANIM_END - end of the imported time range */ val LWS_ANIM_START = "IMPORT_LWS_ANIM_START" val LWS_ANIM_END = "IMPORT_LWS_ANIM_END" } /** @brief Defines the output frame rate of the IRR loader. * * IRR animations are difficult to convert for Assimp and there will always be a loss of quality. * This setting defines how many keys per second are returned by the converter.<br> * Property type: integer. Default value: 100 */ val IRR_ANIM_FPS = "IMPORT_IRR_ANIM_FPS" object Ogre { /** @brief Ogre Importer will try to find referenced materials from this file. * * Ogre meshes reference with material names, this does not tell Assimp the file where it is located in. * Assimp will try to find the source file in the following order: <material-name>.material, * <mesh-filename-base>.material and lastly the material name defined by this config property. <br> * Property type: String. Default value: Scene.material. */ val MATERIAL_FILE = "IMPORT_OGRE_MATERIAL_FILE" /** @brief Ogre Importer detect the texture usage from its filename. * * Ogre material texture units do not define texture type, the textures usage depends on the used shader or * Ogre's fixed pipeline. If this config property is true Assimp will try to detect the type from the textures * filename postfix: _n, _nrm, _nrml, _normal, _normals and _normalmap for normal map, _s, _spec, _specular * and _specularmap for specular map, _l, _light, _lightmap, _occ and _occlusion for light map, _disp and * _displacement for displacement map. * The matching is case insensitive. Post fix is taken between the last underscore and the last period. * Default behavior is to detect type from lower cased texture unit name by matching against: normalmap, * specularmap, lightmap and displacementmap. * For both cases if no match is found aiTextureType_DIFFUSE is used. <br> * Property type: Bool. Default value: false. */ val OGRE_TEXTURETYPE_FROM_FILENAME = "IMPORT_OGRE_TEXTURETYPE_FROM_FILENAME" } object Ifc { /** @brief Specifies whether the IFC loader skips over IfcSpace elements. * * IfcSpace elements (and their geometric representations) are used to represent, well, free space in a * building storey.<br> * Property type: Bool. Default value: true. */ val IFC_SKIP_SPACE_REPRESENTATIONS = "IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS" /** @brief Specifies whether the IFC loader will use its own, custom triangulation algorithm to triangulate * wall and floor meshes. * * If this property is set to false, walls will be either triangulated by AiProcess_Triangulate or * will be passed through as huge polygons with faked holes (i.e. holes that are connected with * the outer boundary using a dummy edge). It is highly recommended to set this property to true * if you want triangulated data because AiProcess_Triangulate is known to have problems with the kind * of polygons that the IFC loader spits out for complicated meshes. * Property type: Bool. Default value: true. */ val IFC_CUSTOM_TRIANGULATION = "IMPORT_IFC_CUSTOM_TRIANGULATION" /** @brief Set the tessellation conic angle for IFC smoothing curves. * * This is used by the IFC importer to determine the tessellation parameter for smoothing curves. * @note The default value is 10f and the accepted values are in range [5f, 120f]. * Property type: Float. */ val IFC_SMOOTHING_ANGLE = "IMPORT_IFC_SMOOTHING_ANGLE" /** @brief Set the tessellation for IFC cylindrical shapes. * * This is used by the IFC importer to determine the tessellation parameter for cylindrical shapes, * i.e. the number of segments used to aproximate a circle. * @note The default value is 32 and the accepted values are in range [3, 180]. * Property type: Integer. */ val IFC_CYLINDRICAL_TESSELLATION = "IMPORT_IFC_CYLINDRICAL_TESSELLATION" } /** @brief Specifies whether the Collada loader will ignore the provided up direction. * * If this property is set to true, the up direction provided in the file header will be ignored and the file * will be loaded as is. * Property type: Bool. Default value: false. */ val COLLADA_IGNORE_UP_DIRECTION = "IMPORT_COLLADA_IGNORE_UP_DIRECTION" } }
mit
ec990f2de33802a8acdfd13b6d856e46
50.708084
125
0.608946
4.556127
false
false
false
false
GLodi/GitNav
app/src/main/java/giuliolodi/gitnav/ui/option/OptionActivity.kt
1
2057
/* * 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.option import android.content.Context import android.content.Intent import android.os.Bundle import giuliolodi.gitnav.R import giuliolodi.gitnav.ui.base.BaseDrawerActivity import kotlinx.android.synthetic.main.base_activity.* import kotlinx.android.synthetic.main.base_activity_drawer.* /** * Created by giulio on 07/10/2017. */ class OptionActivity : BaseDrawerActivity() { private val OPTION_FRAGMENT_TAG = "OPTION_FRAGMENT_TAG" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) layoutInflater.inflate(R.layout.option_activity, content_frame) var optionFragment: OptionFragment? = supportFragmentManager.findFragmentByTag(OPTION_FRAGMENT_TAG) as OptionFragment? if (optionFragment == null) { optionFragment = OptionFragment() supportFragmentManager .beginTransaction() .replace(R.id.option_activity_frame, optionFragment, OPTION_FRAGMENT_TAG) .commit() } } override fun onResume() { super.onResume() nav_view.menu.getItem(6).subMenu.getItem(0).isChecked = true } override fun onBackPressed() { super.onBackPressed() overridePendingTransition(0,0) } companion object { fun getIntent(context: Context): Intent { return Intent(context, OptionActivity::class.java) } } }
apache-2.0
c02413bff2e2831a3a3e7fddb8bd5b60
31.15625
126
0.695187
4.501094
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/operatorConventions/compareTo/boolean.kt
1
390
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS fun checkLess(x: Boolean, y: Boolean) = when { x >= y -> "Fail $x >= $y" !(x < y) -> "Fail !($x < $y)" !(x <= y) -> "Fail !($x <= $y)" x > y -> "Fail $x > $y" x.compareTo(y) >= 0 -> "Fail $x.compareTo($y) >= 0" else -> "OK" } fun box() = checkLess(false, true)
apache-2.0
719c967e46b3c51d31034ed384581bfb
29
72
0.494872
2.708333
false
false
false
false
savvasdalkitsis/gameframe
device/src/main/java/com/savvasdalkitsis/gameframe/feature/device/usecase/DeviceUseCase.kt
1
5420
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.device.usecase import com.savvasdalkitsis.gameframe.feature.bitmap.model.Bitmap import com.savvasdalkitsis.gameframe.feature.bitmap.usecase.BmpUseCase import com.savvasdalkitsis.gameframe.feature.device.api.CommandResponse import com.savvasdalkitsis.gameframe.feature.device.api.DeviceApi import com.savvasdalkitsis.gameframe.feature.device.model.* import com.savvasdalkitsis.gameframe.feature.ip.repository.IpRepository import com.savvasdalkitsis.gameframe.feature.networking.model.WifiNotEnabledException import com.savvasdalkitsis.gameframe.feature.networking.usecase.WifiUseCase import com.savvasdalkitsis.gameframe.feature.storage.usecase.LocalStorageUseCase import io.reactivex.Completable import io.reactivex.Maybe import io.reactivex.functions.Function import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import java.io.File import java.util.Collections.singletonMap class DeviceUseCase(private val deviceApi: DeviceApi, private val localStorageUseCase: LocalStorageUseCase, private val bmpUseCase: BmpUseCase, private val ipRepository: IpRepository, private val wifiUseCase: WifiUseCase) { fun togglePower() = issueCommand("power") fun menu() = issueCommand("menu") fun next() = issueCommand("next") fun setBrightness(brightness: Brightness) = setParam(brightness.queryParamName) fun setPlaybackMode(playbackMode: PlaybackMode) = setParam(playbackMode.queryParamName) fun setCycleInterval(cycleInterval: CycleInterval) = setParam(cycleInterval.queryParamName) fun setDisplayMode(displayMode: DisplayMode) = setParam(displayMode.queryParamName) fun setClockFace(clockFace: ClockFace) = setParam(clockFace.queryParamName) fun removeFolder(name: String) = issueCommand("rmdir", name) fun uploadAndDisplay(name: String, bitmap: Bitmap): Completable = localStorageUseCase.saveFile(dirName = "bmp/$name", fileName = "0.bmp", fileContentsProvider = { bmpUseCase.rasterizeToBmp(bitmap) }, overwriteFile = true) .flatMap<File> { file -> createFolder(name).toSingleDefault<File>(file) } .flatMapCompletable { uploadFile(it) } .andThen(play(name)) private fun createFolder(name: String): Completable = issueCommand("mkdir", name) .onErrorResumeNext { if (it is DeviceCommandError && (it.response.message?.contains("exists")) == true) { Completable.error(AlreadyExistsOnDeviceException("Could not create folder on game frame with name '$name' as it already exists", it)) } else { Completable.error(it) } } private fun uploadFile(file: File): Completable { val requestFile = RequestBody.create(MediaType.parse("image/bmp"), file) val filePart = MultipartBody.Part.createFormData("my_file[]", "0.bmp", requestFile) return deviceApi.upload(filePart) .to(mapResponse()) .onErrorResumeNext { error -> wifiUseCase.isWifiEnabled() .flatMapCompletable { enabled -> if (!enabled) Completable.error(WifiNotEnabledException()) else Completable.error(error) } } } private fun play(name: String) = issueCommand("play", name) private fun param(key: String, value: String = "") = singletonMap(key, value) private fun mapResponse(): Function<Maybe<CommandResponse>, Completable> = Function { s -> s.flatMapCompletable { when { isSuccess(it) -> Completable.complete() else -> Completable.error(wrap(it)) } } } private fun issueCommand(key: String, value: String = ""): Completable = ipRepository.ipAddress .flatMapCompletable { deviceApi.command(param(key, value)).to(mapResponse()) } .onErrorResumeNext(changeErrorToWifiIfNotEnabled()) private fun changeErrorToWifiIfNotEnabled(): (Throwable) -> Completable = { error -> wifiUseCase.isWifiEnabled().flatMapCompletable { enabled -> if (!enabled) Completable.error(WifiNotEnabledException()) else Completable.error(error) } } private fun setParam(key: String): Completable = deviceApi.set(param(key)) private fun wrap(response: CommandResponse) = DeviceCommandError("Command was not successful. response: $response", response) private fun isSuccess(response: CommandResponse?) = "success" == response?.status }
apache-2.0
45415f0eb061a39e882b19882b41a63d
43.434426
153
0.685793
4.79646
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/data/history/HistoryMapper.kt
1
1182
package eu.kanade.data.history import eu.kanade.domain.history.model.History import eu.kanade.domain.history.model.HistoryWithRelations import eu.kanade.domain.manga.model.MangaCover import java.util.Date val historyMapper: (Long, Long, Date?, Long) -> History = { id, chapterId, readAt, readDuration -> History( id = id, chapterId = chapterId, readAt = readAt, readDuration = readDuration, ) } val historyWithRelationsMapper: (Long, Long, Long, String, String?, Long, Boolean, Long, Float, Date?, Long) -> HistoryWithRelations = { historyId, mangaId, chapterId, title, thumbnailUrl, sourceId, isFavorite, coverLastModified, chapterNumber, readAt, readDuration -> HistoryWithRelations( id = historyId, chapterId = chapterId, mangaId = mangaId, title = title, chapterNumber = chapterNumber, readAt = readAt, readDuration = readDuration, coverData = MangaCover( mangaId = mangaId, sourceId = sourceId, isMangaFavorite = isFavorite, url = thumbnailUrl, lastModified = coverLastModified, ), ) }
apache-2.0
e5fedbff79f4ffc279c40e2dd312b61f
32.771429
139
0.651438
4.377778
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/utils/BolusTimer.kt
1
2301
package info.nightscout.androidaps.utils import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.GlucoseUnit import info.nightscout.androidaps.plugins.general.automation.AutomationEvent import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.automation.actions.ActionAlarm import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.InputDelta import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerBg import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerDelta import info.nightscout.androidaps.interfaces.ResourceHelper import java.text.DecimalFormat import javax.inject.Inject import javax.inject.Singleton @Singleton class BolusTimer @Inject constructor( private val injector: HasAndroidInjector, private val rh: ResourceHelper, private val automationPlugin: AutomationPlugin, ) { fun scheduleBolusReminder() { val event = AutomationEvent(injector).apply { title = rh.gs(R.string.bolusreminder) readOnly = true systemAction = true autoRemove = true trigger = TriggerConnector(injector, TriggerConnector.Type.AND).apply { // Bg above 70 mgdl and delta positive mgdl list.add(TriggerBg(injector, 70.0, GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_GREATER)) list.add( TriggerDelta( injector, InputDelta(rh, 0.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), GlucoseUnit.MGDL, Comparator.Compare .IS_GREATER ) ) } actions.add(ActionAlarm(injector, rh.gs(R.string.time_to_bolus))) } automationPlugin.addIfNotExists(event) } fun removeBolusReminder() { val event = AutomationEvent(injector).apply { title = rh.gs(R.string.bolusreminder) } automationPlugin.removeIfExists(event) } }
agpl-3.0
c58c8ec519ebc5750654ed9b1c40f480
40.854545
159
0.714472
4.565476
false
false
false
false
kvakil/venus
src/main/kotlin/venus/riscv/utils.kt
1
1297
package venus.riscv fun userStringToInt(s: String): Int { if (isCharacterLiteral(s)) { return characterLiteralToInt(s) } val radix = when { s.startsWith("0x") -> 16 s.startsWith("0b") -> 2 s.drop(1).startsWith("0x") -> 16 s.drop(1).startsWith("0b") -> 2 else -> return s.toLong().toInt() } val skipSign = when (s.first()) { '+', '-' -> 1 else -> 0 } val noRadixString = s.take(skipSign) + s.drop(skipSign + 2) return noRadixString.toLong(radix).toInt() } private fun isCharacterLiteral(s: String) = s.first() == '\'' && s.last() == '\'' private fun characterLiteralToInt(s: String): Int { val stripSingleQuotes = s.drop(1).dropLast(1) if (stripSingleQuotes == "\\'") return '\''.toInt() if (stripSingleQuotes == "\"") return '"'.toInt() val jsonString = "\"$stripSingleQuotes\"" try { val parsed = JSON.parse<String>(jsonString) if (parsed.isEmpty()) throw NumberFormatException("character literal $s is empty") if (parsed.length > 1) throw NumberFormatException("character literal $s too long") return parsed[0].toInt() } catch (e: Throwable) { throw NumberFormatException("could not parse character literal $s") } }
mit
f208b0d656716018ffd6aad50fd6c538
29.880952
91
0.592907
3.803519
false
false
false
false
Adventech/sabbath-school-android-2
common/design-compose/src/main/kotlin/app/ss/design/compose/theme/Size.kt
1
1379
/* * Copyright (c) 2022. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.design.compose.theme import androidx.compose.ui.unit.dp val Spacing4 = 4.dp val Spacing6 = 6.dp val Spacing8 = 8.dp val Spacing12 = 12.dp val Spacing16 = 16.dp val Spacing20 = 20.dp val Spacing24 = 24.dp val Spacing32 = 32.dp
mit
f6f0bf968b9ce5e442c30103dc49efb6
39.558824
80
0.757796
4.079882
false
false
false
false
auth0/Auth0.Android
auth0/src/main/java/com/auth0/android/request/ProfileRequest.kt
1
4733
package com.auth0.android.request import com.auth0.android.Auth0Exception import com.auth0.android.authentication.AuthenticationException import com.auth0.android.callback.Callback import com.auth0.android.result.Authentication import com.auth0.android.result.Credentials import com.auth0.android.result.UserProfile import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** * Request to fetch a profile after a successful authentication with Auth0 Authentication API */ public class ProfileRequest /** * @param authenticationRequest the request that will output a pair of credentials * @param userInfoRequest the /userinfo request that will be wrapped */( private val authenticationRequest: AuthenticationRequest, private val userInfoRequest: Request<UserProfile, AuthenticationException> ) : Request<Authentication, AuthenticationException> { /** * Adds additional parameters for the login request * * @param parameters as a non-null dictionary * @return itself */ override fun addParameters(parameters: Map<String, String>): ProfileRequest { authenticationRequest.addParameters(parameters) return this } override fun addParameter(name: String, value: String): ProfileRequest { authenticationRequest.addParameter(name, value) return this } /** * Adds a header to the request, e.g. "Authorization" * * @param name of the header * @param value of the header * @return itself * @see [ProfileRequest] */ override fun addHeader(name: String, value: String): ProfileRequest { authenticationRequest.addHeader(name, value) return this } /** * Set the scope used to authenticate the user * * @param scope value * @return itself */ public fun setScope(scope: String): ProfileRequest { authenticationRequest.setScope(scope) return this } /** * Set the connection used to authenticate * * @param connection name * @return itself */ public fun setConnection(connection: String): ProfileRequest { authenticationRequest.setConnection(connection) return this } /** * Starts the log in request and then fetches the user's profile * * @param callback called on either success or failure */ override fun start(callback: Callback<Authentication, AuthenticationException>) { authenticationRequest.start(object : Callback<Credentials, AuthenticationException> { override fun onSuccess(credentials: Credentials) { userInfoRequest .addHeader(HEADER_AUTHORIZATION, "Bearer " + credentials.accessToken) .start(object : Callback<UserProfile, AuthenticationException> { override fun onSuccess(profile: UserProfile) { callback.onSuccess(Authentication(profile, credentials)) } override fun onFailure(error: AuthenticationException) { callback.onFailure(error) } }) } override fun onFailure(error: AuthenticationException) { callback.onFailure(error) } }) } /** * Logs in the user with Auth0 and fetches it's profile. * * @return authentication object containing the user's tokens and profile * @throws Auth0Exception when either authentication or profile fetch fails */ @Throws(Auth0Exception::class) override fun execute(): Authentication { val credentials = authenticationRequest.execute() val profile = userInfoRequest .addHeader(HEADER_AUTHORIZATION, "Bearer " + credentials.accessToken) .execute() return Authentication(profile, credentials) } /** * Logs in the user with Auth0 and fetches it's profile inside a Coroutine. * This is a Coroutine that is exposed only for Kotlin. * * @return authentication object containing the user's tokens and profile * @throws Auth0Exception when either authentication or profile fetch fails */ @JvmSynthetic @Throws(Auth0Exception::class) override suspend fun await(): Authentication { val credentials = authenticationRequest.await() val profile = userInfoRequest .addHeader(HEADER_AUTHORIZATION, "Bearer " + credentials.accessToken) .await() return Authentication(profile, credentials) } private companion object { private const val HEADER_AUTHORIZATION = "Authorization" } }
mit
17eedf3bb67b0cc38ddbd6a725f70bc4
33.808824
93
0.661103
5.270601
false
false
false
false
Maccimo/intellij-community
build/tasks/src/org/jetbrains/intellij/build/io/ssh.kt
3
3399
// 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.io import net.schmizz.sshj.xfer.LocalDestFile import net.schmizz.sshj.xfer.LocalFileFilter import net.schmizz.sshj.xfer.LocalSourceFile import java.io.InputStream import java.io.OutputStream import java.nio.file.Files import java.nio.file.Path import java.nio.file.attribute.PosixFilePermission import java.util.* import java.util.concurrent.TimeUnit internal class NioFileDestination(private val file: Path) : LocalDestFile { override fun getOutputStream(): OutputStream = Files.newOutputStream(file) override fun getChild(name: String?) = throw UnsupportedOperationException() override fun getTargetFile(filename: String): LocalDestFile { return this } override fun getTargetDirectory(dirname: String?): LocalDestFile { return this } override fun setPermissions(perms: Int) { Files.setPosixFilePermissions(file, fromOctalFileMode(perms)) } override fun setLastAccessedTime(t: Long) { // ignore } override fun setLastModifiedTime(t: Long) { // ignore } } internal class NioFileSource(private val file: Path, private val filePermission: Int = -1) : LocalSourceFile { override fun getName() = file.fileName.toString() override fun getLength() = Files.size(file) override fun getInputStream(): InputStream = Files.newInputStream(file) override fun getPermissions(): Int { return if (filePermission == -1) toOctalFileMode(Files.getPosixFilePermissions(file)) else filePermission } override fun isFile() = true override fun isDirectory() = false override fun getChildren(filter: LocalFileFilter): Iterable<LocalSourceFile> = emptyList() override fun providesAtimeMtime() = false override fun getLastAccessTime() = System.currentTimeMillis() / 1000 override fun getLastModifiedTime() = TimeUnit.MILLISECONDS.toSeconds(Files.getLastModifiedTime(file).toMillis()) } private fun toOctalFileMode(permissions: Set<PosixFilePermission?>): Int { var result = 0 for (permissionBit in permissions) { when (permissionBit) { PosixFilePermission.OWNER_READ -> result = result or 256 PosixFilePermission.OWNER_WRITE -> result = result or 128 PosixFilePermission.OWNER_EXECUTE -> result = result or 64 PosixFilePermission.GROUP_READ -> result = result or 32 PosixFilePermission.GROUP_WRITE -> result = result or 16 PosixFilePermission.GROUP_EXECUTE -> result = result or 8 PosixFilePermission.OTHERS_READ -> result = result or 4 PosixFilePermission.OTHERS_WRITE -> result = result or 2 PosixFilePermission.OTHERS_EXECUTE -> result = result or 1 else -> {} } } return result } private val decodeMap = arrayOf( PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_WRITE, PosixFilePermission.OTHERS_READ, PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.GROUP_WRITE, PosixFilePermission.GROUP_READ, PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_READ ) private fun fromOctalFileMode(mode: Int): Set<PosixFilePermission> { var mask = 1 val perms = EnumSet.noneOf(PosixFilePermission::class.java) for (flag in decodeMap) { if (mask and mode != 0) { perms.add(flag) } mask = mask shl 1 } return perms }
apache-2.0
821f7ec6ffe2ca132fded0216c75e26d
33
120
0.753163
4.454784
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/SdkInfoCache.kt
1
5894
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.projectStructure import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.jetbrains.rd.util.concurrentMapOf import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.caches.project.cacheInvalidatingOnRootModifications import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.ArrayDeque /** * Maintains and caches mapping ModuleInfo -> SdkInfo *form its dependencies* * (note that this SDK might be different from Project SDK) * * Cache is needed because one and the same library might (and usually does) * participate as dependency in several modules, so if someone queries a lot * of modules for their SDKs (ex.: determine built-ins for each module in a * project), we end up inspecting one and the same dependency multiple times. * * With projects with abnormally high amount of dependencies this might lead * to performance issues. */ interface SdkInfoCache { fun findOrGetCachedSdk(moduleInfo: ModuleInfo): SdkInfo? companion object { fun getInstance(project: Project): SdkInfoCache = project.service() } } internal class SdkInfoCacheImpl(private val project: Project) : SdkInfoCache { @JvmInline value class SdkDependency(val sdk: SdkInfo?) private val cache: MutableMap<ModuleInfo, SdkDependency> get() = project.cacheInvalidatingOnRootModifications { concurrentMapOf() } override fun findOrGetCachedSdk(moduleInfo: ModuleInfo): SdkInfo? { // get an operate on the fixed instance of a cache to avoid case of roots modification in the middle of lookup val instance = cache if (!instance.containsKey(moduleInfo)) { findSdk(instance, moduleInfo) } return instance[moduleInfo]?.sdk } private fun findSdk(cache: MutableMap<ModuleInfo, SdkDependency>, moduleInfo: ModuleInfo) { moduleInfo.safeAs<SdkDependency>()?.let { cache[moduleInfo] = it return } val libraryDependenciesCache = LibraryDependenciesCache.getInstance(this.project) val visitedModuleInfos = mutableSetOf<ModuleInfo>() // graphs is a stack of paths is used to implement DFS without recursion // it depends on a number of libs, that could be > 10k for a huge monorepos val graphs = ArrayDeque<List<ModuleInfo>>().also { // initial graph item it.add(listOf(moduleInfo)) } val (path, sdkInfo) = run { while (graphs.isNotEmpty()) { ProgressManager.checkCanceled() // graph of DFS from the root i.e from `moduleInfo` // note: traverse of graph goes in a depth over the most left edge: // - poll() retrieves and removes the head of the queue // - push(element) inserts the element at the front of the deque val graph = graphs.poll() val last = graph.last() // the result could be immediately returned when cache already has it val cached = cache[last] if (cached != null) { cached.sdk?.let { return@run graph to cached } continue } if (!visitedModuleInfos.add(last)) continue val dependencies = run deps@{ if (last is LibraryInfo) { // use a special case for LibraryInfo to reuse values from a library dependencies cache val (libraries, sdks) = libraryDependenciesCache.getLibrariesAndSdksUsedWith(last) sdks.firstOrNull()?.let { return@run graph to SdkDependency(it) } libraries } else { last.dependencies() .also { dependencies -> dependencies.firstIsInstanceOrNull<SdkInfo>()?.let { return@run graph to SdkDependency(it) } } } } dependencies.forEach { dependency -> val sdkDependency = cache[dependency] if (sdkDependency != null) { sdkDependency.sdk?.let { // sdk is found when some dependency is already resolved return@run (graph + dependency) to sdkDependency } } else { // otherwise add a new graph of (existed graph + dependency) as candidates for DFS lookup if (!visitedModuleInfos.contains(dependency)) { graphs.push(graph + dependency) } } } } return@run null to noSdkDependency } // when sdk is found: mark all graph elements could be resolved to the same sdk path?.let { it.forEach { info -> cache[info] = sdkInfo } visitedModuleInfos.removeAll(it) } // mark all visited modules (apart from found path) as dead ends visitedModuleInfos.forEach { info -> cache[info] = noSdkDependency } } companion object { private val noSdkDependency = SdkDependency(null) } }
apache-2.0
1c5a9f09e39f6060cc664e25580012db
41.410072
120
0.604683
5.343608
false
false
false
false
k9mail/k-9
app/core/src/main/java/com/fsck/k9/notification/NotificationHelper.kt
1
2387
package com.fsck.k9.notification import android.content.Context import android.net.Uri import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.fsck.k9.Account import com.fsck.k9.K9 class NotificationHelper( private val context: Context, private val notificationManager: NotificationManagerCompat, private val channelUtils: NotificationChannelManager ) { fun getContext(): Context { return context } fun getNotificationManager(): NotificationManagerCompat { return notificationManager } fun createNotificationBuilder( account: Account, channelType: NotificationChannelManager.ChannelType ): NotificationCompat.Builder { return NotificationCompat.Builder( context, channelUtils.getChannelIdFor(account, channelType) ) } companion object { internal const val NOTIFICATION_LED_ON_TIME = 500 internal const val NOTIFICATION_LED_OFF_TIME = 2000 internal const val NOTIFICATION_LED_FAST_ON_TIME = 100 internal const val NOTIFICATION_LED_FAST_OFF_TIME = 100 internal const val NOTIFICATION_LED_FAILURE_COLOR = 0xFFFF0000L.toInt() } } internal fun NotificationCompat.Builder.setErrorAppearance(): NotificationCompat.Builder = apply { setSilent(true) if (!K9.isQuietTime) { setLights( NotificationHelper.NOTIFICATION_LED_FAILURE_COLOR, NotificationHelper.NOTIFICATION_LED_FAST_ON_TIME, NotificationHelper.NOTIFICATION_LED_FAST_OFF_TIME ) } } internal fun NotificationCompat.Builder.setAppearance( silent: Boolean, appearance: NotificationAppearance ): NotificationCompat.Builder = apply { if (silent) { setSilent(true) } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { if (!appearance.ringtone.isNullOrEmpty()) { setSound(Uri.parse(appearance.ringtone)) } if (appearance.vibrationPattern != null) { setVibrate(appearance.vibrationPattern) } if (appearance.ledColor != null) { setLights( appearance.ledColor, NotificationHelper.NOTIFICATION_LED_ON_TIME, NotificationHelper.NOTIFICATION_LED_OFF_TIME ) } } }
apache-2.0
c37725a6b67e8605f51ea2d94d5b686f
29.21519
98
0.679933
4.822222
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/services/OptionService.kt
1
9961
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.services import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.ex.ExException import com.maddyhome.idea.vim.options.Option import com.maddyhome.idea.vim.options.OptionChangeListener import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType /** * COMPATIBILITY-LAYER: Moved to a different package * Please see: https://jb.gg/zo8n0r */ interface OptionService { /** * Gets option value. * @param scope global/local option scope * @param optionName option name or alias * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") */ fun getOptionValue(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, token: String = optionName): VimDataType /** * Sets option value. * @param scope global/local option scope * @param optionName option name or alias * @param value option value * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") */ fun setOptionValue(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, value: VimDataType, token: String = optionName) /** * Checks if the [value] is contained in string option. * * Returns false if there is no option with the given optionName, or it's type is different from string. * @param scope global/local option scope * @param optionName option name or alias * @param value option value */ fun contains(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, value: String): Boolean /** * Splits a string option into flags * * e.g. the `fileencodings` option with value "ucs-bom,utf-8,default,latin1" will result listOf("ucs-bom", "utf-8", "default", "latin1") * * returns null if there is no option with the given optionName, or its type is different from string. * @param scope global/local option scope * @param optionName option name or alias */ fun getValues(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String): List<String>? /** * Same as [setOptionValue], but automatically casts [value] to the required [VimDataType] * @param scope global/local option scope * @param optionName option name or alias * @param value option value * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") in case the option is not found * @throws ExException("E474: Invalid argument: $token") in case the cast to VimDataType is impossible */ fun setOptionValue(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, value: String, token: String = optionName) /** * Same as `set {option}+={value}` in Vim documentation. * @param scope global/local option scope * @param optionName option name or alias * @param value option value * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") in case the option is not found * @throws ExException("E474: Invalid argument: $token") in case the method was called for the [ToggleOption] * @throws ExException("E474: Invalid argument: $token") in case the method was called for the [StringOption] and the argument is invalid (does not satisfy the option bounded values) * @throws ExException("E521: Number required after =: $token") in case the cast to VimInt is impossible */ fun appendValue(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, value: String, token: String = optionName) /** * Same as `set {option}^={value}` in Vim documentation. * @param scope global/local option scope * @param optionName option name or alias * @param value option value * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") in case the option is not found * @throws ExException("E474: Invalid argument: $token") in case the method was called for the [ToggleOption] * @throws ExException("E474: Invalid argument: $token") in case the method was called for the [StringOption] and the argument is invalid (does not satisfy the option bounded values) * @throws ExException("E521: Number required after =: $token") in case the cast to VimInt is impossible */ fun prependValue(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, value: String, token: String = optionName) /** * Same as `set {option}-={value}` in Vim documentation. * @param scope global/local option scope * @param optionName option name or alias * @param value option value * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") in case the option is not found * @throws ExException("E474: Invalid argument: $token") in case the method was called for the [ToggleOption] * @throws ExException("E474: Invalid argument: $token") in case the method was called for the [StringOption] and the argument is invalid (does not satisfy the option bounded values) * @throws ExException("E521: Number required after =: $token") in case the cast to VimInt is impossible */ fun removeValue(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, value: String, token: String = optionName) /** * Checks if the toggle option on. * * Returns false if [optionName] is not a [ToggleOption] * @param scope global/local option scope * @param optionName option name or alias * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") in case the option is not found */ fun isSet(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, token: String = optionName): Boolean /** * Checks if the option's value set to default. * * @param scope global/local option scope * @param optionName option name or alias * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") in case the option is not found */ fun isDefault(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, token: String = optionName): Boolean /** * Resets option's value to default. * * @param scope global/local option scope * @param optionName option name or alias * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") in case the option is not found */ fun resetDefault(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, token: String = optionName) /** * Resets all options back to default values. */ fun resetAllOptions() /** * Checks if the option with given optionName is a toggleOption. * @param optionName option name or alias */ fun isToggleOption(optionName: String): Boolean /** * Sets the option on (true). * @param scope global/local option scope * @param optionName option name or alias * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") in case the option is not found * @throws ExException("E474: Invalid argument: $token") in case the option is not a [ToggleOption] */ fun setOption(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, token: String = optionName) /** * COMPATIBILITY-LAYER: New method added * Please see: https://jb.gg/zo8n0r */ fun setOption(scope: Scope, optionName: String, token: String = optionName) /** * Unsets the option (false). * @param scope global/local option scope * @param optionName option name or alias * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") in case the option is not found * @throws ExException("E474: Invalid argument: $token") in case the option is not a [ToggleOption] */ fun unsetOption(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, token: String = optionName) /** * Inverts boolean option value true -> false / false -> true. * @param scope global/local option scope * @param optionName option name or alias * @param token used in exception messages * @throws ExException("E518: Unknown option: $token") in case the option is not found * @throws ExException("E474: Invalid argument: $token") in case the option is not a [ToggleOption] */ fun toggleOption(scope: com.maddyhome.idea.vim.options.OptionScope, optionName: String, token: String = optionName) /** * @return list of all option names */ fun getOptions(): Set<String> /** * @return list of all option abbreviations */ fun getAbbrevs(): Set<String> /** * Adds the option. * @param option option */ fun addOption(option: Option<out VimDataType>) /** * Removes the option. * @param optionName option name or alias */ fun removeOption(optionName: String) /** * Adds a listener to the option. * @param optionName option name or alias * @param listener option listener * @param executeOnAdd whether execute listener after the method call or not */ fun addListener(optionName: String, listener: OptionChangeListener<VimDataType>, executeOnAdd: Boolean = false) /** * Remove the listener from the option. * @param optionName option name or alias * @param listener option listener */ fun removeListener(optionName: String, listener: OptionChangeListener<VimDataType>) /** * Get the [Option] by its name or abbreviation */ fun getOptionByNameOrAbbr(key: String): Option<out VimDataType>? /** * COMPATIBILITY-LAYER: Added this class * Please see: https://jb.gg/zo8n0r */ sealed class Scope { object GLOBAL : Scope() class LOCAL(val editor: VimEditor) : Scope() } }
mit
7fd82e78027d2f7d1359420e3291f6c9
40.33195
184
0.714788
4.159081
false
false
false
false
VTUZ-12IE1bzud/TruckMonitor-Android
app/src/main/kotlin/ru/annin/truckmonitor/data/repository/KeyStoreRepository.kt
1
1693
package ru.annin.truckmonitor.data.repository import ru.annin.truckmonitor.data.KeyStoreException import ru.annin.truckmonitor.data.keystore.KeyStoreService import ru.annin.truckmonitor.data.repository.KeyStoreRepository.token /** * Репозиторий ключей. * Для инициализации репозитория, необходимо вызвать метод initialization() в Application. * Если во время записи/удаления данных будет получена ошибка, будет выбрашенно исключение KeyStoreException. * * @property token Токен пользователя. * * @author Pavel Annin. */ object KeyStoreRepository { // Configuration private val TOKEN_ALIAS: String = "token" // Component's private lateinit var keyStore: KeyStoreService // Properties var token: String get() = keyStore.retrieveSecretKey(TOKEN_ALIAS) ?: throw KeyStoreException("Error retrieve token") set(value) = keyStore.run { val result = addSecretKey(TOKEN_ALIAS, value) if (!result) { throw KeyStoreException("Error save token") } } /** * Инициализация репозитория. * Необходимо вызвать в Application. */ @JvmStatic fun initialization(keyStore: KeyStoreService) { this.keyStore = keyStore } /** Удалить токен пользователя. */ fun deleteToken() { val result = keyStore.deleteEntryByAlias(TOKEN_ALIAS) if (!result) { throw KeyStoreException("Error delete token") } } }
apache-2.0
a94235b07d45d3674599278da34a4326
28.979592
109
0.68188
3.624691
false
false
false
false
GunoH/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/ChangeTypeFixUtils.kt
2
3101
// 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.quickfix import com.intellij.codeInspection.util.IntentionFamilyName import com.intellij.codeInspection.util.IntentionName import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.KtProperty object ChangeTypeFixUtils { @IntentionFamilyName fun familyName(): String = KotlinBundle.message("fix.change.return.type.family") fun functionOrConstructorParameterPresentation(element: KtCallableDeclaration, containerName: String?): String? { val name = element.name return if (name != null) { val fullName = if (containerName != null) "'${containerName}.$name'" else "'$name'" when (element) { is KtParameter -> KotlinBundle.message("fix.change.return.type.presentation.property", fullName) is KtProperty -> KotlinBundle.message("fix.change.return.type.presentation.property", fullName) else -> KotlinBundle.message("fix.change.return.type.presentation.function", fullName) } } else null } fun baseFunctionOrConstructorParameterPresentation(presentation: String): String = KotlinBundle.message("fix.change.return.type.presentation.base", presentation) fun baseFunctionOrConstructorParameterPresentation(element: KtCallableDeclaration, containerName: String?): String? { val presentation = functionOrConstructorParameterPresentation(element, containerName) ?: return null return baseFunctionOrConstructorParameterPresentation(presentation) } @IntentionName fun getTextForQuickFix( element: KtCallableDeclaration, presentation: String?, isUnitType: Boolean, typePresentation: String ): String { if (isUnitType && element is KtFunction && element.hasBlockBody()) { return if (presentation == null) KotlinBundle.message("fix.change.return.type.remove.explicit.return.type") else KotlinBundle.message("fix.change.return.type.remove.explicit.return.type.of", presentation) } return when (element) { is KtFunction -> { if (presentation != null) KotlinBundle.message("fix.change.return.type.return.type.text.of", presentation, typePresentation) else KotlinBundle.message("fix.change.return.type.return.type.text", typePresentation) } else -> { if (presentation != null) KotlinBundle.message("fix.change.return.type.type.text.of", presentation, typePresentation) else KotlinBundle.message("fix.change.return.type.type.text", typePresentation) } } } }
apache-2.0
76064f98eeb44b61357c87552fc9ac9f
45.298507
158
0.681071
5.100329
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/HeadlessPluginsInstaller.kt
5
1760
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.plugins import com.intellij.openapi.application.ApplicationStarter import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable import com.intellij.util.io.URLUtil import kotlin.system.exitProcess internal class HeadlessPluginsInstaller : ApplicationStarter { @Suppress("SSBasedInspection") private val LOG = logger<HeadlessPluginsInstaller>() override val commandName: String get() = "installPlugins" override val requiredModality: Int get() = ApplicationStarter.NOT_IN_EDT override fun main(args: List<String>) { try { val pluginIds = LinkedHashSet<PluginId>() val customRepositories = LinkedHashSet<String>() for (i in 1 until args.size) { val arg = args[i] when { arg.contains(URLUtil.SCHEME_SEPARATOR) -> customRepositories += arg else -> pluginIds += PluginId.getId(arg) } } if (customRepositories.isNotEmpty()) { val hosts = System.getProperty("idea.plugin.hosts") val newHosts = customRepositories.joinToString(separator = ";", prefix = if (hosts.isNullOrBlank()) "" else "${hosts};") System.setProperty("idea.plugin.hosts", newHosts) println("plugin hosts: $newHosts") LOG.info("plugin hosts: $newHosts") } println("installing: $pluginIds") LOG.info("installing: $pluginIds") installAndEnable(null, pluginIds) {} exitProcess(0) } catch (t: Throwable) { LOG.error(t) exitProcess(1) } } }
apache-2.0
fc11c5809b0194d4cd75e182db9676cc
33.509804
128
0.692614
4.345679
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/PrimaryConstructorDetectConversion.kt
2
3491
// 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.nj2k.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.declarationList import org.jetbrains.kotlin.nj2k.mutate import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.tree.JKClass.ClassKind.* class PrimaryConstructorDetectConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element is JKClass && (element.classKind == CLASS || element.classKind == ENUM || element.classKind == RECORD)) { processClass(element) } return recurse(element) } private fun processClass(element: JKClass) { val constructors = element.declarationList.filterIsInstance<JKConstructor>() if (constructors.any { it is JKKtPrimaryConstructor }) return val primaryConstructorCandidate = detectPrimaryConstructor(constructors) ?: return val delegationCall = primaryConstructorCandidate.delegationCall as? JKDelegationConstructorCall if (delegationCall?.expression is JKThisExpression) return primaryConstructorCandidate.invalidate() if (primaryConstructorCandidate.block.statements.isNotEmpty()) { val initDeclaration = JKKtInitDeclaration(primaryConstructorCandidate.block) .withFormattingFrom(primaryConstructorCandidate) primaryConstructorCandidate.clearFormatting() primaryConstructorCandidate.forEachModifier { modifierElement -> modifierElement.clearFormatting() } val lastInitBlockOrFieldIndex = element.classBody.declarations.indexOfLast { it is JKInitDeclaration || it is JKField } element.classBody.declarations = element.classBody.declarations.mutate { val insertAfter = maxOf(lastInitBlockOrFieldIndex, indexOf(primaryConstructorCandidate)) add(insertAfter + 1, initDeclaration) remove(primaryConstructorCandidate) } } else { element.classBody.declarations -= primaryConstructorCandidate } val primaryConstructor = JKKtPrimaryConstructor( primaryConstructorCandidate.name, primaryConstructorCandidate.parameters, primaryConstructorCandidate.delegationCall, primaryConstructorCandidate.annotationList, primaryConstructorCandidate.otherModifierElements, primaryConstructorCandidate.visibilityElement, primaryConstructorCandidate.modalityElement ).withFormattingFrom(primaryConstructorCandidate) symbolProvider.transferSymbol(primaryConstructor, primaryConstructorCandidate) element.classBody.declarations += primaryConstructor } private fun detectPrimaryConstructor(constructors: List<JKConstructor>): JKConstructor? { val constructorsWithoutOtherConstructorCall = constructors.filterNot { (it.delegationCall as? JKDelegationConstructorCall)?.expression is JKThisExpression } return constructorsWithoutOtherConstructorCall.singleOrNull() } }
apache-2.0
988093128d74db44716d5f7d3f606e27
51.119403
158
0.725294
6.018966
false
false
false
false
ftomassetti/kolasu
playground/src/test/kotlin/com/strumenta/kolasu/playground/TranspilationTraceTest.kt
1
4626
package com.strumenta.kolasu.playground import com.strumenta.kolasu.emf.MetamodelBuilder import com.strumenta.kolasu.model.Named import com.strumenta.kolasu.model.Node import com.strumenta.kolasu.validation.Issue import com.strumenta.kolasu.validation.IssueSeverity import com.strumenta.kolasu.validation.IssueType import com.strumenta.kolasu.validation.Result import org.junit.Test import kotlin.test.assertEquals data class ANode(override val name: String, val value: Int) : Node(), Named class TranspilationTraceTest { val mm = MetamodelBuilder( "com.strumenta.kolasu.playground", "http://mypackage.com", "myp" ).apply { provideClass(ANode::class) }.generate() @Test fun serializeTranslationIssues() { val tt = TranspilationTrace( "a:1", "b:2", ANode("a", 1), ANode("b", 2), listOf(Issue(IssueType.TRANSLATION, "some issue", IssueSeverity.WARNING)) ) assertEquals( """{ "eClass" : "https://strumenta.com/starlasu/transpilation/v1#//TranspilationTrace", "originalCode" : "a:1", "sourceResult" : { "root" : { "eClass" : "http://mypackage.com#//ANode", "name" : "a", "value" : 1 } }, "targetResult" : { "root" : { "eClass" : "http://mypackage.com#//ANode", "name" : "b", "value" : 2 } }, "generatedCode" : "b:2", "issues" : [ { "message" : "some issue", "severity" : "WARNING" } ] }""", tt.saveAsJson("foo.json", mm) ) } @Test fun serializeSourceIssues() { val tt = TranspilationTrace( "a:1", "b:2", Result(listOf(Issue(IssueType.SYNTACTIC, "some issue", IssueSeverity.WARNING)), ANode("a", 1)), Result(emptyList(), ANode("b", 2)) ) assertEquals( """{ "eClass" : "https://strumenta.com/starlasu/transpilation/v1#//TranspilationTrace", "originalCode" : "a:1", "sourceResult" : { "root" : { "eClass" : "http://mypackage.com#//ANode", "name" : "a", "value" : 1 }, "issues" : [ { "type" : "SYNTACTIC", "message" : "some issue", "severity" : "WARNING" } ] }, "targetResult" : { "root" : { "eClass" : "http://mypackage.com#//ANode", "name" : "b", "value" : 2 } }, "generatedCode" : "b:2" }""", tt.saveAsJson("foo.json", mm) ) } @Test fun serializeTargetIssues() { val tt = TranspilationTrace( "a:1", "b:2", Result(emptyList(), ANode("a", 1)), Result(listOf(Issue(IssueType.SYNTACTIC, "some issue", IssueSeverity.WARNING)), ANode("b", 2)) ) assertEquals( """{ "eClass" : "https://strumenta.com/starlasu/transpilation/v1#//TranspilationTrace", "originalCode" : "a:1", "sourceResult" : { "root" : { "eClass" : "http://mypackage.com#//ANode", "name" : "a", "value" : 1 } }, "targetResult" : { "root" : { "eClass" : "http://mypackage.com#//ANode", "name" : "b", "value" : 2 }, "issues" : [ { "type" : "SYNTACTIC", "message" : "some issue", "severity" : "WARNING" } ] }, "generatedCode" : "b:2" }""", tt.saveAsJson("foo.json", mm) ) } @Test fun serializeSourceAndDestination() { val aRoot = ANode("a", 1) val bRoot = ANode("b", 2) aRoot.destination = bRoot bRoot.origin = aRoot val tt = TranspilationTrace( "a:1", "b:2", Result(emptyList(), aRoot), Result(emptyList(), bRoot) ) assertEquals( """{ "eClass" : "https://strumenta.com/starlasu/transpilation/v1#//TranspilationTrace", "originalCode" : "a:1", "sourceResult" : { "root" : { "eClass" : "http://mypackage.com#//ANode", "destination" : { "eClass" : "https://strumenta.com/starlasu/v2#//NodeDestination", "node" : { "eClass" : "http://mypackage.com#//ANode", "${'$'}ref" : "//@targetResult/@root" } }, "name" : "a", "value" : 1 } }, "targetResult" : { "root" : { "eClass" : "http://mypackage.com#//ANode", "origin" : { "eClass" : "https://strumenta.com/starlasu/v2#//NodeOrigin", "node" : { "eClass" : "http://mypackage.com#//ANode", "${'$'}ref" : "//@sourceResult/@root" } }, "name" : "b", "value" : 2 } }, "generatedCode" : "b:2" }""", tt.saveAsJson("foo.json", mm) ) } }
apache-2.0
3483d3c23678c2071617ea85960ccdb0
25.284091
107
0.524427
3.287846
false
false
false
false
marius-m/wt4
models/src/main/java/lt/markmerkk/entities/LocalTimeGap.kt
1
2664
package lt.markmerkk.entities import lt.markmerkk.round import lt.markmerkk.utils.LogFormatters import org.joda.time.Duration import org.joda.time.LocalTime import org.joda.time.Period data class LocalTimeGap private constructor( val start: LocalTime, val end: LocalTime ) { val period: Period = Period(start, end) val duration: Duration = period.toStandardDuration() fun isOverlapping(otherTimeGap: LocalTimeGap): Boolean { return start.isBefore(otherTimeGap.end) && end.isAfter(otherTimeGap.start) } fun isOverlappingWithAny(otherTimeGaps: List<LocalTimeGap>): Boolean { return otherTimeGaps.any { it.isOverlapping(this) } } fun toStringShort(): String { return "%s - %s".format( LogFormatters.formatTime.print(start), LogFormatters.formatTime.print(end), ) } companion object { val DEFAULT_BREAK_START = LocalTime.MIDNIGHT.plusHours(12) val DEFAULT_BREAK_END = LocalTime.MIDNIGHT.plusHours(13) fun asEmpty(): LocalTimeGap { return LocalTimeGap(start = LocalTime.MIDNIGHT, end = LocalTime.MIDNIGHT) } fun asDefaultBreak(): LocalTimeGap { return LocalTimeGap( start = DEFAULT_BREAK_START, end = DEFAULT_BREAK_END, ) } /** * Ensures the time gap is a valid one */ fun from(start: LocalTime, end: LocalTime): LocalTimeGap { val rStart = start.round() val rEnd = end.round() if (rStart.isEqual(rEnd) || rEnd.isBefore(rStart)) { return LocalTimeGap(rStart, rStart) } return LocalTimeGap(rStart, rEnd) } } } fun List<LocalTimeGap>.hasOverlapping(): Boolean { val scannedTimeGaps = mutableListOf<LocalTimeGap>() val timeGapWithOverlap = mutableListOf<LocalTimeGap>() this.forEach { timeGap -> val hasOverlap = timeGap.isOverlappingWithAny(scannedTimeGaps) if (hasOverlap) { timeGapWithOverlap.add(timeGap) } scannedTimeGaps.add(timeGap) } return timeGapWithOverlap.isNotEmpty() } fun List<LocalTimeGap>.ignoreOverlapping(): List<LocalTimeGap> { val scannedTimeGaps = mutableListOf<LocalTimeGap>() val timeGapWithOverlap = mutableListOf<LocalTimeGap>() this.forEach { timeGap -> val hasOverlap = timeGap.isOverlappingWithAny(scannedTimeGaps) if (hasOverlap) { timeGapWithOverlap.add(timeGap) } scannedTimeGaps.add(timeGap) } return this.minus(timeGapWithOverlap) }
apache-2.0
b697a39eff9274aac26f6eac7a7ef139
30.341176
85
0.638514
4.289855
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-host-common/jvm/src/io/ktor/server/engine/internal/AutoReloadUtils.kt
1
2789
/* * 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.server.engine.internal import io.ktor.server.application.* import java.lang.reflect.* import java.nio.file.* import kotlin.reflect.* import kotlin.reflect.full.* import kotlin.reflect.jvm.* internal val currentStartupModules = ThreadLocal<MutableList<String>>() internal val ApplicationEnvironmentClassInstance = ApplicationEnvironment::class.java internal val ApplicationClassInstance = Application::class.java internal fun isApplicationEnvironment(parameter: KParameter): Boolean = isParameterOfType(parameter, ApplicationEnvironmentClassInstance) internal fun isApplication(parameter: KParameter): Boolean = isParameterOfType(parameter, ApplicationClassInstance) internal fun ClassLoader.loadClassOrNull(name: String): Class<*>? = try { loadClass(name) } catch (cause: ClassNotFoundException) { null } internal fun isParameterOfType(parameter: KParameter, type: Class<*>) = (parameter.type.javaType as? Class<*>)?.let { type.isAssignableFrom(it) } ?: false internal fun <R> List<KFunction<R>>.bestFunction(): KFunction<R>? = sortedWith( compareBy( { it.parameters.isNotEmpty() && isApplication(it.parameters[0]) }, { it.parameters.count { !it.isOptional } }, { it.parameters.size } ) ).lastOrNull() internal fun KFunction<*>.isApplicableFunction(): Boolean { if (isOperator || isInfix || isInline || isAbstract) return false if (isSuspend) return false // not supported yet extensionReceiverParameter?.let { if (!isApplication(it) && !isApplicationEnvironment(it)) return false } javaMethod?.let { if (it.isSynthetic) return false // static no-arg function is useless as a module function since no application instance available // so nothing could be configured if (Modifier.isStatic(it.modifiers) && parameters.isEmpty()) { return false } } return parameters.all { isApplication(it) || isApplicationEnvironment(it) || it.kind == KParameter.Kind.INSTANCE || it.isOptional } } internal fun Class<*>.takeIfNotFacade(): KClass<*>? = if (getAnnotation(Metadata::class.java)?.takeIf { it.kind == 1 } != null) kotlin else null @Suppress("FunctionName") internal fun get_com_sun_nio_file_SensitivityWatchEventModifier_HIGH(): WatchEvent.Modifier? { if (System.getenv("ANDROID_DATA") != null) return null return try { val modifierClass = Class.forName("com.sun.nio.file.SensitivityWatchEventModifier") val field = modifierClass.getField("HIGH") field.get(modifierClass) as? WatchEvent.Modifier } catch (cause: Throwable) { null } }
apache-2.0
281ddd8292de522f50125531ab0b05d8
34.75641
118
0.713159
4.412975
false
false
false
false
codebutler/farebot
farebot-app/src/main/java/com/codebutler/farebot/app/core/serialize/gson/CardKeysGsonTypeAdapterFactory.kt
1
3100
/* * CardKeysGsonTypeAdapterFactory.kt * * This file is part of FareBot. * Learn more at: https://codebutler.github.io/farebot/ * * Copyright (C) 2017 Eric Butler <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.farebot.app.core.serialize.gson import com.codebutler.farebot.card.CardType import com.codebutler.farebot.card.classic.key.ClassicCardKeys import com.codebutler.farebot.key.CardKeys import com.google.gson.Gson import com.google.gson.TypeAdapter import com.google.gson.TypeAdapterFactory import com.google.gson.internal.Streams import com.google.gson.reflect.TypeToken import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import java.util.HashMap class CardKeysGsonTypeAdapterFactory : TypeAdapterFactory { companion object { private val KEY_CARD_TYPE = "cardType" private val CLASSES = mapOf( CardType.MifareClassic to ClassicCardKeys::class.java ) } @Suppress("UNCHECKED_CAST") override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? { if (!CardKeys::class.java.isAssignableFrom(type.rawType)) { return null } val delegates = HashMap<CardType, TypeAdapter<CardKeys>>() for ((key, value) in CLASSES) { delegates.put(key, gson.getDelegateAdapter(this, TypeToken.get(value) as TypeToken<CardKeys>)) } return CardKeysTypeAdapter(delegates) as TypeAdapter<T> } private inner class CardKeysTypeAdapter internal constructor( private val delegates: Map<CardType, TypeAdapter<CardKeys>> ) : TypeAdapter<CardKeys>() { override fun write(out: JsonWriter, value: CardKeys) { val delegateAdapter = delegates[value.cardType()] ?: throw IllegalArgumentException("Unknown type: ${value.cardType()}") val jsonObject = delegateAdapter.toJsonTree(value).asJsonObject Streams.write(jsonObject, out) } override fun read(inJsonReader: JsonReader): CardKeys { val rootElement = Streams.parse(inJsonReader) val typeElement = rootElement.asJsonObject.get(KEY_CARD_TYPE) val cardType = CardType.valueOf(typeElement.asString) val delegateAdapter = delegates[cardType] ?: throw IllegalArgumentException("Unknown type: $cardType") return delegateAdapter.fromJsonTree(rootElement) } } }
gpl-3.0
2c3d4a423046fa1b557d679cc1ba24a5
38.240506
106
0.703226
4.460432
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/AutoFitRecyclerView.kt
2
2078
package org.wikipedia.views import android.content.Context import android.util.AttributeSet import androidx.core.content.withStyledAttributes import androidx.recyclerview.widget.RecyclerView import org.wikipedia.R import org.wikipedia.util.log.L.logRemoteErrorIfProd import androidx.annotation.IntRange as AndroidIntRange /** [RecyclerView] that invokes a callback when the number of columns should be updated. */ open class AutoFitRecyclerView constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RecyclerView(context, attrs, defStyleAttr) { interface Callback { fun onColumns(columns: Int) } private var minColumnWidth = 0 @AndroidIntRange(from = MIN_COLUMNS.toLong()) var columns = MIN_COLUMNS var callback: Callback = DefaultCallback() init { if (attrs != null) { context.withStyledAttributes(attrs, R.styleable.AutoFitRecyclerView, defStyleAttr) { minColumnWidth = getDimensionPixelSize(R.styleable.AutoFitRecyclerView_minColumnWidth, 0) } } } override fun onMeasure(widthSpec: Int, heightSpec: Int) { super.onMeasure(widthSpec, heightSpec) val cols = calculateColumns(minColumnWidth, measuredWidth) if (columns != cols) { columns = cols callback.onColumns(columns) } } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { // https://issuetracker.google.com/issues/37034096 // TODO: check again in Sep 2021 try { super.onLayout(changed, l, t, r, b) } catch (e: Exception) { logRemoteErrorIfProd(e) } } private fun calculateColumns(columnWidth: Int, availableWidth: Int): Int { return if (columnWidth > 0) MIN_COLUMNS.coerceAtLeast(availableWidth / columnWidth) else MIN_COLUMNS } private class DefaultCallback : Callback { override fun onColumns(columns: Int) {} } companion object { private const val MIN_COLUMNS = 1 } }
apache-2.0
956fabe9401ad81f8533dcb722f9cfb2
32.516129
114
0.672281
4.488121
false
false
false
false
iSoron/uhabits
uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/models/EntryList.kt
1
12284
/* * 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.uhabits.core.models import org.isoron.uhabits.core.models.Entry.Companion.SKIP import org.isoron.uhabits.core.models.Entry.Companion.UNKNOWN import org.isoron.uhabits.core.models.Entry.Companion.YES_AUTO import org.isoron.uhabits.core.models.Entry.Companion.YES_MANUAL import org.isoron.uhabits.core.utils.DateUtils import java.util.ArrayList import java.util.Calendar import javax.annotation.concurrent.ThreadSafe import kotlin.collections.set import kotlin.math.max import kotlin.math.min @ThreadSafe open class EntryList { private val entriesByTimestamp: HashMap<Timestamp, Entry> = HashMap() /** * Returns the entry corresponding to the given timestamp. If no entry with such timestamp * has been previously added, returns Entry(timestamp, UNKNOWN). */ @Synchronized open fun get(timestamp: Timestamp): Entry { return entriesByTimestamp[timestamp] ?: Entry(timestamp, UNKNOWN) } /** * Returns one entry for each day in the given interval. The first element corresponds to the * newest entry, and the last element corresponds to the oldest. The interval endpoints are * included. */ @Synchronized open fun getByInterval(from: Timestamp, to: Timestamp): List<Entry> { val result = mutableListOf<Entry>() if (from.isNewerThan(to)) return result var current = to while (current >= from) { result.add(get(current)) current = current.minus(1) } return result } /** * Adds the given entry to the list. If another entry with the same timestamp already exists, * replaces it. */ @Synchronized open fun add(entry: Entry) { entriesByTimestamp[entry.timestamp] = entry } /** * Returns all entries whose values are known, sorted by timestamp. The first element * corresponds to the newest entry, and the last element corresponds to the oldest. */ @Synchronized open fun getKnown(): List<Entry> { return entriesByTimestamp.values.sortedBy { it.timestamp }.reversed() } /** * Replaces all entries in this list by entries computed automatically from another list. * * For boolean habits, this function creates additional entries (with value YES_AUTO) according * to the frequency of the habit. For numerical habits, this function simply copies all entries. */ @Synchronized open fun recomputeFrom( originalEntries: EntryList, frequency: Frequency, isNumerical: Boolean, ) { clear() val original = originalEntries.getKnown() if (isNumerical) { original.forEach { add(it) } } else { val intervals = buildIntervals(frequency, original) snapIntervalsTogether(intervals) val computed = buildEntriesFromInterval(original, intervals) computed.filter { it.value != UNKNOWN || it.notes.isNotEmpty() }.forEach { add(it) } } } /** * Removes all known entries. */ @Synchronized open fun clear() { entriesByTimestamp.clear() } /** * Returns the total number of successful entries for each month, grouped by day of week. * <p> * The checkmarks are returned in a HashMap. The key is the timestamp for * the first day of the month, at midnight (00:00). The value is an integer * array with 7 entries. The first entry contains the total number of * successful checkmarks during the specified month that occurred on a Saturday. The * second entry corresponds to Sunday, and so on. If there are no * successful checkmarks during a certain month, the value is null. * * @return total number of checkmarks by month versus day of week */ @Synchronized fun computeWeekdayFrequency(isNumerical: Boolean): HashMap<Timestamp, Array<Int>> { val entries = getKnown() val map = hashMapOf<Timestamp, Array<Int>>() for ((originalTimestamp, value) in entries) { val weekday = originalTimestamp.weekday val truncatedTimestamp = Timestamp( originalTimestamp.toCalendar().apply { set(Calendar.DAY_OF_MONTH, 1) }.timeInMillis ) var list = map[truncatedTimestamp] if (list == null) { list = arrayOf(0, 0, 0, 0, 0, 0, 0) map[truncatedTimestamp] = list } if (isNumerical) { list[weekday] += value } else if (value == YES_MANUAL) { list[weekday] += 1 } } return map } data class Interval(val begin: Timestamp, val center: Timestamp, val end: Timestamp) { val length: Int get() = begin.daysUntil(end) + 1 } companion object { /** * Converts a list of intervals into a list of entries. Entries that fall outside of any * interval receive value UNKNOWN. Entries that fall within an interval but do not appear * in [original] receive value YES_AUTO. Entries provided in [original] are copied over. * * The intervals should be sorted by timestamp. The first element in the list should * correspond to the newest interval. */ fun buildEntriesFromInterval( original: List<Entry>, intervals: List<Interval>, ): List<Entry> { val result = arrayListOf<Entry>() if (original.isEmpty()) return result var from = original[0].timestamp var to = original[0].timestamp for (e in original) { if (e.timestamp < from) from = e.timestamp if (e.timestamp > to) to = e.timestamp } for (interval in intervals) { if (interval.begin < from) from = interval.begin if (interval.end > to) to = interval.end } // Create unknown entries var current = to while (current >= from) { result.add(Entry(current, UNKNOWN)) current = current.minus(1) } // Create YES_AUTO entries intervals.forEach { interval -> current = interval.end while (current >= interval.begin) { val offset = current.daysUntil(to) result[offset] = Entry(current, YES_AUTO) current = current.minus(1) } } // Copy original entries original.forEach { entry -> val offset = entry.timestamp.daysUntil(to) if (result[offset].value == UNKNOWN || entry.value == SKIP || entry.value == YES_MANUAL) { result[offset] = entry } } return result } /** * Starting from the second newest interval, this function tries to slide the * intervals backwards into the past, so that gaps are eliminated and * streaks are maximized. * * The intervals should be sorted by timestamp. The first element in the list should * correspond to the newest interval. */ fun snapIntervalsTogether(intervals: ArrayList<Interval>) { for (i in 1 until intervals.size) { val curr = intervals[i] val next = intervals[i - 1] val gapNextToCurrent = next.begin.daysUntil(curr.end) val gapCenterToEnd = curr.center.daysUntil(curr.end) if (gapNextToCurrent >= 0) { val shift = min(gapCenterToEnd, gapNextToCurrent + 1) intervals[i] = Interval( curr.begin.minus(shift), curr.center, curr.end.minus(shift) ) } } } fun buildIntervals( freq: Frequency, entries: List<Entry>, ): ArrayList<Interval> { val filtered = entries.filter { it.value == YES_MANUAL } val num = freq.numerator val den = freq.denominator val intervals = arrayListOf<Interval>() for (i in num - 1 until filtered.size) { val (begin, _) = filtered[i] val (center, _) = filtered[i - num + 1] var size = den if (den == 30 || den == 31) { val beginDate = begin.toLocalDate() size = if (beginDate.day == beginDate.monthLength) { beginDate.plus(1).monthLength } else { beginDate.monthLength } } if (begin.daysUntil(center) < size) { val end = begin.plus(size - 1) intervals.add(Interval(begin, center, end)) } } return intervals } } } /** * Given a list of entries, truncates the timestamp of each entry (according to the field given), * groups the entries according to this truncated timestamp, then creates a new entry (t,v) for * each group, where t is the truncated timestamp and v is the sum of the values of all entries in * the group. * * For numerical habits, non-positive entry values are converted to zero. For boolean habits, each * YES_MANUAL value is converted to 1000 and all other values are converted to zero. * * SKIP values are converted to zero (if they weren't, each SKIP day would count as 0.003). * * The returned list is sorted by timestamp, with the newest entry coming first and the oldest entry * coming last. If the original list has gaps in it (for example, weeks or months without any * entries), then the list produced by this method will also have gaps. * * The argument [firstWeekday] is only relevant when truncating by week. */ fun List<Entry>.groupedSum( truncateField: DateUtils.TruncateField, firstWeekday: Int = Calendar.SATURDAY, isNumerical: Boolean, ): List<Entry> { return this.map { (timestamp, value) -> if (isNumerical) { if (value == SKIP) Entry(timestamp, 0) else Entry(timestamp, max(0, value)) } else { Entry(timestamp, if (value == YES_MANUAL) 1000 else 0) } }.groupBy { entry -> entry.timestamp.truncate( truncateField, firstWeekday, ) }.entries.map { (timestamp, entries) -> Entry(timestamp, entries.sumOf { it.value }) }.sortedBy { (timestamp, _) -> -timestamp.unixTime } } /** * Counts the number of days with vaLue SKIP in the given period. */ fun List<Entry>.countSkippedDays( truncateField: DateUtils.TruncateField, firstWeekday: Int = Calendar.SATURDAY ): List<Entry> { return this.map { (timestamp, value) -> if (value == SKIP) { Entry(timestamp, 1) } else { Entry(timestamp, 0) } }.groupBy { entry -> entry.timestamp.truncate( truncateField, firstWeekday, ) }.entries.map { (timestamp, entries) -> Entry(timestamp, entries.sumOf { it.value }) }.sortedBy { (timestamp, _) -> -timestamp.unixTime } }
gpl-3.0
2da331d3f0e2c534e95f950f62e4ade6
35.556548
106
0.593178
4.626365
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/region/RegionIteratorFlat3D.kt
1
2650
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.region class RegionIteratorFlat3D( region: RegionFlat, private val flatIterator: MutableIterator<RegionVector2D> ) : MutableIterator<RegionVectorBlock> { private val minY: Int = region.minimumY private val maxY: Int = region.maximumY private var next2D: RegionVector2D? = if(flatIterator.hasNext()) flatIterator.next() else null private var nextY: Int = minY constructor(region: RegionFlat) : this(region, region.asRegionFlat().iterator()) override fun hasNext(): Boolean = next2D != null override fun next(): RegionVectorBlock { if(!hasNext()) throw NoSuchElementException() val current = RegionVectorBlock(next2D!!.blockX, nextY, next2D!!.blockZ) when { nextY < maxY -> nextY += 1 flatIterator.hasNext() -> { next2D = flatIterator.next() nextY = minY } else -> next2D = null } return current } override fun remove() = throw UnsupportedOperationException() }
gpl-3.0
0c901ee19a393e92266cdeac698c18ad
36.323944
98
0.692075
4.281099
false
false
false
false
adjack/ExampleTools
lifefinancetool/src/main/java/com/yuan/lifefinance/tool/MainActivity.kt
1
7831
package com.yuan.lifefinance.tool import android.Manifest import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.Environment import android.support.v4.content.FileProvider import android.text.TextUtils import android.view.View import android.widget.Toast import com.yuan.lifefinance.tool.greendao.DBManager import com.yuan.lifefinance.tool.services.StockPriceService import com.yuan.lifefinance.tool.tools.* import com.yuan.lifefinance.tool.view.CustomHintDialog import kotlinx.android.synthetic.main.activity_main.* import java.io.File import java.text.SimpleDateFormat import java.util.* class MainActivity : BaseActivity(), PermissionTools.PermissionDealListener { internal var permissionlist = HashMap<String, String>() internal var permissionTools: PermissionTools? =null private var permissionIsOk: Boolean = false internal var rvalue: Double = 0.toDouble() internal var nowDate = "" var strs:String ?= null private val isDataOk: Boolean get() { if (et_name?.text.isNullOrBlank()) { Toast.makeText(this@MainActivity, "请输入名称!", Toast.LENGTH_SHORT).show() return false } if (StringInputUtils.valueIsEmpty(et_code!!) && StringInputUtils.value(et_code!!).length == 6) { Toast.makeText(this@MainActivity, "请输入个股代码!", Toast.LENGTH_SHORT).show() return false } if (StringInputUtils.valueIsEmpty(et_cost!!)) { Toast.makeText(this@MainActivity, "买入价格为空!", Toast.LENGTH_SHORT).show() return false } if (StringInputUtils.valueIsEmpty(et_stopLoss!!)) { Toast.makeText(this@MainActivity, "止损价格为空!", Toast.LENGTH_SHORT).show() return false } if (StringInputUtils.valueIsEmpty(et_mostPrice!!)) { Toast.makeText(this@MainActivity, "目标价格为空!", Toast.LENGTH_SHORT).show() return false } if (StringInputUtils.valueIsEmpty(tv_rValue!!)) { Toast.makeText(this@MainActivity, "R比率为空!", Toast.LENGTH_SHORT).show() return false } return true } init { permissionlist[Manifest.permission.WRITE_EXTERNAL_STORAGE] = "获取存储权限" } override fun permissionForbidden(noGrantpermissionDislist: ArrayList<String>) { permissionTools?.showPermissionDialog(noGrantpermissionDislist) } override fun permissionRefuse() {} override fun permissionPass() { permissionIsOk = true } internal override fun bindLayout(): Int { return R.layout.activity_main } internal override fun initData() { // initView() permissionTools = PermissionTools.getInstance(this, permissionlist, this) permissionTools?.requestRunPermission(false) setDate() startService(Intent(this, StockPriceService::class.java)) } private fun textss() { } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) tv_refreshRValue?.setOnClickListener { v: View -> try { val value1 = java.lang.Double.valueOf(StringInputUtils.value(et_cost!!)) - java.lang.Double.valueOf(StringInputUtils.value(et_stopLoss!!)) val value2 = java.lang.Double.valueOf(StringInputUtils.value(et_mostPrice!!)) - java.lang.Double.valueOf(StringInputUtils.value(et_cost!!)) rvalue = value2 / value1 tv_rValue?.setTextColor(if (rvalue < 3) Color.parseColor("#008B45") else Color.RED) tv_rValue?.text = DoubleTools.dealMaximumFractionDigits(rvalue, 2) val value3 = java.lang.Double.valueOf(DoubleTools.dealMaximumFractionDigits(value2 / java.lang.Double.valueOf(StringInputUtils.value(et_cost!!)) * 100, 2)) tv_income!!.text = DoubleTools.dealMaximumFractionDigits(value3, 2) + "%" } catch (ex: Exception) { } } } fun onclickSell(view: View) { startActivity(Intent(this@MainActivity, HistoryInfoActivity::class.java)) } override fun onResume() { super.onResume() if (tv_time != null) { nowDate = "" tv_time?.text = "日期:" + TimeTools.dealTime(getNowDate()) } } private fun setDate() { tv_time?.text = "日期:" + getNowDate() } private fun getNowDate(): String { if (TextUtils.isEmpty(nowDate)) { val simpleDateFormat = SimpleDateFormat("yyyyMMddHH:mm:ss")// HH:mm:ss //获取当前时间 val date = Date(System.currentTimeMillis()) nowDate = simpleDateFormat.format(date) } return nowDate } fun onclick(view: View) { if (isDataOk) { val value = if (rvalue < 3) "R比率很低哦,谨慎下单哦!" else "确定下单!" CustomHintDialog(this@MainActivity, { savaData() }, value, "取消", "下单", CustomHintDialog.Dialog_TYPE_1) } } fun onclickCompare(view: View) { // if(isDataOk()){ // new CustomHintDialog(MainActivity.this, ()->savaDataToTempStockInfo(),"添加到比对池","取消", "添加",CustomHintDialog.Dialog_TYPE_1); // } startActivity(Intent(this@MainActivity, TempStockInfoActivity::class.java)) } fun onclickOpenFile(view: View) { // 判断sd卡是否存在 if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) { val dirName = Environment.getExternalStorageDirectory().absolutePath + File.separator + "finance" val file = File(dirName) if (null == file || !file.exists()) { return } val intent = Intent(Intent.ACTION_VIEW) // intent.addCategory(Intent.CATEGORY_OPENABLE); val contentUri = FileProvider.getUriForFile(this@MainActivity, "com.yuan.lifefinance.tool.fileprovider", file) intent.setDataAndType(contentUri, "*/*") startActivity(intent) } } //下单保存 fun savaData() { try { //保存数据库信息 val stokeName = StringInputUtils.value(et_name!!) val cost = StringInputUtils.value(et_cost!!) val stopLoss = java.lang.Double.valueOf(StringInputUtils.value(et_stopLoss!!)) val mostPrice = java.lang.Double.valueOf(StringInputUtils.value(et_mostPrice!!)) val rValue = java.lang.Double.valueOf(StringInputUtils.value(tv_rValue!!)) val result = DBManager.getInstance().savaStockInfo(stokeName, StringInputUtils.value(et_code!!), cost, stopLoss, mostPrice, rValue, nowDate) LogUtil.d("savaStockInfo", "result:$result") //截图保存 val nowdate = getNowDate().replace(" ", "") FileTools.saveToSD(ActivityUtils.activityShot(this@MainActivity), et_name!!.text.toString() + "_" + nowdate) Toast.makeText(this@MainActivity, "保存成功", Toast.LENGTH_SHORT).show() clearData() } catch (ex: Exception) { Toast.makeText(this@MainActivity, ex.toString(), Toast.LENGTH_SHORT).show() } } private fun clearData() { et_name?.setText("") et_code?.setText("") et_cost?.setText("") et_stopLoss?.setText("") et_mostPrice?.setText("") tv_rValue?.text = "" nowDate = "" nowDate = getNowDate() tv_time?.text = "日期:" + TimeTools.dealTime(getNowDate()) } }
apache-2.0
9c4b7fcc86f6abe32b810ef5923c714f
35.868932
171
0.61817
4.189189
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/search/KotlinUseScopeTest.kt
1
11510
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.search import com.intellij.openapi.module.JavaModuleType import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.PsiNamedElement import com.intellij.psi.search.SearchScope import com.intellij.testFramework.PsiTestUtil import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase import junit.framework.TestCase import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.base.psi.kotlinFqName import org.jetbrains.kotlin.idea.search.useScope import org.jetbrains.kotlin.psi.KtNamedDeclaration import kotlin.test.assertNotEquals class KotlinUseScopeTest : JavaCodeInsightFixtureTestCase() { fun `test all`() { val moduleA = PsiTestUtil.addModule( project, JavaModuleType.getModuleType(), "ModuleA", myFixture.tempDirFixture.findOrCreateDir("ModuleA"), ) myFixture.addFileToProject( "ModuleA/one/PrivateK.kt", """ package one private class PrivateK { private object PrivateNestedObject { object NestedObjectInPrivate {} } private var privateMemberPropertyFromPrivateClass = 42 private fun privateMemberFunctionFromPrivateClass() = 42 var publicMemberPropertyFromPrivateClass = 42 fun publicMemberFunctionFromPrivateClass() = 42 } private object PrivateObject {} private fun privateFunction() = Unit private var privateProperty = 42 fun publicFunction() = Unit var publicProperty = 42 """.trimIndent() ) myFixture.addFileToProject( "ModuleA/one/JavaClass.java", """ package one; public class JavaClass { } """.trimIndent() ) myFixture.addFileToProject( "ModuleA/two/OtherJavaClass.java", """ package two; public class OtherJavaClass { } """.trimIndent() ) myFixture.addFileToProject("ModuleA/one/KK.kt", "package one\nclass KK{\nclass Nested\n}") myFixture.addFileToProject("ModuleA/two/I.kt", "package two\ninterface I") val moduleB = PsiTestUtil.addModule( project, JavaModuleType.getModuleType(), "ModuleB", myFixture.tempDirFixture.findOrCreateDir("ModuleB"), ) myFixture.addFileToProject( "ModuleB/one/I.kt", """ package one interface I { class Nested { private fun privateMemberFunctionFromNested() = 42 fun publicMemberFunctionFromNested() = 42 private var privateMemberPropertyFromNested = 42 var publicMemberPropertyFromNested = 42 } } fun publicFunction2() {} """.trimIndent(), ) myFixture.addFileToProject( "ModuleB/two/PrivateInterface.kt", "package two\nprivate interface PrivateInterface\nprivate var privateProperty = 42\nvar publicProperty = 42" ) myFixture.addFileToProject("ModuleB/one/JavaModB.java", "package one;\npublic class JavaModB {}") myFixture.addFileToProject("ModuleB/two/JavaModBTwo.java", "package one;\npublic class JavaModBTwo {}") ModuleRootModificationUtil.addDependency(moduleB, moduleA) val moduleAScope = """ global: A/one/JavaClass.java, A/one/KK.kt, A/one/PrivateK.kt, A/two/I.kt, A/two/OtherJavaClass.java, B/one/I.kt, B/one/JavaModB.java, B/two/JavaModBTwo.java, B/two/PrivateInterface.kt, """.trimIndent() assertLightAndOriginalScope(findClass("one.KK"), moduleAScope) assertLightAndOriginalScope(findClass("one.KK.Nested"), moduleAScope) assertLightAndOriginalScope(findClass("two.I"), moduleAScope) assertLightAndOriginalScope(findMethod("one.PrivateKKt", "publicFunction"), moduleAScope) assertLightAndOriginalScope(findMethod("one.PrivateKKt", "getPublicProperty"), moduleAScope) assertLightAndOriginalScope(findMethod("one.PrivateKKt", "setPublicProperty"), moduleAScope) val moduleBScope = """ global: B/one/I.kt, B/one/JavaModB.java, B/two/JavaModBTwo.java, B/two/PrivateInterface.kt, """.trimIndent() assertNotEquals(moduleBScope, moduleAScope) assertLightAndOriginalScope(findClass("one.I"), moduleBScope) assertLightAndOriginalScope(findClass("one.I.Nested"), moduleBScope) assertLightAndOriginalScope(findMethod("one.IKt", "publicFunction2"), moduleBScope) assertLightAndOriginalScope(findMethod("two.PrivateInterfaceKt", "getPublicProperty"), moduleBScope) assertLightAndOriginalScope(findMethod("two.PrivateInterfaceKt", "setPublicProperty"), moduleBScope) assertLightAndOriginalScope(findMethod("one.I.Nested", "getPublicMemberPropertyFromNested"), moduleBScope) assertLightAndOriginalScope(findMethod("one.I.Nested", "setPublicMemberPropertyFromNested"), moduleBScope) assertLightAndOriginalScope(findMethod("one.I.Nested", "publicMemberFunctionFromNested"), moduleBScope) val privateJvmModuleAScope = """ global: A/one/JavaClass.java, A/one/PrivateK.kt, """.trimIndent() assertNotEquals(moduleAScope, privateJvmModuleAScope) assertLightAndOriginalScope(findClass("one.PrivateK"), privateJvmModuleAScope) assertLightAndOriginalScope(findClass("one.PrivateObject"), privateJvmModuleAScope) val restrictedByPrivateKClass = """ local: files: A/one/PrivateK.kt, elements: PrivateK, """.trimIndent() assertLightAndOriginalScope( findClass("one.PrivateK.PrivateNestedObject"), restrictedByPrivateKClass, ) assertLightAndOriginalScope( findClass("one.PrivateK.PrivateNestedObject.NestedObjectInPrivate"), restrictedByPrivateKClass, ) val restrictedLocalByPrivateKFile = """ local: files: A/one/PrivateK.kt, elements: PrivateK.kt, """.trimIndent() assertLightAndOriginalScope( findMethod("one.PrivateKKt", "privateFunction"), restrictedLocalByPrivateKFile, ) val restrictedByPrivateKFile = """ global: A/one/PrivateK.kt, """.trimIndent() assertLightAndOriginalScope( findField("one.PrivateKKt", "privateProperty"), restrictedByPrivateKFile, expectedOriginal = restrictedLocalByPrivateKFile, ) assertLightAndOriginalScope( findMethod("one.PrivateK", "getPublicMemberPropertyFromPrivateClass"), privateJvmModuleAScope, ) assertLightAndOriginalScope( findMethod("one.PrivateK", "setPublicMemberPropertyFromPrivateClass"), privateJvmModuleAScope, ) assertLightAndOriginalScope( findField("one.PrivateKKt", "publicProperty"), restrictedByPrivateKFile, expectedOriginal = moduleAScope, ) assertLightAndOriginalScope( findField("one.PrivateK", "privateMemberPropertyFromPrivateClass"), restrictedByPrivateKFile, expectedOriginal = restrictedByPrivateKClass, ) assertLightAndOriginalScope( findField("one.PrivateK", "publicMemberPropertyFromPrivateClass"), restrictedByPrivateKFile, expectedOriginal = privateJvmModuleAScope, ) assertLightAndOriginalScope( findMethod("one.PrivateK", "publicMemberFunctionFromPrivateClass"), privateJvmModuleAScope, ) assertLightAndOriginalScope( findMethod("one.PrivateK", "privateMemberFunctionFromPrivateClass"), restrictedByPrivateKClass, ) val privateJvmModuleBScope = """ global: B/two/JavaModBTwo.java, B/two/PrivateInterface.kt, """.trimIndent() assertNotEquals(moduleBScope, privateJvmModuleBScope) assertLightAndOriginalScope(findClass("two.PrivateInterface"), privateJvmModuleBScope) val restrictedByPrivateInterfaceFile = """ global: B/two/PrivateInterface.kt, """.trimIndent() assertLightAndOriginalScope( findField("two.PrivateInterfaceKt", "privateProperty"), restrictedByPrivateInterfaceFile, expectedOriginal = """ local: files: B/two/PrivateInterface.kt, elements: PrivateInterface.kt, """.trimIndent(), ) assertLightAndOriginalScope( findField("two.PrivateInterfaceKt", "publicProperty"), restrictedByPrivateInterfaceFile, expectedOriginal = moduleBScope, ) val restrictedByIFile = """ global: B/one/I.kt, """.trimIndent() assertLightAndOriginalScope( findField("one.I.Nested", "publicMemberPropertyFromNested"), restrictedByIFile, expectedOriginal = moduleBScope, ) val restrictedLocalByNestedClass = """ local: files: B/one/I.kt, elements: Nested, """.trimIndent() assertLightAndOriginalScope( findField("one.I.Nested", "privateMemberPropertyFromNested"), restrictedByIFile, expectedOriginal = restrictedLocalByNestedClass ) assertLightAndOriginalScope( findMethod("one.I.Nested", "privateMemberFunctionFromNested"), restrictedLocalByNestedClass, ) } private fun findClass(qualifier: String): PsiClass = myFixture.findClass(qualifier) private fun findMethod(qualifier: String, name: String): PsiMethod = myFixture.findClass(qualifier).findMethodsByName(name, false).single() private fun findField(qualifier: String, name: String): PsiField = myFixture.findClass(qualifier).findFieldByName(name, false)!! } private fun assertLightAndOriginalScope(element: PsiNamedElement, expected: String, expectedOriginal: String = expected) { val ktElement = element.unwrapped as KtNamedDeclaration TestCase.assertEquals("light: ${element.kotlinFqName.toString()}", expected, element.useScope().findFiles()) TestCase.assertEquals("kt: ${ktElement.fqName.toString()}", expectedOriginal, ktElement.useScope().findFiles()) } private fun SearchScope.findFiles() = findFiles { vFile -> vFile.path.substringAfterLast("Module") }
apache-2.0
a693a6f44d005e491fd448459dbc898a
36.132258
122
0.628063
6.112586
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/util/CoroutineUtils.kt
2
6732
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.coroutine.util import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.impl.DebuggerUtilsEx import com.intellij.debugger.jdi.StackFrameProxyImpl import com.intellij.debugger.jdi.ThreadReferenceProxyImpl import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.search.GlobalSearchScope import com.intellij.xdebugger.XDebuggerUtil import com.intellij.xdebugger.XSourcePosition import com.sun.jdi.* import org.jetbrains.kotlin.idea.debugger.* import org.jetbrains.kotlin.idea.debugger.base.util.isSubtype import org.jetbrains.kotlin.idea.debugger.coroutine.data.SuspendExitMode import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runReadAction const val CREATION_STACK_TRACE_SEPARATOR = "\b\b\b" // the "\b\b\b" is used as creation stacktrace separator in kotlinx.coroutines const val CREATION_CLASS_NAME = "_COROUTINE._CREATION" fun Method.isInvokeSuspend(): Boolean = name() == "invokeSuspend" && signature() == "(Ljava/lang/Object;)Ljava/lang/Object;" fun Method.isInvoke(): Boolean = name() == "invoke" && signature().contains("Ljava/lang/Object;)Ljava/lang/Object;") fun Method.isSuspendLambda() = isInvokeSuspend() && declaringType().isSuspendLambda() fun Method.hasContinuationParameter() = signature().contains("Lkotlin/coroutines/Continuation;)") fun Location.getSuspendExitMode(): SuspendExitMode { val method = safeMethod() ?: return SuspendExitMode.NONE if (method.isSuspendLambda()) return SuspendExitMode.SUSPEND_LAMBDA else if (method.hasContinuationParameter()) return SuspendExitMode.SUSPEND_METHOD_PARAMETER else if ((method.isInvokeSuspend() || method.isInvoke()) && safeCoroutineExitPointLineNumber()) return SuspendExitMode.SUSPEND_METHOD return SuspendExitMode.NONE } fun Location.safeCoroutineExitPointLineNumber() = (wrapIllegalArgumentException { DebuggerUtilsEx.getLineNumber(this, false) } ?: -2) == -1 fun ReferenceType.isContinuation() = isBaseContinuationImpl() || isSubtype("kotlin.coroutines.Continuation") fun Type.isBaseContinuationImpl() = isSubtype("kotlin.coroutines.jvm.internal.BaseContinuationImpl") fun Type.isAbstractCoroutine() = isSubtype("kotlinx.coroutines.AbstractCoroutine") fun Type.isCoroutineScope() = isSubtype("kotlinx.coroutines.CoroutineScope") fun Type.isSubTypeOrSame(className: String) = name() == className || isSubtype(className) fun ReferenceType.isSuspendLambda() = SUSPEND_LAMBDA_CLASSES.any { isSubtype(it) } fun Location.isInvokeSuspend() = safeMethod()?.isInvokeSuspend() ?: false fun Location.isInvokeSuspendWithNegativeLineNumber() = isInvokeSuspend() && safeLineNumber() < 0 fun Location.isFilteredInvokeSuspend() = isInvokeSuspend() || isInvokeSuspendWithNegativeLineNumber() fun StackFrameProxyImpl.variableValue(variableName: String): ObjectReference? { val continuationVariable = safeVisibleVariableByName(variableName) ?: return null return getValue(continuationVariable) as? ObjectReference ?: return null } fun StackFrameProxyImpl.continuationVariableValue(): ObjectReference? = variableValue("\$continuation") fun StackFrameProxyImpl.thisVariableValue(): ObjectReference? = this.thisObject() private fun Method.isGetCoroutineSuspended() = signature() == "()Ljava/lang/Object;" && name() == "getCOROUTINE_SUSPENDED" && declaringType().name() == "kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsKt" fun DefaultExecutionContext.findCoroutineMetadataType() = debugProcess.invokeInManagerThread { findClassSafe("kotlin.coroutines.jvm.internal.DebugMetadataKt") } fun DefaultExecutionContext.findDispatchedContinuationReferenceType(): List<ReferenceType>? = vm.classesByName("kotlinx.coroutines.DispatchedContinuation") fun DefaultExecutionContext.findCancellableContinuationImplReferenceType(): List<ReferenceType>? = vm.classesByName("kotlinx.coroutines.CancellableContinuationImpl") fun hasGetCoroutineSuspended(frames: List<StackFrameProxyImpl>) = frames.indexOfFirst { it.safeLocation()?.safeMethod()?.isGetCoroutineSuspended() == true } fun StackTraceElement.isCreationSeparatorFrame() = className.startsWith(CREATION_STACK_TRACE_SEPARATOR) || className == CREATION_CLASS_NAME fun Location.findPosition(project: Project) = runReadAction { if (declaringType() != null) getPosition(project, declaringType().name(), lineNumber()) else null } private fun getPosition(project: Project, className: String, lineNumber: Int): XSourcePosition? { val psiFacade = JavaPsiFacade.getInstance(project) val psiClass = psiFacade.findClass( className.substringBefore("$"), // find outer class, for which psi exists TODO GlobalSearchScope.everythingScope(project) ) val classFile = psiClass?.containingFile?.virtualFile // to convert to 0-based line number or '-1' to do not move val localLineNumber = if (lineNumber > 0) lineNumber - 1 else return null return XDebuggerUtil.getInstance().createPosition(classFile, localLineNumber) } fun SuspendContextImpl.executionContext() = invokeInManagerThread { DefaultExecutionContext(EvaluationContextImpl(this, this.frameProxy)) } fun <T : Any> SuspendContextImpl.invokeInManagerThread(f: () -> T?): T? = debugProcess.invokeInManagerThread { f() } fun ThreadReferenceProxyImpl.supportsEvaluation(): Boolean = threadReference?.isSuspended ?: false fun SuspendContextImpl.supportsEvaluation() = this.debugProcess.canRunEvaluation || isUnitTestMode() fun threadAndContextSupportsEvaluation(suspendContext: SuspendContextImpl, frameProxy: StackFrameProxyImpl?) = suspendContext.invokeInManagerThread { suspendContext.supportsEvaluation() && frameProxy?.threadProxy()?.supportsEvaluation() ?: false } ?: false fun Location.sameLineAndMethod(location: Location?): Boolean = location != null && location.safeMethod() == safeMethod() && location.safeLineNumber() == safeLineNumber() fun Location.isFilterFromTop(location: Location?): Boolean = isFilteredInvokeSuspend() || sameLineAndMethod(location) || location?.safeMethod() == safeMethod() fun Location.isFilterFromBottom(location: Location?): Boolean = sameLineAndMethod(location)
apache-2.0
75d571d4ac5e9188b37dfbd94859477c
42.720779
166
0.774361
4.694561
false
false
false
false
paplorinc/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/VarargArgumentMapping.kt
1
3740
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.impl import com.intellij.psi.* import com.intellij.util.containers.ComparatorUtil.min import org.jetbrains.plugins.groovy.lang.resolve.api.Applicability import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.ArgumentMapping import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments import org.jetbrains.plugins.groovy.util.init import org.jetbrains.plugins.groovy.util.recursionAwareLazy private typealias MapWithVarargs = Pair<Map<Argument, PsiParameter>, Set<Argument>> class VarargArgumentMapping( method: PsiMethod, override val arguments: Arguments, private val context: PsiElement ) : ArgumentMapping { private val varargParameter: PsiParameter = method.parameterList.parameters.last() private val varargType: PsiType = (varargParameter.type as PsiArrayType).componentType private val mapping: MapWithVarargs? by recursionAwareLazy(fun(): MapWithVarargs? { val parameters = method.parameterList.parameters val regularParameters = parameters.init() val regularParametersCount = regularParameters.size if (arguments.size < regularParametersCount) { // not enough arguments return null } val map = arguments.zip(regularParameters).toMap() val varargs = arguments.drop(regularParametersCount) return Pair(map, LinkedHashSet(varargs)) }) override fun targetParameter(argument: Argument): PsiParameter? { val (positional, varargs) = mapping ?: return null if (argument in varargs) { return varargParameter } else { return positional[argument] } } override fun expectedType(argument: Argument): PsiType? { val (positional, varargs) = mapping ?: return null if (argument in varargs) { return varargType } else { return positional[argument]?.type } } override fun isVararg(parameter: PsiParameter): Boolean = varargParameter === parameter override val expectedTypes: Iterable<Pair<PsiType, Argument>> get() { val (positional, varargs) = mapping ?: return emptyList() val positionalSequence = positional.asSequence().map { (argument, parameter) -> Pair(parameter.type, argument) } val varargsSequence = varargs.asSequence().map { Pair(varargType, it) } return (positionalSequence + varargsSequence).asIterable() } override fun applicability(substitutor: PsiSubstitutor, erase: Boolean): Applicability { val (positional, varargs) = mapping ?: return Applicability.inapplicable val mapApplicability = mapApplicability(positional, substitutor, erase, context) if (mapApplicability === Applicability.inapplicable) { return Applicability.inapplicable } val varargApplicability = varargApplicability(parameterType(varargType, substitutor, erase), varargs, context) if (varargApplicability === Applicability.inapplicable) { return Applicability.inapplicable } return min(mapApplicability, varargApplicability) } private fun varargApplicability(parameterType: PsiType?, varargs: Collection<Argument>, context: PsiElement): Applicability { for (vararg in varargs) { val argumentAssignability = argumentApplicability(parameterType, vararg, context) if (argumentAssignability != Applicability.applicable) { return argumentAssignability } } return Applicability.applicable } val varargs: Collection<Argument> get() = requireNotNull(mapping) { "#varargs should not be accessed on inapplicable mapping" }.second }
apache-2.0
69761091128cb9cc6c32b8591357ac99
37.163265
140
0.745989
4.740177
false
false
false
false
deso88/TinyGit
src/main/kotlin/hamburg/remme/tinygit/domain/Commit.kt
1
1105
package hamburg.remme.tinygit.domain import java.time.LocalDateTime open class Commit(val id: String, val parents: List<CommitIsh>, val fullMessage: String, val date: LocalDateTime, val authorName: String, val authorMail: String) : Comparable<Commit> { val shortId: String = id.abbreviate() val parentId = if (parents.isEmpty()) Head.EMPTY.id else parents[0].id val shortParents: List<String> = parents.map { it.id.abbreviate() } val shortMessage: String = fullMessage.lines()[0].substringBefore(". ") val author = "$authorName <$authorMail>" override fun toString() = id override fun compareTo(other: Commit) = -date.compareTo(other.date) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Commit if (id != other.id) return false return true } override fun hashCode() = id.hashCode() private fun String.abbreviate() = substring(0, 8) }
bsd-3-clause
58d6dbada7593d1a024e271aaf5f8460
28.864865
75
0.621719
4.384921
false
false
false
false
suchoX/Addect
app/src/main/java/com/crimson/addect/feature/playscreen/PlayViewModel.kt
1
2436
package com.crimson.addect.feature.playscreen import com.crimson.addect.R import com.crimson.addect.feature.base.BaseViewModel import com.crimson.addect.feature.base.MvvmView import com.crimson.addect.model.SumObject import com.crimson.addect.utils.Resources import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import java.util.Random import java.util.concurrent.TimeUnit.SECONDS import javax.inject.Inject open class PlayViewModel @Inject constructor() : BaseViewModel<MvvmView>() { @Inject lateinit var resources: Resources private var score: Int = 0 private var highScore: Int = 0 private val random: Random = Random() private lateinit var sumText: String private lateinit var sum: SumObject override fun attach() { super.attach() sumText = resources.getString(R.string.get_ready) notifyChange() setQuestionTimer() } private fun setQuestionTimer() { Observable.interval(3, SECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { generateSumObject() } } private fun generateSumObject() { var firstNumber = random.nextInt(1000 + 1) if (score > 10) { firstNumber %= 15 } else { firstNumber %= 10 } var secondNumber = random.nextInt(1000 + 1) if (score > 10) { secondNumber %= 15 } else { secondNumber %= 10 } if (generateRightAnswer()) { sum = SumObject(firstNumber, secondNumber, firstNumber + secondNumber, true) } else { sum = generateWrongAnswer(firstNumber, secondNumber) } sumText = sum.toString() notifyChange() } private fun generateRightAnswer(): Boolean = random.nextBoolean() private fun generateWrongAnswer(firstNumber: Int, secondNumber: Int): SumObject { val moreThanActualAnswer = random.nextBoolean() val difference = random.nextInt(1000) % 6 if (moreThanActualAnswer) { return SumObject(firstNumber, secondNumber, firstNumber + secondNumber + difference, false) } else { val answer = firstNumber + secondNumber if (answer - difference > 0) { return SumObject(firstNumber, secondNumber, firstNumber + secondNumber - difference, false) } else { return generateWrongAnswer(firstNumber, secondNumber) } } } fun getSumText(): String = sumText fun getHighScore(): String = highScore.toString() }
apache-2.0
77498501e2a2e2629ff91da0f7348222
29.08642
99
0.706486
4.164103
false
false
false
false
jmfayard/skripts
test/kotlin/PropertiesTesting.kt
1
4154
import io.kotlintest.properties.Gen import io.kotlintest.properties.forAll import io.kotlintest.shouldBe import io.kotlintest.specs.FreeSpec import java.math.BigInteger /* http://fsharpforfunandprofit.com/posts/property-based-testing-2/ */ class PropertiesTesting : FreeSpec() { init { "Different paths, same destination" - { fun List<Int>.mysort() = this.sorted() // fun List<Int>.mysort() = this.filterNot { it == 10 }.sorted() // fun List<Int>.mysort() = emptyList<Int>() // fun List<Int>.mysort() = this.reversed() val gen = Gen.list(Gen.choose(8, 267)) "Size don't change" { forAll(gen) { list -> list.mysort().size == list.size } } "Pairs are ordered" { forAll(gen) { list -> list.mysort().fold(Int.MIN_VALUE) { previous, value -> if (value < previous) return@forAll false value } true } } "Shuffling order makes no difference" { forAll(gen) { list -> list.reversed().mysort() == list.mysort() } } "Adding one to all elements" { fun List<Int>.increment() = this.map { it + 1 } forAll(gen) { list -> list.mysort().increment() == list.increment().mysort() } } "Using the sortedness of the list" { forAll(gen) { list -> (list + Int.MIN_VALUE).mysort() == listOf(Int.MIN_VALUE) + list.mysort() } } "Negate then sort" { fun List<Int>.negate() = this.map { -it } forAll(gen) { list -> list.mysort().negate() == list.negate().mysort().reversed() } } "There and back again" { forAll(gen) { list -> list.reversed().reversed() == list } } "Idempotence" { forAll(gen) { list -> list.mysort() == list.mysort().mysort() } } } "Property: it never crashes" { forAll { s: String -> try { s.isPalindrome() true } catch (e: Exception) { false } } } "Property: if s is a palindrome, s.inverse() is one too" { var found = 0 forAll { t: String -> val s = t.take(7) // very few palindroms for large strings if (s.isPalindrome()) { found++ s.reversed().isPalindrome() } else { !s.reversed().isPalindrome() } } println("Foupnd $found palindromes") } "Property: three characters" { forAll(Gen.char(), Gen.char()) { a, b -> "$a$b$a".isPalindrome() && "$a$b$b$a".isPalindrome() } } "Hard to prove, easy to verify" { val gen = Gen.list(Gen.choose(1, 100)) fun String.parseCommas(): List<String> = if (isBlank()) listOf() else this.split(",") forAll(gen) { list -> val string = list.joinToString(separator = ",") string.parseCommas() == list.map { it.toString() } } } "Dollars" - { val gen = Gen.choose(0, 10000) "inverses" { forAll(gen) { times -> (3 * times).dollar == 3.dollar * times } } "data class" { forAll(gen) { amount -> amount.dollar == amount.dollar } } } } } fun String.isPalindrome(): Boolean { for (i in 0 until length) { if (get(i) != get(length - i - 1)) return false } return true } fun Gen.Companion.char(): Gen<Char> = Gen.choose(33, 127).map { it.toChar() } val Int.bigint: BigInteger get() = BigInteger.valueOf(this.toLong()) data class Dollar(val amount: Int) { operator fun plus(amount: Int) = Dollar(this.amount + amount) operator fun times(times: Int) = Dollar(this.amount * times) } val Int.dollar get() = Dollar(this)
apache-2.0
64ec34f243ea207b218fa0c7d4cf9197
25.8
93
0.484834
3.952426
false
false
false
false
paplorinc/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/arguments.kt
2
3457
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.impl import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiSubstitutor import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrSpreadArgument import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.lang.psi.util.isEffectivelyVarArgs import org.jetbrains.plugins.groovy.lang.psi.util.isOptional import org.jetbrains.plugins.groovy.lang.resolve.api.* import java.util.* fun GrCall.getArguments(): Arguments? { val argumentList = argumentList ?: return null return getArguments(argumentList.namedArguments, argumentList.expressionArguments, closureArguments, this) } private fun getArguments(namedArguments: Array<out GrNamedArgument>, expressionArguments: Array<out GrExpression>, closureArguments: Array<out GrClosableBlock>, context: PsiElement): Arguments? { val result = ArrayList<Argument>() if (namedArguments.isNotEmpty()) { result += LazyTypeArgument { GrMapType.createFromNamedArgs(context, namedArguments) } } for (expression in expressionArguments) { if (expression is GrSpreadArgument) { val type = expression.argument.type as? GrTupleType ?: return null type.componentTypes.mapTo(result) { JustTypeArgument(it) } } else { result += ExpressionArgument(expression) } } closureArguments.mapTo(result) { ExpressionArgument(it) } return result } fun argumentMapping(method: PsiMethod, substitutor: PsiSubstitutor, arguments: Arguments, context: PsiElement): ArgumentMapping = when { method.isEffectivelyVarArgs -> { val invokedAsIs = run(fun(): Boolean { // call foo(X[]) as is, i.e. with argument of type X[] (or subtype) val parameters = method.parameterList.parameters if (arguments.size != parameters.size) return false val parameterType = parameterType(parameters.last().type, substitutor, true) val lastArgApplicability = argumentApplicability(parameterType, arguments.last(), context) return lastArgApplicability == Applicability.applicable }) if (invokedAsIs) { PositionalArgumentMapping(method, arguments, context) } else { VarargArgumentMapping(method, arguments, context) } } arguments.isEmpty() -> { val parameters = method.parameterList.parameters val parameter = parameters.singleOrNull() if (parameter != null && !parameter.isOptional && parameter.type is PsiClassType && !PsiUtil.isCompileStatic(context)) { NullArgumentMapping(parameter) } else { PositionalArgumentMapping(method, arguments, context) } } else -> PositionalArgumentMapping(method, arguments, context) }
apache-2.0
a87ed0ab09893f6f8ffecf4da2fb12fd
40.154762
140
0.744865
4.449163
false
false
false
false
indianpoptart/RadioControl
RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/fragments/CellFragment.kt
1
1076
package com.nikhilparanjape.radiocontrol.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.nikhilparanjape.radiocontrol.R import com.nikhilparanjape.radiocontrol.adapters.RecyclerAdapter /** * Created by Nikhil on 07/31/2018. * * @author Nikhil Paranjape * * */ class CellFragment : Fragment() { private var cellTrouble = arrayOf("Blacklist", "Crisis", "Gotham", "Banshee", "Breaking Bad") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.cell_fragment, container, false) val rv = rootView.findViewById<RecyclerView>(R.id.cellRV) rv.layoutManager = LinearLayoutManager(this.activity) val adapter = RecyclerAdapter(cellTrouble) rv.adapter = adapter return rootView } }
gpl-3.0
dc67ff8b6b9bac9a5cd5b6bdcdffbbca
28.888889
116
0.757435
4.391837
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/layout/ActionLt.kt
2
1674
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.layout import kotlinx.serialization.Serializable import org.apache.causeway.client.kroviz.to.Link @Serializable data class ActionLt(var named: String? = "", var describedAs: String? = "", var metadataError: String? = "", var link: Link? = null, var id: String? = "", var bookmarking: String? = "", var cssClass: String? = "", var cssClassFa: String? = "", var cssClassFaPosition: String? = "", var hidden: String? = null, var namedEscaped: String? = "", var position: String? = "", var promptStyle: String? = "", val redirect: String? = null )
apache-2.0
17dd8a6daac82d571f7ca4e73eafc3a4
41.923077
64
0.609319
4.561308
false
false
false
false
google/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GithubLoginPanel.kt
2
4448
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.ui import com.intellij.collaboration.async.CompletableFutureUtil.completionOnEdt import com.intellij.collaboration.async.CompletableFutureUtil.errorOnEdt import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.AnimatedIcon import com.intellij.ui.components.fields.ExtendableTextComponent import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.dsl.builder.Panel import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.i18n.GithubBundle.message import org.jetbrains.plugins.github.ui.util.DialogValidationUtils.notBlank import java.util.concurrent.CompletableFuture import javax.swing.JComponent import javax.swing.JTextField internal typealias UniqueLoginPredicate = (login: String, server: GithubServerPath) -> Boolean internal class GithubLoginPanel( executorFactory: GithubApiRequestExecutor.Factory, isAccountUnique: UniqueLoginPredicate ) : Wrapper() { private val serverTextField = ExtendableTextField(GithubServerPath.DEFAULT_HOST, 0) private var tokenAcquisitionError: ValidationInfo? = null private lateinit var currentUi: GHCredentialsUi private var tokenUi = GHTokenCredentialsUi(serverTextField, executorFactory, isAccountUnique) private var oauthUi = GHOAuthCredentialsUi(executorFactory, isAccountUnique) private val progressIcon = AnimatedIcon.Default() private val progressExtension = ExtendableTextComponent.Extension { progressIcon } var footer: Panel.() -> Unit get() = tokenUi.footer set(value) { tokenUi.footer = value oauthUi.footer = value applyUi(currentUi) } init { applyUi(tokenUi) } private fun applyUi(ui: GHCredentialsUi) { currentUi = ui setContent(currentUi.getPanel()) currentUi.getPreferredFocusableComponent()?.requestFocus() tokenAcquisitionError = null } fun getPreferredFocusableComponent(): JComponent? = serverTextField.takeIf { it.isEditable && it.text.isBlank() } ?: currentUi.getPreferredFocusableComponent() fun doValidateAll(): List<ValidationInfo> { val uiError = notBlank(serverTextField, message("credentials.server.cannot.be.empty")) ?: validateServerPath(serverTextField) ?: currentUi.getValidator().invoke() return listOfNotNull(uiError, tokenAcquisitionError) } private fun validateServerPath(field: JTextField): ValidationInfo? = try { GithubServerPath.from(field.text) null } catch (e: Exception) { ValidationInfo(message("credentials.server.path.invalid"), field) } private fun setBusy(busy: Boolean) { serverTextField.apply { if (busy) addExtension(progressExtension) else removeExtension(progressExtension) } serverTextField.isEnabled = !busy currentUi.setBusy(busy) } fun acquireLoginAndToken(progressIndicator: ProgressIndicator): CompletableFuture<Pair<String, String>> { setBusy(true) tokenAcquisitionError = null val server = getServer() val executor = currentUi.createExecutor() return service<ProgressManager>() .submitIOTask(progressIndicator) { currentUi.acquireLoginAndToken(server, executor, it) } .completionOnEdt(progressIndicator.modalityState) { setBusy(false) } .errorOnEdt(progressIndicator.modalityState) { setError(it) } } fun getServer(): GithubServerPath = GithubServerPath.from(serverTextField.text.trim()) fun setServer(path: String, editable: Boolean) { serverTextField.text = path serverTextField.isEditable = editable } fun setLogin(login: String?, editable: Boolean) { tokenUi.setFixedLogin(if (editable) null else login) } fun setToken(token: String?) = tokenUi.setToken(token.orEmpty()) fun setError(exception: Throwable?) { tokenAcquisitionError = exception?.let { currentUi.handleAcquireError(it) } } fun setOAuthUi() = applyUi(oauthUi) fun setTokenUi() = applyUi(tokenUi) }
apache-2.0
98c05d975a6a4d30cda62f48249500b0
35.768595
140
0.775405
4.772532
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/core/event/CorsHttpRequest.kt
2
2243
package org.apache.causeway.client.kroviz.core.event import kotlinx.browser.document import org.w3c.dom.Document import org.w3c.dom.HTMLIFrameElement // https://stackoverflow.com/questions/33143776/ajax-request-refused-to-set-unsafe-header class CorsHttpRequest { private val scriptStr = """ function sendWithoutOrigin(url, credentials) { console.log("[CHR.script]"); var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.setRequestHeader('Authorization', 'Basic '+ credentials); xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8') xhr.setRequestHeader('Accept', 'image/svg+xml'); xhr.responseType = 'blob'; xhr.onloadend = function() { if (xhr.readyState === XMLHttpRequest.DONE) { console.log('GET succeeded.'); console.log(xhr.response); return xhr.response; } }; xhr.send(); }""" private var iframe: HTMLIFrameElement = document.getElementById("iframe") as HTMLIFrameElement private var iframeWin: Document? = iframe.contentDocument //?: iframe) as Document? init { val iframeDoc = iframe.contentDocument!! //?: iframeWin?.ownerDocument val script = iframeDoc.createElement("SCRIPT") script.append(scriptStr); iframeDoc.documentElement?.appendChild(script); } //https://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy /* iframeDoc.domain = "about:blank" val newDoc = Document(); newDoc.domain = "about:blank" iframeDoc.append(newDoc) val script = newDoc.createElement("SCRIPT") newDoc.documentElement?.appendChild(script); */ fun invoke(url: String, credentials: String): String { val answer = js(""" var iframe = document.getElementById('iframe'); var iframeWin = iframe.contentWindow; return iframeWin.sendWithoutOrigin(url, credentials); """) console.log("[CHR]") console.log(answer as String) return answer } }
apache-2.0
a859f13aadd365654bd62ecaa17e93cd
38.350877
98
0.615693
4.432806
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPropertyProcessor.kt
3
25451
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.refactoring.rename import com.intellij.navigation.NavigationItem import com.intellij.openapi.editor.Editor import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Pass import com.intellij.psi.* import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.DirectClassInheritorsSearch import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.refactoring.rename.RenameUtil import com.intellij.refactoring.util.MoveRenameUsageInfo import com.intellij.refactoring.util.RefactoringUtil import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewUtil import org.jetbrains.kotlin.asJava.* import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.unquoteKotlinIdentifier import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations import org.jetbrains.kotlin.idea.core.isEnumCompanionPropertyWithEntryConflict import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.refactoring.checkSuperMethodsWithPopup import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary import org.jetbrains.kotlin.idea.references.KtDestructuringDeclarationReference import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.base.util.codeUsageScope import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.findPropertyByName import org.jetbrains.kotlin.psi.psiUtil.isPrivate import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.util.findCallableMemberBySignature import org.jetbrains.kotlin.utils.DFS import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addToStdlib.safeAs class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { override fun canProcessElement(element: PsiElement): Boolean { val namedUnwrappedElement = element.namedUnwrappedElement return namedUnwrappedElement is KtProperty || namedUnwrappedElement is PropertyMethodWrapper || (namedUnwrappedElement is KtParameter && namedUnwrappedElement.hasValOrVar()) } override fun isToSearchInComments(psiElement: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_FIELD override fun setToSearchInComments(element: PsiElement, enabled: Boolean) { KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_FIELD = enabled } override fun isToSearchForTextOccurrences(element: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_FOR_TEXT_FOR_FIELD override fun setToSearchForTextOccurrences(element: PsiElement, enabled: Boolean) { KotlinRefactoringSettings.instance.RENAME_SEARCH_FOR_TEXT_FOR_FIELD = enabled } private fun getJvmNames(element: PsiElement): Pair<String?, String?> { val descriptor = (element.unwrapped as? KtDeclaration)?.unsafeResolveToDescriptor() as? PropertyDescriptor ?: return null to null val getterName = descriptor.getter?.let { DescriptorUtils.getJvmName(it) } val setterName = descriptor.setter?.let { DescriptorUtils.getJvmName(it) } return getterName to setterName } protected fun processFoundReferences( element: PsiElement, allReferences: Collection<PsiReference> ): Collection<PsiReference> { val references = allReferences.filterNot { it is KtDestructuringDeclarationReference } val (getterJvmName, setterJvmName) = getJvmNames(element) return when { getterJvmName == null && setterJvmName == null -> references element is KtElement -> references.filter { it is KtReference || (getterJvmName == null && (it.resolve() as? PsiNamedElement)?.name != setterJvmName) || (setterJvmName == null && (it.resolve() as? PsiNamedElement)?.name != getterJvmName) } element is KtLightDeclaration<*, *> -> { val name = element.name if (name == getterJvmName || name == setterJvmName) references.filterNot { it is KtReference } else references } else -> emptyList() } } private fun checkAccidentalOverrides( declaration: KtNamedDeclaration, newName: String, descriptor: VariableDescriptor, result: MutableList<UsageInfo> ) { fun reportAccidentalOverride(candidate: PsiNamedElement) { val what = UsageViewUtil.getType(declaration).capitalize() val withWhat = candidate.renderDescription() val where = candidate.representativeContainer()?.renderDescription() ?: return val message = KotlinBundle.message("text.0.will.clash.with.existing.1.in.2", what, withWhat, where) result += BasicUnresolvableCollisionUsageInfo(candidate, candidate, message) } if (descriptor !is PropertyDescriptor) return val initialClass = declaration.containingClassOrObject ?: return val initialClassDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return val prototype = object : PropertyDescriptor by descriptor { override fun getName() = Name.guessByFirstCharacter(newName) } DFS.dfs( listOf(initialClassDescriptor), DFS.Neighbors { DescriptorUtils.getSuperclassDescriptors(it) }, object : DFS.AbstractNodeHandler<ClassDescriptor, Unit>() { override fun beforeChildren(current: ClassDescriptor): Boolean { if (current == initialClassDescriptor) return true (current.findCallableMemberBySignature(prototype))?.let { candidateDescriptor -> val candidate = candidateDescriptor.source.getPsi() as? PsiNamedElement ?: return false reportAccidentalOverride(candidate) return false } return true } override fun result() {} } ) if (!declaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) { val initialPsiClass = initialClass.toLightClass() ?: return val prototypes = declaration.toLightMethods().mapNotNull { it as KtLightMethod val methodName = accessorNameByPropertyName(newName, it) ?: return@mapNotNull null object : KtLightMethod by it { override fun getName() = methodName override fun getSourceElement(): PsiElement? = it.getSourceElement() } } DFS.dfs( listOf(initialPsiClass), DFS.Neighbors { DirectClassInheritorsSearch.search(it) }, object : DFS.AbstractNodeHandler<PsiClass, Unit>() { override fun beforeChildren(current: PsiClass): Boolean { if (current == initialPsiClass) return true if (current is KtLightClass) { val property = current.kotlinOrigin?.findPropertyByName(newName) ?: return true reportAccidentalOverride(property) return false } for (psiMethod in prototypes) { current.findMethodBySignature(psiMethod, false)?.let { val candidate = it.unwrapped as? PsiNamedElement ?: return true reportAccidentalOverride(candidate) return false } } return true } override fun result() {} } ) } } override fun findCollisions( element: PsiElement, newName: String, allRenames: MutableMap<out PsiElement, String>, result: MutableList<UsageInfo> ) { val declaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return val resolutionFacade = declaration.getResolutionFacade() val descriptor = declaration.unsafeResolveToDescriptor(resolutionFacade) as VariableDescriptor val collisions = SmartList<UsageInfo>() checkRedeclarations(declaration, newName, collisions, resolutionFacade, descriptor) checkAccidentalOverrides(declaration, newName, descriptor, collisions) checkOriginalUsagesRetargeting(declaration, newName, result, collisions) checkNewNameUsagesRetargeting(declaration, newName, collisions) result += collisions } private fun chooseCallableToRename(callableDeclaration: KtCallableDeclaration): KtCallableDeclaration? { val deepestSuperDeclaration = findDeepestOverriddenDeclaration(callableDeclaration) if (deepestSuperDeclaration == null || deepestSuperDeclaration == callableDeclaration) { return callableDeclaration } if (isUnitTestMode()) return deepestSuperDeclaration val containsText: String? = deepestSuperDeclaration.fqName?.parent()?.asString() ?: (deepestSuperDeclaration.parent as? KtClassOrObject)?.name val message = if (containsText != null) KotlinBundle.message("text.do.you.want.to.rename.base.property.from.0", containsText) else KotlinBundle.message("text.do.you.want.to.rename.base.property") val result = Messages.showYesNoCancelDialog( deepestSuperDeclaration.project, message, KotlinBundle.message("title.rename.warning"), Messages.getQuestionIcon() ) return when (result) { Messages.YES -> deepestSuperDeclaration Messages.NO -> callableDeclaration else -> /* Cancel rename */ null } } override fun substituteElementToRename(element: PsiElement, editor: Editor?): PsiElement? { val namedUnwrappedElement = element.namedUnwrappedElement ?: return null val callableDeclaration = namedUnwrappedElement as? KtCallableDeclaration ?: throw IllegalStateException("Can't be for element $element there because of canProcessElement()") val declarationToRename = chooseCallableToRename(callableDeclaration) ?: return null val (getterJvmName, setterJvmName) = getJvmNames(namedUnwrappedElement) if (element is KtLightMethod) { val name = element.name if (element.name != getterJvmName && element.name != setterJvmName) return declarationToRename return declarationToRename.toLightMethods().firstOrNull { it.name == name } } return declarationToRename } override fun substituteElementToRename(element: PsiElement, editor: Editor, renameCallback: Pass<PsiElement>) { val namedUnwrappedElement = element.namedUnwrappedElement ?: return val callableDeclaration = namedUnwrappedElement as? KtCallableDeclaration ?: throw IllegalStateException("Can't be for element $element there because of canProcessElement()") fun preprocessAndPass(substitutedJavaElement: PsiElement) { val (getterJvmName, setterJvmName) = getJvmNames(namedUnwrappedElement) val elementToProcess = if (element is KtLightMethod) { val name = element.name if (element.name != getterJvmName && element.name != setterJvmName) { substitutedJavaElement } else { substitutedJavaElement.toLightMethods().firstOrNull { it.name == name } } } else substitutedJavaElement renameCallback.pass(elementToProcess) } val deepestSuperDeclaration = findDeepestOverriddenDeclaration(callableDeclaration) if (deepestSuperDeclaration == null || deepestSuperDeclaration == callableDeclaration) { return preprocessAndPass(callableDeclaration) } val superPsiMethods = listOfNotNull(deepestSuperDeclaration.getRepresentativeLightMethod()) checkSuperMethodsWithPopup(callableDeclaration, superPsiMethods, editor) { preprocessAndPass(if (it.size > 1) deepestSuperDeclaration else callableDeclaration) } } class PropertyMethodWrapper(private val propertyMethod: PsiMethod) : PsiNamedElement by propertyMethod, NavigationItem by propertyMethod { override fun getName() = propertyMethod.name override fun setName(name: String) = this override fun copy() = this } override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>, scope: SearchScope) { super.prepareRenaming(element, newName, allRenames, scope) val namedUnwrappedElement = element.namedUnwrappedElement val propertyMethods = when (namedUnwrappedElement) { is KtProperty -> runReadAction { LightClassUtil.getLightClassPropertyMethods(namedUnwrappedElement) } is KtParameter -> runReadAction { LightClassUtil.getLightClassPropertyMethods(namedUnwrappedElement) } else -> throw IllegalStateException("Can't be for element $element there because of canProcessElement()") } val newPropertyName = if (element is KtLightMethod) propertyNameByAccessor(newName, element) else newName val (getterJvmName, setterJvmName) = getJvmNames(namedUnwrappedElement) val getter = propertyMethods.getter as? KtLightMethod val setter = propertyMethods.setter as? KtLightMethod if (newPropertyName != null && getter != null && setter != null && (element == getter || element == setter) && propertyNameByAccessor(getter.name, getter) == propertyNameByAccessor(setter.name, setter) ) { val accessorToRename = if (element == getter) setter else getter val newAccessorName = if (element == getter) JvmAbi.setterName(newPropertyName) else JvmAbi.getterName(newPropertyName) if (isUnitTestMode() || Messages.showYesNoDialog( KotlinBundle.message("text.do.you.want.to.rename.0.as.well", accessorToRename.name), RefactoringBundle.message("rename.title"), Messages.getQuestionIcon() ) == Messages.YES ) { allRenames[accessorToRename] = newAccessorName } } for (propertyMethod in propertyMethods) { val mangledPropertyName = if (propertyMethod is KtLightMethod && propertyMethod.isMangled) { val suffix = KotlinTypeMapper.InternalNameMapper.getModuleNameSuffix(propertyMethod.name) if (suffix != null && newPropertyName != null) KotlinTypeMapper.InternalNameMapper.mangleInternalName( newPropertyName, suffix ) else null } else null val adjustedPropertyName = mangledPropertyName ?: newPropertyName if (element is KtDeclaration && adjustedPropertyName != null) { val wrapper = PropertyMethodWrapper(propertyMethod) when { JvmAbi.isGetterName(propertyMethod.name) && getterJvmName == null -> allRenames[wrapper] = JvmAbi.getterName(adjustedPropertyName) JvmAbi.isSetterName(propertyMethod.name) && setterJvmName == null -> allRenames[wrapper] = JvmAbi.setterName(adjustedPropertyName) } } addRenameElements(propertyMethod, (element as PsiNamedElement).name, adjustedPropertyName, allRenames, scope) } ForeignUsagesRenameProcessor.prepareRenaming(element, newName, allRenames, scope) } protected enum class UsageKind { SIMPLE_PROPERTY_USAGE, GETTER_USAGE, SETTER_USAGE } private fun addRenameElements( psiMethod: PsiMethod?, oldName: String?, newName: String?, allRenames: MutableMap<PsiElement, String>, scope: SearchScope ) { if (psiMethod == null) return OverridingMethodsSearch.search(psiMethod, scope, true).forEach { overrider -> val overriderElement = overrider.namedUnwrappedElement if (overriderElement != null && overriderElement !is SyntheticElement) { RenameUtil.assertNonCompileElement(overriderElement) val overriderName = overriderElement.name if (overriderElement is PsiMethod) { if (newName != null && Name.isValidIdentifier(newName)) { val isGetter = overriderElement.parameterList.parametersCount == 0 allRenames[overriderElement] = if (isGetter) JvmAbi.getterName(newName) else JvmAbi.setterName(newName) } } else { val demangledName = if (newName != null && overrider is KtLightMethod && overrider.isMangled) KotlinTypeMapper.InternalNameMapper.demangleInternalName( newName ) else null val adjustedName = demangledName ?: newName val newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, oldName, adjustedName) if (newOverriderName != null) { allRenames[overriderElement] = newOverriderName } } } } } private fun findDeepestOverriddenDeclaration(declaration: KtCallableDeclaration): KtCallableDeclaration? { if (declaration.modifierList?.hasModifier(KtTokens.OVERRIDE_KEYWORD) == true) { val bindingContext = declaration.analyze() var descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] if (descriptor is ValueParameterDescriptor) { descriptor = bindingContext[BindingContext.VALUE_PARAMETER_AS_PROPERTY, descriptor] ?: return declaration } if (descriptor != null) { assert(descriptor is PropertyDescriptor) { "Property descriptor is expected" } val supers = (descriptor as PropertyDescriptor).getDeepestSuperDeclarations() // Take one of supers for now - API doesn't support substitute to several elements (IDEA-48796) val deepest = supers.first() if (deepest != descriptor) { val superPsiElement = DescriptorToSourceUtils.descriptorToDeclaration(deepest) return superPsiElement as? KtCallableDeclaration } } } return null } override fun findReferences( element: PsiElement, searchScope: SearchScope, searchInCommentsAndStrings: Boolean ): Collection<PsiReference> { val referenceSearchScope = if (element is KtParameter && element.isPrivate()) { element.ownerFunction.safeAs<KtPrimaryConstructor>()?.codeUsageScope()?.union(searchScope) ?: searchScope } else { searchScope } val references = super.findReferences(element, referenceSearchScope, searchInCommentsAndStrings) return processFoundReferences(element, references) } //TODO: a very long and complicated method, even recursive. mb refactor it somehow? at least split by PsiElement types? override tailrec fun renameElement( element: PsiElement, newName: String, usages: Array<UsageInfo>, listener: RefactoringElementListener? ) { val newNameUnquoted = newName.unquoteKotlinIdentifier() if (element is KtLightMethod) { if (element.modifierList.hasAnnotation(DescriptorUtils.JVM_NAME.asString())) { return super.renameElement(element, newName, usages, listener) } val origin = element.kotlinOrigin val newPropertyName = propertyNameByAccessor(newNameUnquoted, element) // Kotlin references to Kotlin property should not use accessor name if (newPropertyName != null && (origin is KtProperty || origin is KtParameter)) { val (ktUsages, otherUsages) = usages.partition { it.reference is KtSimpleNameReference } super.renameElement(element, newName, otherUsages.toTypedArray(), listener) renameElement(origin, newPropertyName.quoteIfNeeded(), ktUsages.toTypedArray(), listener) return } } if (element !is KtProperty && element !is KtParameter) { super.renameElement(element, newName, usages, listener) return } val name = (element as KtNamedDeclaration).name!! val oldGetterName = JvmAbi.getterName(name) val oldSetterName = JvmAbi.setterName(name) if (isEnumCompanionPropertyWithEntryConflict(element, newNameUnquoted)) { for ((i, usage) in usages.withIndex()) { if (usage !is MoveRenameUsageInfo) continue val ref = usage.reference ?: continue // TODO: Enum value can't be accessed from Java in case of conflict with companion member if (ref is KtReference) { val newRef = (ref.bindToElement(element) as? KtSimpleNameExpression)?.mainReference ?: continue usages[i] = MoveRenameUsageInfo(newRef, usage.referencedElement) } } } val adjustedUsages = if (element is KtParameter) usages.filterNot { val refTarget = it.reference?.resolve() refTarget is KtLightMethod && DataClassDescriptorResolver.isComponentLike(Name.guessByFirstCharacter(refTarget.name)) } else usages.toList() val refKindUsages = adjustedUsages.groupBy { usage: UsageInfo -> val refElement = usage.reference?.resolve() if (refElement is PsiMethod) { val refElementName = refElement.name val refElementNameToCheck = ( if (usage is MangledJavaRefUsageInfo) KotlinTypeMapper.InternalNameMapper.demangleInternalName(refElementName) else null ) ?: refElementName when (refElementNameToCheck) { oldGetterName -> UsageKind.GETTER_USAGE oldSetterName -> UsageKind.SETTER_USAGE else -> UsageKind.SIMPLE_PROPERTY_USAGE } } else { UsageKind.SIMPLE_PROPERTY_USAGE } } super.renameElement( element.copy(), JvmAbi.setterName(newNameUnquoted).quoteIfNeeded(), refKindUsages[UsageKind.SETTER_USAGE]?.toTypedArray() ?: arrayOf(), null, ) super.renameElement( element.copy(), JvmAbi.getterName(newNameUnquoted).quoteIfNeeded(), refKindUsages[UsageKind.GETTER_USAGE]?.toTypedArray() ?: arrayOf(), null, ) super.renameElement( element, newName, refKindUsages[UsageKind.SIMPLE_PROPERTY_USAGE]?.toTypedArray() ?: arrayOf(), null, ) usages.forEach { (it as? KtResolvableCollisionUsageInfo)?.apply() } dropOverrideKeywordIfNecessary(element) listener?.elementRenamed(element) } }
apache-2.0
db843c4e03f5434e4e2fe1a34ac178c8
46.571963
209
0.663314
5.662069
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ide/minimap/MinimapService.kt
1
3297
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.minimap import com.intellij.ide.minimap.settings.MinimapSettings import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.EditorKind import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import java.awt.BorderLayout import javax.swing.JPanel class MinimapService : Disposable { companion object { fun getInstance() = service<MinimapService>() private val MINI_MAP_PANEL_KEY: Key<MinimapPanel> = Key.create("com.intellij.ide.minimap.panel") } private val settings = MinimapSettings.getInstance() private val onSettingsChange = { type: MinimapSettings.SettingsChangeType -> if (type == MinimapSettings.SettingsChangeType.WithUiRebuild) { updateAllEditors() } } init { MinimapSettings.getInstance().settingsChangeCallback += onSettingsChange } fun updateAllEditors() { EditorFactory.getInstance().allEditors.forEach { editor -> getEditorImpl(editor)?.let { removeMinimap(it) if (settings.state.enabled) { addMinimap(it) } } } } override fun dispose() { MinimapSettings.getInstance().settingsChangeCallback -= onSettingsChange } private fun getEditorImpl(editor: Editor): EditorImpl? { val editorImpl = editor as? EditorImpl ?: return null if (editorImpl.editorKind != EditorKind.MAIN_EDITOR) return null val virtualFile = editorImpl.virtualFile ?: FileDocumentManager.getInstance().getFile(editor.document) ?: return null if (settings.state.fileTypes.isNotEmpty() && !settings.state.fileTypes.contains(virtualFile.fileType.defaultExtension)) return null return editorImpl } fun editorOpened(editor: Editor) { if (!settings.state.enabled) { return } getEditorImpl(editor)?.let { addMinimap(it) } } private fun getPanel(fileEditor: EditorImpl): JPanel? { return fileEditor.component as? JPanel } private fun addMinimap(textEditor: EditorImpl) { val panel = getPanel(textEditor) ?: return val where = if (settings.state.rightAligned) BorderLayout.LINE_END else BorderLayout.LINE_START if ((panel.layout as? BorderLayout)?.getLayoutComponent(where) == null) { val minimapPanel = MinimapPanel(textEditor.disposable, textEditor, panel) panel.add(minimapPanel, where) textEditor.putUserData(MINI_MAP_PANEL_KEY, minimapPanel) Disposer.register(textEditor.disposable) { textEditor.getUserData(MINI_MAP_PANEL_KEY)?.onClose() textEditor.putUserData(MINI_MAP_PANEL_KEY, null) } panel.revalidate() panel.repaint() } } private fun removeMinimap(editor: EditorImpl) { val minimapPanel = editor.getUserData(MINI_MAP_PANEL_KEY) ?: return minimapPanel.onClose() editor.putUserData(MINI_MAP_PANEL_KEY, null) minimapPanel.parent?.apply { remove(minimapPanel) revalidate() repaint() } } }
apache-2.0
7c22e2608bf6eec71a5eeec26db70331
31.98
135
0.730361
4.309804
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/statistic/StatisticBase.kt
1
10311
// 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.statistic import com.intellij.ide.RecentProjectsManagerBase import com.intellij.ide.plugins.PluginManagerCore import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.* import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.impl.DefaultKeymapImpl import com.intellij.util.TimeoutUtil import training.lang.LangManager import training.learn.CourseManager import training.learn.course.IftModule import training.learn.course.Lesson import training.learn.lesson.LessonManager import training.statistic.FeatureUsageStatisticConsts.ACTION_ID import training.statistic.FeatureUsageStatisticConsts.COMPLETED_COUNT import training.statistic.FeatureUsageStatisticConsts.COURSE_SIZE import training.statistic.FeatureUsageStatisticConsts.DURATION import training.statistic.FeatureUsageStatisticConsts.EXPAND_WELCOME_PANEL import training.statistic.FeatureUsageStatisticConsts.KEYMAP_SCHEME import training.statistic.FeatureUsageStatisticConsts.LANGUAGE import training.statistic.FeatureUsageStatisticConsts.LEARN_PROJECT_OPENED_FIRST_TIME import training.statistic.FeatureUsageStatisticConsts.LEARN_PROJECT_OPENING_WAY import training.statistic.FeatureUsageStatisticConsts.LESSON_ID import training.statistic.FeatureUsageStatisticConsts.MODULE_NAME import training.statistic.FeatureUsageStatisticConsts.NON_LEARNING_PROJECT_OPENED import training.statistic.FeatureUsageStatisticConsts.PASSED import training.statistic.FeatureUsageStatisticConsts.PROGRESS import training.statistic.FeatureUsageStatisticConsts.REASON import training.statistic.FeatureUsageStatisticConsts.RESTORE import training.statistic.FeatureUsageStatisticConsts.SHORTCUT_CLICKED import training.statistic.FeatureUsageStatisticConsts.START import training.statistic.FeatureUsageStatisticConsts.START_MODULE_ACTION import training.statistic.FeatureUsageStatisticConsts.STOPPED import training.statistic.FeatureUsageStatisticConsts.TASK_ID import training.util.KeymapUtil import java.awt.event.KeyEvent import java.util.concurrent.ConcurrentHashMap import javax.swing.JOptionPane internal class StatisticBase : CounterUsagesCollector() { override fun getGroup() = GROUP private data class LessonProgress(val lessonId: String, val taskId: Int) enum class LearnProjectOpeningWay { LEARN_IDE, ONBOARDING_PROMOTER } enum class LessonStopReason { CLOSE_PROJECT, RESTART, CLOSE_FILE, OPEN_MODULES, OPEN_NEXT_OR_PREV_LESSON } companion object { private val LOG = logger<StatisticBase>() private val sessionLessonTimestamp: ConcurrentHashMap<String, Long> = ConcurrentHashMap() private var prevRestoreLessonProgress: LessonProgress = LessonProgress("", 0) private val GROUP: EventLogGroup = EventLogGroup("ideFeaturesTrainer", 9) var isLearnProjectClosing = false // FIELDS private val lessonIdField = EventFields.StringValidatedByCustomRule(LESSON_ID, LESSON_ID) private val languageField = EventFields.StringValidatedByCustomRule(LANGUAGE, LANGUAGE) private val completedCountField = EventFields.Int(COMPLETED_COUNT) private val courseSizeField = EventFields.Int(COURSE_SIZE) private val moduleNameField = EventFields.StringValidatedByCustomRule(MODULE_NAME, MODULE_NAME) private val taskIdField = EventFields.StringValidatedByCustomRule(TASK_ID, TASK_ID) private val actionIdField = EventFields.StringValidatedByCustomRule(ACTION_ID, ACTION_ID) private val keymapSchemeField = EventFields.StringValidatedByCustomRule(KEYMAP_SCHEME, KEYMAP_SCHEME) private val versionField = EventFields.Version private val inputEventField = EventFields.InputEvent private val learnProjectOpeningWayField = EventFields.Enum<LearnProjectOpeningWay>(LEARN_PROJECT_OPENING_WAY) private val reasonField = EventFields.Enum<LessonStopReason>(REASON) // EVENTS private val lessonStartedEvent: EventId2<String?, String?> = GROUP.registerEvent(START, lessonIdField, languageField) private val lessonPassedEvent: EventId3<String?, String?, Long> = GROUP.registerEvent(PASSED, lessonIdField, languageField, EventFields.Long(DURATION)) private val lessonStoppedEvent = GROUP.registerVarargEvent(STOPPED, lessonIdField, taskIdField, languageField, reasonField) private val progressUpdatedEvent = GROUP.registerVarargEvent(PROGRESS, lessonIdField, completedCountField, courseSizeField, languageField) private val moduleStartedEvent: EventId2<String?, String?> = GROUP.registerEvent(START_MODULE_ACTION, moduleNameField, languageField) private val welcomeScreenPanelExpandedEvent: EventId1<String?> = GROUP.registerEvent(EXPAND_WELCOME_PANEL, languageField) private val shortcutClickedEvent = GROUP.registerVarargEvent(SHORTCUT_CLICKED, inputEventField, keymapSchemeField, lessonIdField, taskIdField, actionIdField, versionField) private val restorePerformedEvent = GROUP.registerVarargEvent(RESTORE, lessonIdField, taskIdField, versionField) private val learnProjectOpenedFirstTimeEvent: EventId2<LearnProjectOpeningWay, String?> = GROUP.registerEvent(LEARN_PROJECT_OPENED_FIRST_TIME, learnProjectOpeningWayField, languageField) private val nonLearningProjectOpened: EventId1<LearnProjectOpeningWay> = GROUP.registerEvent(NON_LEARNING_PROJECT_OPENED, learnProjectOpeningWayField) // LOGGING fun logLessonStarted(lesson: Lesson) { sessionLessonTimestamp[lesson.id] = System.nanoTime() lessonStartedEvent.log(lesson.id, courseLanguage()) } fun logLessonPassed(lesson: Lesson) { val timestamp = sessionLessonTimestamp[lesson.id] if (timestamp == null) { LOG.warn("Unable to find timestamp for a lesson: ${lesson.name}") return } val delta = TimeoutUtil.getDurationMillis(timestamp) lessonPassedEvent.log(lesson.id, courseLanguage(), delta) progressUpdatedEvent.log(lessonIdField with lesson.id, completedCountField with completedCount(), courseSizeField with CourseManager.instance.lessonsForModules.size, languageField with courseLanguage()) } fun logLessonStopped(reason: LessonStopReason) { val lessonManager = LessonManager.instance if (lessonManager.lessonIsRunning()) { val lessonId = lessonManager.currentLesson!!.id val taskId = lessonManager.currentLessonExecutor!!.currentTaskIndex lessonStoppedEvent.log(lessonIdField with lessonId, taskIdField with taskId.toString(), languageField with courseLanguage(), reasonField with reason ) } } fun logModuleStarted(module: IftModule) { moduleStartedEvent.log(module.name, courseLanguage()) } fun logWelcomeScreenPanelExpanded() { welcomeScreenPanelExpandedEvent.log(courseLanguage()) } fun logShortcutClicked(actionId: String) { val lessonManager = LessonManager.instance if (lessonManager.lessonIsRunning()) { val lesson = lessonManager.currentLesson!! val keymap = getDefaultKeymap() ?: return shortcutClickedEvent.log(inputEventField with createInputEvent(actionId), keymapSchemeField with keymap.name, lessonIdField with lesson.id, taskIdField with lessonManager.currentLessonExecutor?.currentTaskIndex.toString(), actionIdField with actionId, versionField with getPluginVersion(lesson)) } } fun logRestorePerformed(lesson: Lesson, taskId: Int) { val curLessonProgress = LessonProgress(lesson.id, taskId) if (curLessonProgress != prevRestoreLessonProgress) { prevRestoreLessonProgress = curLessonProgress restorePerformedEvent.log(lessonIdField with lesson.id, taskIdField with taskId.toString(), versionField with getPluginVersion(lesson)) } } fun logLearnProjectOpenedForTheFirstTime(way: LearnProjectOpeningWay) { if (RecentProjectsManagerBase.instanceEx.getRecentPaths().isEmpty()) { LearnProjectState.instance.firstTimeOpenedWay = way learnProjectOpenedFirstTimeEvent.log(way, courseLanguage()) } } fun logNonLearningProjectOpened(way: LearnProjectOpeningWay) { nonLearningProjectOpened.log(way) } private fun courseLanguage() = LangManager.getInstance().getLangSupport()?.primaryLanguage?.toLowerCase() ?: "" private fun completedCount(): Int = CourseManager.instance.lessonsForModules.count { it.passed } private fun createInputEvent(actionId: String): FusInputEvent? { val keyStroke = KeymapUtil.getShortcutByActionId(actionId) ?: return null val inputEvent = KeyEvent(JOptionPane.getRootFrame(), KeyEvent.KEY_PRESSED, System.currentTimeMillis(), keyStroke.modifiers, keyStroke.keyCode, keyStroke.keyChar, KeyEvent.KEY_LOCATION_STANDARD) return FusInputEvent(inputEvent, "") } private fun getPluginVersion(lesson: Lesson): String? { val pluginId = PluginManagerCore.getPluginByClassName(lesson::class.java.name) return PluginManagerCore.getPlugin(pluginId)?.version } private fun getDefaultKeymap(): Keymap? { val keymap = KeymapManager.getInstance().activeKeymap if (keymap is DefaultKeymapImpl) { return keymap } return keymap.parent as? DefaultKeymapImpl } } }
apache-2.0
03cb589e6b29881977069152481d03ef
50.049505
140
0.737465
5.223404
false
false
false
false
Ayvytr/EasyAndroid
EasyAndroidTest/src/main/java/com/ayvytr/easyandroidtest/customview/AuthEditTextActivity2.kt
1
3347
package com.ayvytr.easyandroidtest.customview import android.graphics.Color import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.LinearLayout import com.ayvytr.easyandroid.tools.withcontext.ToastTool import com.ayvytr.easyandroid.view.custom.AuthEditText import com.ayvytr.easyandroidtest.R import kotlinx.android.synthetic.main.activity_auth_edit_text2.* import java.util.* class AuthEditTextActivity2 : AppCompatActivity() { private val random = Random() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_auth_edit_text2) initView(savedInstanceState) } fun initView(savedInstanceState: Bundle?) { btnMaxLength?.setOnClickListener { authEditText?.maxLength = randomMaxLength } btnSize?.setOnClickListener { authEditText?.layoutParams = randomLp } btnTextColor.setOnClickListener { authEditText?.textColor = randomColor } btnTextSize.setOnClickListener { authEditText.textSize = random.nextInt(30) } btnFrameColor.setOnClickListener { authEditText.frameColor = randomColor } btnFrameWidth.setOnClickListener { authEditText.frameWidth = random.nextInt(20) } btnInputType.setOnClickListener { authEditText.inputType = randomInputType } btnPasswordString.setOnClickListener { authEditText.passwordString = randomPasswordString } authEditText.setOnInputChangeListener(object : AuthEditText.OnInputChangeListener { override fun onFinished(authEditText: AuthEditText, s: String) { } override fun onTextChanged(isFinished: Boolean, s: String) { ToastTool.show(s) } }) } private val randomMaxLength: Int get() { var i = random.nextInt(AuthEditText.MAX_LENGTH) while (i < AuthEditText.MIN_LENGTH) { i = random.nextInt(AuthEditText.MAX_LENGTH) } return i } private val randomLp: LinearLayout.LayoutParams get() { return LinearLayout.LayoutParams(random.nextInt(500), random.nextInt(400)) } private val randomColor: Int get() { return Color.rgb(random.nextInt(0xff), random.nextInt(0xff), random.nextInt(0xff)) } private val randomInputType: AuthEditText.InputType get() = AuthEditText.InputType.valueOf(random.nextInt(5)) private val randomPasswordString: String get() { val i = random.nextInt(6) when (i) { 0 -> return "·" 1 -> return "*" 2 -> return "CCcccccccc" 4 -> return "" else -> return "aaa" } } }
apache-2.0
e4111a5eec63968ca2ada25e7d0e2217
35.595506
112
0.555589
5.269291
false
false
false
false
genonbeta/TrebleShot
zxing/src/main/java/org/monora/android/codescanner/DecodeTask.kt
1
3033
/* * MIT License * * Copyright (c) 2017 Yuriy Budiyev [[email protected]] * Copyright (c) 2021 Veli Tasalı [[email protected]] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.monora.android.codescanner import android.graphics.Rect import com.google.zxing.MultiFormatReader import com.google.zxing.PlanarYUVLuminanceSource import com.google.zxing.ReaderException import com.google.zxing.Result import org.monora.android.codescanner.Utils.decodeLuminanceSource import org.monora.android.codescanner.Utils.getImageFrameRect import org.monora.android.codescanner.Utils.rotateYuv class DecodeTask( private val image: ByteArray, private val imageSize: CartesianCoordinate, private val previewSize: CartesianCoordinate, private val viewSize: CartesianCoordinate, private val viewFrameRect: Rect, private val orientation: Int, private val reverseHorizontal: Boolean, ) { @Throws(ReaderException::class) fun decode(reader: MultiFormatReader): Result? { var imageWidth = imageSize.x var imageHeight = imageSize.y val orientation = orientation val image = rotateYuv(image, imageWidth, imageHeight, orientation) if (orientation == 90 || orientation == 270) { val width = imageWidth imageWidth = imageHeight imageHeight = width } val frameRect = getImageFrameRect(imageWidth, imageHeight, viewFrameRect, previewSize, viewSize) val frameWidth: Int = frameRect.width() val frameHeight: Int = frameRect.height() return if (frameWidth < 1 || frameHeight < 1) { null } else decodeLuminanceSource( reader, PlanarYUVLuminanceSource( image, imageWidth, imageHeight, frameRect.left, frameRect.top, frameWidth, frameHeight, reverseHorizontal ) ) } }
gpl-2.0
2e28bf014783219b8e2842f4e40db9b2
37.884615
104
0.698879
4.636086
false
false
false
false
Raizlabs/DBFlow
lib/src/main/kotlin/com/dbflow5/query/NameAlias.kt
1
8326
package com.dbflow5.query import com.dbflow5.isNotNullOrEmpty import com.dbflow5.quoteIfNeeded import com.dbflow5.sql.Query import com.dbflow5.stripQuotes /** * Description: Rewritten from the ground up, this class makes it easier to build an alias. */ class NameAlias(private val name: String, private val aliasName: String? = null, val tableName: String? = null, val keyword: String? = null, val shouldStripIdentifier: Boolean = true, val shouldStripAliasName: Boolean = true, private val shouldAddIdentifierToQuery: Boolean = true, private val shouldAddIdentifierToAliasName: Boolean = true) : Query { /** * @return The name used in queries. If an alias is specified, use that, otherwise use the name * of the property with a table name (if specified). */ override val query: String get() = when { aliasName.isNotNullOrEmpty() -> aliasName ?: "" name.isNotNullOrEmpty() -> fullName() else -> "" } /** * @return The value used as a key. Uses either the [.aliasNameRaw] * or the [.nameRaw], depending on what's specified. */ val nameAsKey: String? get() = if (aliasName.isNotNullOrEmpty()) { aliasNameRaw() } else { nameRaw() } /** * @return The full query that represents itself with `{tableName}`.`{name}` AS `{aliasName}` */ val fullQuery: String get() { var query = fullName() if (aliasName.isNotNullOrEmpty()) { query += " AS ${aliasName()}" } if (keyword.isNotNullOrEmpty()) { query = "$keyword $query" } return query } private constructor(builder: Builder) : this( name = if (builder.shouldStripIdentifier) { builder.name.stripQuotes() ?: "" } else { builder.name }, keyword = builder.keyword, aliasName = if (builder.shouldStripAliasName) { builder.aliasName.stripQuotes() } else { builder.aliasName }, tableName = if (builder.tableName.isNotNullOrEmpty()) { builder.tableName.quoteIfNeeded() } else { null }, shouldStripIdentifier = builder.shouldStripIdentifier, shouldStripAliasName = builder.shouldStripAliasName, shouldAddIdentifierToQuery = builder.shouldAddIdentifierToQuery, shouldAddIdentifierToAliasName = builder.shouldAddIdentifierToAliasName) /** * @return The real column name. */ fun name(): String? { return if (name.isNotNullOrEmpty() && shouldAddIdentifierToQuery) name.quoteIfNeeded() else name } /** * @return The name, stripped from identifier syntax completely. */ fun nameRaw(): String = if (shouldStripIdentifier) name else name.stripQuotes() ?: "" /** * @return The name used as part of the AS query. */ fun aliasName(): String? { return if (aliasName.isNotNullOrEmpty() && shouldAddIdentifierToAliasName) aliasName.quoteIfNeeded() else aliasName } /** * @return The alias name, stripped from identifier syntax completely. */ fun aliasNameRaw(): String? = if (shouldStripAliasName) aliasName else aliasName.stripQuotes() /** * @return The `{tableName}`.`{name}`. If [.tableName] specified. */ fun fullName(): String = (if (tableName.isNotNullOrEmpty()) "$tableName." else "") + name() override fun toString(): String = fullQuery /** * @return Constructs a builder as a new instance that can be modified without fear. */ fun newBuilder(): Builder { return Builder(name) .keyword(keyword) .`as`(aliasName) .shouldStripAliasName(shouldStripAliasName) .shouldStripIdentifier(shouldStripIdentifier) .shouldAddIdentifierToName(shouldAddIdentifierToQuery) .shouldAddIdentifierToAliasName(shouldAddIdentifierToAliasName) .withTable(tableName) } class Builder(internal val name: String) { internal var aliasName: String? = null internal var tableName: String? = null internal var shouldStripIdentifier = true internal var shouldStripAliasName = true internal var shouldAddIdentifierToQuery = true internal var shouldAddIdentifierToAliasName = true internal var keyword: String? = null /** * Appends a DISTINCT that prefixes this alias class. */ fun distinct(): Builder = keyword("DISTINCT") /** * Appends a keyword that prefixes this alias class. */ fun keyword(keyword: String?) = apply { this.keyword = keyword } /** * Provide an alias that is used `{name}` AS `{aliasName}` */ fun `as`(aliasName: String?) = apply { this.aliasName = aliasName } /** * Provide a table-name prefix as such: `{tableName}`.`{name}` */ fun withTable(tableName: String?) = apply { this.tableName = tableName } /** * @param shouldStripIdentifier If true, we normalize the identifier [.name] from any * ticks around the name. If false, we leave it as such. */ fun shouldStripIdentifier(shouldStripIdentifier: Boolean) = apply { this.shouldStripIdentifier = shouldStripIdentifier } /** * @param shouldStripAliasName If true, we normalize the identifier [.aliasName] from any * ticks around the name. If false, we leave it as such. */ fun shouldStripAliasName(shouldStripAliasName: Boolean) = apply { this.shouldStripAliasName = shouldStripAliasName } /** * @param shouldAddIdentifierToName If true (default), we add the identifier to the name: `{name}` */ fun shouldAddIdentifierToName(shouldAddIdentifierToName: Boolean) = apply { this.shouldAddIdentifierToQuery = shouldAddIdentifierToName } /** * @param shouldAddIdentifierToAliasName If true (default), we add an identifier to the alias * name. `{aliasName}` */ fun shouldAddIdentifierToAliasName(shouldAddIdentifierToAliasName: Boolean) = apply { this.shouldAddIdentifierToAliasName = shouldAddIdentifierToAliasName } fun build(): NameAlias = NameAlias(this) } companion object { /** * Combines any number of names into a single [NameAlias] separated by some operation. * * @param operation The operation to separate into. * @param names The names to join. * @return The new namealias object. */ fun joinNames(operation: String, vararg names: String): NameAlias { var newName = "" for (i in names.indices) { if (i > 0) { newName += " $operation " } newName += names[i] } return rawBuilder(newName).build() } fun builder(name: String): Builder = Builder(name) fun tableNameBuilder(tableName: String): Builder = Builder("") .withTable(tableName) /** * @param name The raw name of this alias. * @return A new instance without adding identifier `` to any part of the query. */ fun rawBuilder(name: String): Builder { return Builder(name) .shouldStripIdentifier(false) .shouldAddIdentifierToName(false) } fun of(name: String): NameAlias = builder(name).build() fun of(name: String, aliasName: String): NameAlias = builder(name).`as`(aliasName).build() fun ofTable(tableName: String, name: String): NameAlias = builder(name).withTable(tableName).build() } } val String.nameAlias get() = NameAlias.of(this) fun String.`as`(alias: String = "") = NameAlias.of(this, alias)
mit
aa647f2e1232172a73e6f336f2f7d3fe
32.437751
106
0.590079
4.863318
false
false
false
false
zdary/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/DgmIntdivCallTypeCalculator.kt
12
1083
// 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.lang.typing import com.intellij.openapi.util.NlsSafe import com.intellij.psi.CommonClassNames.JAVA_LANG_INTEGER import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.DEFAULT_GROOVY_METHODS import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments class DgmIntdivCallTypeCalculator : GrCallTypeCalculator { companion object { @NlsSafe private const val INTDIV = "intdiv" } override fun getType(receiver: PsiType?, method: PsiMethod, arguments: Arguments?, context: PsiElement): PsiType? { if (method.name == INTDIV && method.containingClass?.qualifiedName == DEFAULT_GROOVY_METHODS) { return createType(JAVA_LANG_INTEGER, context) } return null } }
apache-2.0
69128b4244604f019189458fa3432ef5
40.653846
140
0.787627
4.041045
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/parser/HProfVisitor.kt
1
5028
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.parser import java.nio.ByteBuffer open class HProfVisitor { private val myTopLevelVisits = BooleanArray(RecordType.HeapDumpEnd.value + 1) private val myHeapDumpVisits = BooleanArray(HeapDumpRecordType.RootUnknown.value + 1) lateinit var visitorContext: VisitorContext val heapRecordOffset: Long get() = visitorContext.currentHeapRecordOffset val sizeOfID: Int get() = visitorContext.idSize init { enableAll() } fun isEnabled(type: RecordType): Boolean { return myTopLevelVisits[type.value] } fun isEnabled(type: HeapDumpRecordType): Boolean { return myHeapDumpVisits[type.value] } fun enableAll() { for (recordType in RecordType.values()) { myTopLevelVisits[recordType.value] = true } for (recordType in HeapDumpRecordType.values()) { myHeapDumpVisits[recordType.value] = true } } fun disableAll() { for (recordType in RecordType.values()) { myTopLevelVisits[recordType.value] = false } for (recordType in HeapDumpRecordType.values()) { myHeapDumpVisits[recordType.value] = false } } fun enable(type: RecordType) { if (type === RecordType.HeapDump || type === RecordType.HeapDumpSegment) { myTopLevelVisits[RecordType.HeapDump.value] = true myTopLevelVisits[RecordType.HeapDumpSegment.value] = true } else { myTopLevelVisits[type.value] = true } } fun enable(type: HeapDumpRecordType) { enable(RecordType.HeapDump) myHeapDumpVisits[type.value] = true } fun disable(type: RecordType) { myTopLevelVisits[type.value] = false } fun disable(type: HeapDumpRecordType) { myHeapDumpVisits[type.value] = false } open fun preVisit() {} open fun postVisit() {} open fun visitStringInUTF8(id: Long, s: String) {} open fun visitLoadClass(classSerialNumber: Long, classObjectId: Long, stackSerialNumber: Long, classNameStringId: Long) {} open fun visitStackFrame(stackFrameId: Long, methodNameStringId: Long, methodSignatureStringId: Long, sourceFilenameStringId: Long, classSerialNumber: Long, lineNumber: Int) { } open fun visitStackTrace(stackTraceSerialNumber: Long, threadSerialNumber: Long, numberOfFrames: Int, stackFrameIds: LongArray) { } // TODO: Many of these are not implemented yet. Events are fired, but there are no parameters open fun visitAllocSites() {} open fun visitHeapSummary(totalLiveBytes: Long, totalLiveInstances: Long, totalBytesAllocated: Long, totalInstancesAllocated: Long) {} open fun visitStartThread() {} open fun visitEndThread(threadSerialNumber: Long) {} open fun visitHeapDump() {} open fun visitHeapDumpEnd() {} open fun visitCPUSamples() {} open fun visitControlSettings() {} open fun visitRootUnknown(objectId: Long) {} open fun visitRootGlobalJNI(objectId: Long, jniGlobalRefId: Long) {} open fun visitRootLocalJNI(objectId: Long, threadSerialNumber: Long, frameNumber: Long) {} open fun visitRootJavaFrame(objectId: Long, threadSerialNumber: Long, frameNumber: Long) {} open fun visitRootNativeStack(objectId: Long, threadSerialNumber: Long) {} open fun visitRootStickyClass(objectId: Long) {} open fun visitRootThreadBlock(objectId: Long, threadSerialNumber: Long) {} open fun visitRootMonitorUsed(objectId: Long) {} open fun visitRootThreadObject(objectId: Long, threadSerialNumber: Long, stackTraceSerialNumber: Long) {} open fun visitPrimitiveArrayDump( arrayObjectId: Long, stackTraceSerialNumber: Long, numberOfElements: Long, elementType: Type) { } open fun visitClassDump( classId: Long, stackTraceSerialNumber: Long, superClassId: Long, classloaderClassId: Long, instanceSize: Long, constants: Array<ConstantPoolEntry>, staticFields: Array<StaticFieldEntry>, instanceFields: Array<InstanceFieldEntry>) { } open fun visitObjectArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, arrayClassObjectId: Long, objects: LongArray) {} open fun visitInstanceDump(objectId: Long, stackTraceSerialNumber: Long, classObjectId: Long, bytes: ByteBuffer) {} open fun visitUnloadClass(classSerialNumber: Long) {} }
apache-2.0
ced0c0dd03c8e8862ea0ba343cf95932
32.744966
136
0.707438
4.497317
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/multiModule/inlineMultiModuleWithController.kt
1
1450
// IGNORE_BACKEND: NATIVE // WITH_COROUTINES // WITH_RUNTIME // MODULE: lib(support) // FILE: lib.kt import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* var continuation: () -> Unit = { } var log = "" var finished = false class C { var v: String = "" inline suspend fun bar() { log += "before bar($v);" foo("1:$v") log += "inside bar($v);" foo("2:$v") log += "after bar($v);" } } suspend fun <T> foo(v: T): T = suspendCoroutineOrReturn { x -> continuation = { x.resume(v) } log += "foo($v);" COROUTINE_SUSPENDED } fun C.builder(c: suspend C.() -> Unit) { c.startCoroutine(this, handleResultContinuation { continuation = { } finished = true }) } // MODULE: main(lib) // FILE: main.kt import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* suspend fun C.baz() { v = "A" bar() log += "between bar;" v = "B" bar() } val expectedString = "before bar(A);foo(1:A);@;inside bar(A);foo(2:A);@;after bar(A);" + "between bar;" + "before bar(B);foo(1:B);@;inside bar(B);foo(2:B);@;after bar(B);" fun box(): String { var c = C() c.builder { baz() } while (!finished) { log += "@;" continuation() } if (log != expectedString) return "fail: $log" return "OK" }
apache-2.0
eb199377aab4ec0aaf95ad24b73bc78c
17.831169
75
0.552414
3.333333
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/NotificationList.kt
1
710
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.common.Pageable /** * List of notifications that could be paged. */ @JsonClass(generateAdapter = true) data class NotificationList( @Json(name = "total") override val total: Int? = null, @Json(name = "page") override val page: Int? = null, @Json(name = "per_page") override val perPage: Int? = null, @Json(name = "paging") override val paging: Paging? = null, @Json(name = "data") override val data: List<Notification>? = null, @Json(name = "filtered_total") override val filteredTotal: Int? = null ) : Pageable<Notification>
mit
4f3f6329737477615865c5e9cb43c35e
22.666667
50
0.676056
3.641026
false
false
false
false
smmribeiro/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUVariable.kt
2
9664
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.java import com.intellij.psi.* import com.intellij.psi.impl.light.LightRecordCanonicalConstructor.LightRecordConstructorParameter import com.intellij.psi.impl.light.LightRecordField import com.intellij.psi.impl.source.PsiParameterImpl import com.intellij.psi.impl.source.tree.java.PsiLocalVariableImpl import com.intellij.psi.util.PsiTypesUtil import com.intellij.psi.util.parentOfType import com.intellij.util.castSafelyTo import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* import org.jetbrains.uast.internal.accommodate import org.jetbrains.uast.internal.alternative import org.jetbrains.uast.java.internal.JavaUElementWithComments @ApiStatus.Internal abstract class AbstractJavaUVariable( givenParent: UElement? ) : JavaAbstractUElement(givenParent), PsiVariable, UVariableEx, JavaUElementWithComments, UAnchorOwner { abstract override val javaPsi: PsiVariable @Suppress("OverridingDeprecatedMember") override val psi get() = javaPsi override val uastInitializer: UExpression? by lz { val initializer = javaPsi.initializer ?: return@lz null UastFacade.findPlugin(initializer)?.convertElement(initializer, this) as? UExpression } override val uAnnotations: List<UAnnotation> by lz { javaPsi.annotations.map { JavaUAnnotation(it, this) } } override val typeReference: UTypeReferenceExpression? by lz { javaPsi.typeElement?.let { UastFacade.findPlugin(it)?.convertOpt<UTypeReferenceExpression>(javaPsi.typeElement, this) } } abstract override val sourcePsi: PsiVariable? override val uastAnchor: UIdentifier? get() = sourcePsi?.let { UIdentifier(it.nameIdentifier, this) } override fun equals(other: Any?): Boolean = other is AbstractJavaUVariable && javaPsi == other.javaPsi override fun hashCode(): Int = javaPsi.hashCode() } @ApiStatus.Internal class JavaUVariable( override val javaPsi: PsiVariable, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UVariableEx, PsiVariable by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiVariable get() = javaPsi override val sourcePsi: PsiVariable? get() = javaPsi.takeIf { it.isPhysical || it is PsiLocalVariableImpl} companion object { fun create(psi: PsiVariable, containingElement: UElement?): UVariable { return when (psi) { is PsiEnumConstant -> JavaUEnumConstant(psi, containingElement) is PsiLocalVariable -> JavaULocalVariable(psi, containingElement) is PsiParameter -> JavaUParameter(psi, containingElement) is PsiField -> JavaUField(psi, containingElement) else -> JavaUVariable(psi, containingElement) } } } override fun getOriginalElement(): PsiElement? = javaPsi.originalElement } @ApiStatus.Internal class JavaUParameter( override val javaPsi: PsiParameter, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UParameterEx, PsiParameter by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiParameter get() = javaPsi override val sourcePsi: PsiParameter? get() = javaPsi.takeIf { it.isPhysical || (it is PsiParameterImpl && it.parentOfType<PsiMethod>()?.let { canBeSourcePsi(it) } == true) } override fun getOriginalElement(): PsiElement? = javaPsi.originalElement } private class JavaRecordUParameter( override val sourcePsi: PsiRecordComponent, override val javaPsi: PsiParameter, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UParameterEx, PsiParameter by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiParameter get() = javaPsi override val uastAnchor: UIdentifier get() = UIdentifier(sourcePsi.nameIdentifier, this) override fun getPsiParentForLazyConversion(): PsiElement? = javaPsi.context } internal fun convertRecordConstructorParameterAlternatives( element: PsiElement, givenParent: UElement?, expectedTypes: Array<out Class<out UElement>> ): Sequence<UVariable> { val (psiRecordComponent, lightRecordField, lightConstructorParameter) = when (element) { is PsiRecordComponent -> Triple(element, null, null) is LightRecordConstructorParameter -> { val lightRecordField = element.parentOfType<PsiMethod>()?.containingClass?.findFieldByName(element.name, false) ?.castSafelyTo<LightRecordField>() ?: return emptySequence() Triple(lightRecordField.recordComponent, lightRecordField, element) } is LightRecordField -> Triple(element.recordComponent, element, null) else -> return emptySequence() } val paramAlternative = alternative { val psiClass = psiRecordComponent.containingClass ?: return@alternative null val jvmParameter = lightConstructorParameter ?: psiClass.constructors.asSequence() .filter { !it.isPhysical } .flatMap { it.parameterList.parameters.asSequence() }.firstOrNull { it.name == psiRecordComponent.name } JavaRecordUParameter(psiRecordComponent, jvmParameter ?: return@alternative null, givenParent) } val fieldAlternative = alternative { val psiField = lightRecordField ?: psiRecordComponent.containingClass?.findFieldByName(psiRecordComponent.name, false) ?: return@alternative null JavaRecordUField(psiRecordComponent, psiField, givenParent) } return when (element) { is LightRecordField -> expectedTypes.accommodate(fieldAlternative, paramAlternative) else -> expectedTypes.accommodate(paramAlternative, fieldAlternative) } } @ApiStatus.Internal class JavaUField( override val sourcePsi: PsiField, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UFieldEx, PsiField by sourcePsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiField get() = javaPsi override val javaPsi: PsiField = unwrap<UField, PsiField>(sourcePsi) override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement } private class JavaRecordUField( private val psiRecord: PsiRecordComponent, override val javaPsi: PsiField, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UFieldEx, PsiField by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiField get() = javaPsi override val sourcePsi: PsiVariable? get() = null override val uastAnchor: UIdentifier get() = UIdentifier(psiRecord.nameIdentifier, this) override fun getPsiParentForLazyConversion(): PsiElement? = javaPsi.context } @ApiStatus.Internal class JavaULocalVariable( override val sourcePsi: PsiLocalVariable, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), ULocalVariableEx, PsiLocalVariable by sourcePsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiLocalVariable get() = javaPsi override val javaPsi: PsiLocalVariable = unwrap<ULocalVariable, PsiLocalVariable>(sourcePsi) override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let { when (it) { is PsiResourceList -> it.parent else -> it } } override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement } @ApiStatus.Internal class JavaUEnumConstant( override val sourcePsi: PsiEnumConstant, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UEnumConstantEx, UCallExpression, PsiEnumConstant by sourcePsi, UMultiResolvable { override val initializingClass: UClass? by lz { UastFacade.findPlugin(sourcePsi)?.convertOpt(sourcePsi.initializingClass, this) } @Suppress("OverridingDeprecatedMember") override val psi: PsiEnumConstant get() = javaPsi override val javaPsi: PsiEnumConstant get() = sourcePsi override val kind: UastCallKind get() = UastCallKind.CONSTRUCTOR_CALL override val receiver: UExpression? get() = null override val receiverType: PsiType? get() = null override val methodIdentifier: UIdentifier? get() = null override val classReference: UReferenceExpression? get() = JavaEnumConstantClassReference(sourcePsi, this) override val typeArgumentCount: Int get() = 0 override val typeArguments: List<PsiType> get() = emptyList() override val valueArgumentCount: Int get() = sourcePsi.argumentList?.expressions?.size ?: 0 override val valueArguments: List<UExpression> by lz { sourcePsi.argumentList?.expressions?.map { UastFacade.findPlugin(it)?.convertElement(it, this) as? UExpression ?: UastEmptyExpression(this) } ?: emptyList() } override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i) override val returnType: PsiType? get() = sourcePsi.type override fun resolve(): PsiMethod? = sourcePsi.resolveMethod() override fun multiResolve(): Iterable<ResolveResult> = listOfNotNull(sourcePsi.resolveMethodGenerics()) override val methodName: String? get() = null private class JavaEnumConstantClassReference( override val sourcePsi: PsiEnumConstant, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable { override fun resolve() = sourcePsi.containingClass override fun multiResolve(): Iterable<ResolveResult> = listOfNotNull(resolve()?.let { PsiTypesUtil.getClassType(it).resolveGenerics() }) override val resolvedName: String? get() = sourcePsi.containingClass?.name override val identifier: String get() = sourcePsi.containingClass?.name ?: "<error>" } override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement }
apache-2.0
3f875d93dd49596d75a5c00a01a72a81
35.885496
140
0.763762
5.062336
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/DynamicPluginEnabler.kt
1
9758
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.plugins import com.intellij.application.options.RegistryManager import com.intellij.externalDependencies.DependencyOnPlugin import com.intellij.externalDependencies.ExternalDependenciesManager import com.intellij.ide.AppLifecycleListener import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.marketplace.statistics.PluginManagerUsageCollector import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.registry.RegistryValue import com.intellij.project.stateStore import com.intellij.util.xmlb.annotations.XCollection import org.jetbrains.annotations.ApiStatus import javax.swing.JComponent @State( name = "DynamicPluginEnabler", storages = [Storage(value = StoragePathMacros.NON_ROAMABLE_FILE, roamingType = RoamingType.DISABLED)], reloadable = false, ) @ApiStatus.Internal class DynamicPluginEnabler : SimplePersistentStateComponent<DynamicPluginEnablerState>(DynamicPluginEnablerState()), PluginEnabler { companion object { private val isPerProjectEnabledValue: RegistryValue get() = RegistryManager.getInstance().get("ide.plugins.per.project") @JvmStatic var isPerProjectEnabled: Boolean get() = isPerProjectEnabledValue.asBoolean() set(value) = isPerProjectEnabledValue.setValue(value) @JvmStatic @JvmOverloads fun findPluginTracker(project: Project, pluginEnabler: PluginEnabler = PluginEnabler.getInstance()): ProjectPluginTracker? { return (pluginEnabler as? DynamicPluginEnabler)?.getPluginTracker(project) } internal class EnableDisablePluginsActivity : StartupActivity { private val dynamicPluginEnabler = PluginEnabler.getInstance() as? DynamicPluginEnabler ?: throw ExtensionNotApplicableException.create() override fun runActivity(project: Project) { val tracker = dynamicPluginEnabler.getPluginTracker(project) val projects = openProjectsExcludingCurrent(project) val pluginIdsToLoad = tracker.enabledPluginsIds .union(dynamicPluginEnabler.locallyDisabledAndGloballyEnabledPlugins(projects)) val pluginIdsToUnload = tracker.disabledPluginsIds if (pluginIdsToLoad.isNotEmpty() || pluginIdsToUnload.isNotEmpty()) { val indicator = ProgressManager.getInstance().progressIndicator ApplicationManager.getApplication().invokeAndWait { indicator?.let { it.text = IdeBundle.message("plugins.progress.loading.plugins.for.current.project.title", project.name) } DynamicPlugins.loadPlugins(pluginIdsToLoad.toPluginDescriptors()) indicator?.let { it.text = IdeBundle.message("plugins.progress.unloading.plugins.for.current.project.title", project.name) } dynamicPluginEnabler.unloadPlugins( pluginIdsToUnload.toPluginDescriptors(), project, projects, ) } } } } private fun openProjectsExcludingCurrent(project: Project?) = ProjectManager.getInstance().openProjects.filterNot { it == project } } val trackers: Map<String, ProjectPluginTracker> get(): Map<String, ProjectPluginTracker> = state.trackers private var applicationShuttingDown = false init { val connection = ApplicationManager.getApplication().messageBus.connect() connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosing(project: Project) { if (applicationShuttingDown) { return } val tracker = getPluginTracker(project) val projects = openProjectsExcludingCurrent(project) val descriptorsToLoad = if (projects.isNotEmpty()) { emptyList() } else { tracker.disabledPluginsIds .filterNot { isDisabled(it) } .toPluginDescriptors() } DynamicPlugins.loadPlugins(descriptorsToLoad) val descriptorsToUnload = tracker.enabledPluginsIds .union(locallyDisabledPlugins(projects)) .toPluginDescriptors() unloadPlugins( descriptorsToUnload, project, projects, ) } }) connection.subscribe(AppLifecycleListener.TOPIC, object : AppLifecycleListener { override fun appWillBeClosed(isRestart: Boolean) { applicationShuttingDown = true } }) } fun getPluginTracker(project: Project): ProjectPluginTracker = state.findStateByProject(project) override fun isDisabled(pluginId: PluginId) = PluginEnabler.HEADLESS.isDisabled(pluginId) override fun enable(descriptors: Collection<IdeaPluginDescriptor>) = updatePluginsState(descriptors, PluginEnableDisableAction.ENABLE_GLOBALLY) override fun disable(descriptors: Collection<IdeaPluginDescriptor>) = updatePluginsState(descriptors, PluginEnableDisableAction.DISABLE_GLOBALLY) @ApiStatus.Internal @JvmOverloads fun updatePluginsState( descriptors: Collection<IdeaPluginDescriptor>, action: PluginEnableDisableAction, project: Project? = null, parentComponent: JComponent? = null, ): Boolean { assert(!action.isPerProject || project != null) val pluginIds = descriptors.toPluginSet() fun unloadExcessPlugins() = unloadPlugins( descriptors, project, openProjectsExcludingCurrent(project), parentComponent, ) PluginManagerUsageCollector.pluginsStateChanged(descriptors, action, project) return when (action) { PluginEnableDisableAction.ENABLE_GLOBALLY -> { state.stopTracking(pluginIds) val loaded = DynamicPlugins.loadPlugins(descriptors) PluginEnabler.HEADLESS.enableById(pluginIds) loaded } PluginEnableDisableAction.ENABLE_FOR_PROJECT -> { state.startTracking(project!!, pluginIds, true) DynamicPlugins.loadPlugins(descriptors) } PluginEnableDisableAction.ENABLE_FOR_PROJECT_DISABLE_GLOBALLY -> { PluginEnabler.HEADLESS.disableById(pluginIds) descriptors.forEach { it.isEnabled = true } state.startTracking(project!!, pluginIds, true) true } PluginEnableDisableAction.DISABLE_GLOBALLY -> { PluginEnabler.HEADLESS.disableById(pluginIds) state.stopTracking(pluginIds) unloadExcessPlugins() } PluginEnableDisableAction.DISABLE_FOR_PROJECT -> { state.startTracking(project!!, pluginIds, false) unloadExcessPlugins() } PluginEnableDisableAction.DISABLE_FOR_PROJECT_ENABLE_GLOBALLY -> false } } private fun unloadPlugins( descriptors: Collection<IdeaPluginDescriptor>, project: Project?, projects: List<Project>, parentComponent: JComponent? = null, ): Boolean { val predicate = when (project) { null -> { _: PluginId -> true } else -> shouldUnload(projects) } return DynamicPlugins.unloadPlugins( descriptors.filter { predicate(it.pluginId) }, project, parentComponent, ) } private fun locallyDisabledPlugins(projects: List<Project>): Collection<PluginId> { return projects .map { getPluginTracker(it) } .flatMap { it.disabledPluginsIds } } private fun locallyDisabledAndGloballyEnabledPlugins(projects: List<Project>): Collection<PluginId> { return locallyDisabledPlugins(projects) .filterNot { isDisabled(it) } } private fun shouldUnload(openProjects: List<Project>) = object : (PluginId) -> Boolean { private val trackers = openProjects .map { getPluginTracker(it) } private val requiredPluginIds = openProjects .map { ExternalDependenciesManager.getInstance(it) } .flatMap { it.getDependencies(DependencyOnPlugin::class.java) } .mapTo(HashSet()) { it.pluginId } override fun invoke(pluginId: PluginId): Boolean { return !requiredPluginIds.contains(pluginId.idString) && !trackers.any { it.isEnabled(pluginId) } && (isDisabled(pluginId) || trackers.all { it.isDisabled(pluginId) }) } } } @ApiStatus.Internal class DynamicPluginEnablerState : BaseState() { @get:XCollection(propertyElementName = "trackers", style = XCollection.Style.v2) internal val trackers by map<String, ProjectPluginTracker>() fun startTracking(project: Project, pluginIds: Collection<PluginId>, enable: Boolean) { val updated = findStateByProject(project) .startTracking(pluginIds, enable) if (updated) { incrementModificationCount() } } fun stopTracking(pluginIds: Collection<PluginId>) { var updated = false trackers.values.forEach { updated = it.stopTracking(pluginIds) || updated } if (updated) { incrementModificationCount() } } internal fun findStateByProject(project: Project): ProjectPluginTracker { val workspaceId = if (project.isDefault) null else project.stateStore.projectWorkspaceId val projectName = project.name return trackers.computeIfAbsent(workspaceId ?: projectName) { ProjectPluginTracker().also { it.projectName = projectName incrementModificationCount() } } } }
apache-2.0
904d25b45dfea1467dd963a5a5a37f1c
35.01107
147
0.71777
5.011813
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/merge/dialog/FlatComboBoxUI.kt
8
3948
// 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 git4idea.merge.dialog import com.intellij.ide.ui.laf.darcula.DarculaUIUtil import com.intellij.ide.ui.laf.darcula.ui.DarculaComboBoxUI import com.intellij.openapi.util.NlsContexts import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.ComponentWithEmptyText import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.StatusText import java.awt.Component import java.awt.Graphics2D import java.awt.Insets import java.awt.Rectangle import java.awt.geom.Line2D import java.awt.geom.Rectangle2D import java.awt.geom.RectangularShape import javax.swing.JButton import javax.swing.JComboBox import javax.swing.JComponent import javax.swing.JList import javax.swing.plaf.basic.ComboPopup /** * ComboBox UI that enables to manager component side border and outer insets. * * @param border component border * @param outerInsets component outer insets * @param popupEmptyText text to show when component have no options */ internal class FlatComboBoxUI(var border: Insets = Insets(1, 1, 1, 1), var outerInsets: Insets = JBInsets.create(DarculaUIUtil.BW.get(), DarculaUIUtil.BW.get()), @NlsContexts.StatusText private val popupEmptyText: String = StatusText.getDefaultEmptyText(), private val popupComponentProvider: ((JComponent) -> JComponent)? = null) : DarculaComboBoxUI(0f, Insets(1, 0, 1, 0), false) { override fun paintArrow(g2: Graphics2D, btn: JButton) { g2.color = JBUI.CurrentTheme.Arrow.foregroundColor(comboBox.isEnabled) val r = Rectangle(btn.size) JBInsets.removeFrom(r, JBUI.insets(1, 0, 1, 1)) val tW = JBUIScale.scale(9) val tH = JBUIScale.scale(5) val xU = (r.width - tW) / 2 - JBUIScale.scale(1) val yU = (r.height - tH) / 2 + JBUIScale.scale(1) val leftLine = Line2D.Float(xU.toFloat(), yU.toFloat(), xU.toFloat() + tW.toFloat() / 2f, yU.toFloat() + tH.toFloat()) val rightLine = Line2D.Float(xU.toFloat() + tW.toFloat() / 2f, yU.toFloat() + tH.toFloat(), xU.toFloat() + tW.toFloat(), yU.toFloat()) g2.draw(leftLine) g2.draw(rightLine) } override fun getOuterShape(r: Rectangle, bw: Float, arc: Float): RectangularShape { return Rectangle2D.Float(outerInsets.left.toFloat(), outerInsets.top.toFloat(), r.width - outerInsets.left.toFloat() - outerInsets.right.toFloat(), r.height - outerInsets.top.toFloat() - outerInsets.bottom.toFloat()) } override fun getInnerShape(r: Rectangle, bw: Float, lw: Float, arc: Float): RectangularShape { return Rectangle2D.Float(outerInsets.left + lw * border.left, outerInsets.top + lw, r.width - (outerInsets.left + lw * border.left) - (outerInsets.right + lw * border.right), r.height - (outerInsets.top + lw) - (outerInsets.bottom + lw)) } override fun getBorderInsets(c: Component?) = outerInsets override fun createPopup(): ComboPopup { return MyComboBoxPopup(comboBox).apply { configureList(list) configurePopupComponent(popupComponentProvider) } } private fun configureList(list: JList<*>) { (list as? ComponentWithEmptyText)?.let { it.emptyText.text = popupEmptyText } } private class MyComboBoxPopup(comboBox: JComboBox<*>) : CustomComboPopup(comboBox) { fun configurePopupComponent(popupComponentProvider: ((JComponent) -> JComponent)? = null) { val popupComponent = popupComponentProvider?.invoke(scroller) if (popupComponent != null) { removeAll() add(popupComponent) } } } }
apache-2.0
e15cb1a45e3adf2689b7babfd078bc61
38.888889
140
0.668693
3.995951
false
false
false
false
jotomo/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgStatusBasic_k.kt
1
1362
package info.nightscout.androidaps.danaRKorean.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.comm.MessageBase import info.nightscout.androidaps.logging.LTag class MsgStatusBasic_k( injector: HasAndroidInjector ) : MessageBase(injector) { init { SetCommand(0x020A) aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(bytes: ByteArray) { val currentBasal = intFromBuff(bytes, 0, 2) / 100.0 val batteryRemaining = intFromBuff(bytes, 2, 1) val reservoirRemainingUnits = intFromBuff(bytes, 3, 3) / 750.0 val dailyTotalUnits = intFromBuff(bytes, 6, 3) / 750.0 val maxDailyTotalUnits = intFromBuff(bytes, 9, 2) / 100 danaPump.dailyTotalUnits = dailyTotalUnits danaPump.maxDailyTotalUnits = maxDailyTotalUnits danaPump.reservoirRemainingUnits = reservoirRemainingUnits danaPump.currentBasal = currentBasal danaPump.batteryRemaining = batteryRemaining aapsLogger.debug(LTag.PUMPCOMM, "Daily total units: $dailyTotalUnits") aapsLogger.debug(LTag.PUMPCOMM, "Max daily total units: $maxDailyTotalUnits") aapsLogger.debug(LTag.PUMPCOMM, "Reservoir remaining units: $reservoirRemainingUnits") aapsLogger.debug(LTag.PUMPCOMM, "Current basal: $currentBasal") } }
agpl-3.0
68b8b4bef2eb90d4d5510513fe6a2dac
41.59375
94
0.726872
4.601351
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/activities/PaymentMethodsSettingsActivity.kt
1
8582
package com.kickstarter.ui.activities import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isGone import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.LinearLayoutManager import com.kickstarter.R import com.kickstarter.databinding.ActivitySettingsPaymentMethodsBinding import com.kickstarter.libs.utils.extensions.getEnvironment import com.kickstarter.libs.utils.extensions.getPaymentSheetConfiguration import com.kickstarter.models.StoredCard import com.kickstarter.ui.adapters.PaymentMethodsAdapter import com.kickstarter.ui.extensions.showErrorSnackBar import com.kickstarter.ui.extensions.showErrorToast import com.kickstarter.ui.extensions.showSnackbar import com.kickstarter.viewmodels.PaymentMethodsViewModel import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.PaymentSheetResult import com.stripe.android.paymentsheet.model.PaymentOption import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers class PaymentMethodsSettingsActivity : AppCompatActivity() { private lateinit var adapter: PaymentMethodsAdapter private var showDeleteCardDialog: AlertDialog? = null private lateinit var binding: ActivitySettingsPaymentMethodsBinding private lateinit var flowController: PaymentSheet.FlowController private lateinit var viewModelFactory: PaymentMethodsViewModel.Factory private val viewModel: PaymentMethodsViewModel by viewModels { viewModelFactory } private lateinit var compositeDisposable: CompositeDisposable override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) compositeDisposable = CompositeDisposable() this.getEnvironment()?.let { env -> viewModelFactory = PaymentMethodsViewModel.Factory(env) } binding = ActivitySettingsPaymentMethodsBinding.inflate(layoutInflater) setContentView(binding.root) setUpRecyclerView() flowController = PaymentSheet.FlowController.create( activity = this, paymentOptionCallback = ::onPaymentOption, paymentResultCallback = ::onPaymentSheetResult ) compositeDisposable.add( this.viewModel.outputs.cards() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { setCards(it) } ) compositeDisposable.add( this.viewModel.outputs.dividerIsVisible() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { binding.paymentsDivider.isGone = !it } ) compositeDisposable.add( this.viewModel.outputs.error() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { showSnackbar(binding.settingPaymentMethodsActivityToolbar.paymentMethodsToolbar, it) } ) compositeDisposable.add( this.viewModel.outputs.progressBarIsVisible() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { binding.progressBar.isGone = !it } ) compositeDisposable.add( this.viewModel.outputs.showDeleteCardDialog() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { lazyDeleteCardConfirmationDialog().show() } ) compositeDisposable.add( this.viewModel.successDeleting() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { showSnackbar(binding.settingPaymentMethodsActivityToolbar.paymentMethodsToolbar, R.string.Got_it_your_changes_have_been_saved) } ) binding.addNewCard.setOnClickListener { this.viewModel.inputs.newCardButtonClicked() } compositeDisposable.add( this.viewModel.outputs.presentPaymentSheet() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { flowControllerPresentPaymentOption(it) } ) compositeDisposable.add( this.viewModel.showError() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { showErrorSnackBar(binding.settingPaymentMethodsActivityToolbar.paymentMethodsToolbar, getString(R.string.general_error_something_wrong)) } ) compositeDisposable.add( this.viewModel.successSaving() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { showSnackbar(binding.settingPaymentMethodsActivityToolbar.paymentMethodsToolbar, R.string.Got_it_your_changes_have_been_saved) } ) } @Override override fun onDestroy() { compositeDisposable.clear() super.onDestroy() } private fun flowControllerPresentPaymentOption(clientSecret: String) { flowController.configureWithSetupIntent( setupIntentClientSecret = clientSecret, configuration = this.getPaymentSheetConfiguration(), callback = ::onConfigured ) } private fun onConfigured(success: Boolean, error: Throwable?) { if (success) { flowController.presentPaymentOptions() } else { showErrorToast(this, binding.paymentMethodsContent, getString(R.string.general_error_something_wrong)) } } private fun onPaymentOption(paymentOption: PaymentOption?) { paymentOption?.let { flowController.confirm() this.viewModel.inputs.confirmedLoading(true) } } fun onPaymentSheetResult(paymentSheetResult: PaymentSheetResult) { this.viewModel.inputs.confirmedLoading(false) when (paymentSheetResult) { is PaymentSheetResult.Canceled -> { showErrorSnackBar(binding.paymentMethodsContent, getString(R.string.general_error_oops)) } is PaymentSheetResult.Failed -> { showErrorSnackBar(binding.paymentMethodsContent, getString(R.string.general_error_something_wrong)) } is PaymentSheetResult.Completed -> { this.viewModel.inputs.savePaymentOption() } } } private fun lazyDeleteCardConfirmationDialog(): AlertDialog { if (this.showDeleteCardDialog == null) { this.showDeleteCardDialog = AlertDialog.Builder(this, R.style.AlertDialog) .setCancelable(false) .setTitle(R.string.Remove_this_card) .setMessage(R.string.Are_you_sure_you_wish_to_remove_this_card) .setNegativeButton(R.string.No_nevermind) { _, _ -> lazyDeleteCardConfirmationDialog().dismiss() } .setPositiveButton(R.string.Yes_remove) { _, _ -> this.viewModel.inputs.confirmDeleteCardClicked() } .create() } return this.showDeleteCardDialog!! } private fun setCards(cards: List<StoredCard>) = this.adapter.populateCards(cards) private fun setUpRecyclerView() { this.adapter = PaymentMethodsAdapter( this.viewModel, object : DiffUtil.ItemCallback<Any>() { override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean { return areCardsTheSame(oldItem as StoredCard, newItem as StoredCard) } override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean { return areCardsTheSame(oldItem as StoredCard, newItem as StoredCard) } private fun areCardsTheSame(oldCard: StoredCard, newCard: StoredCard): Boolean { return oldCard.id() == newCard.id() } } ) binding.recyclerView.adapter = this.adapter binding.recyclerView.layoutManager = LinearLayoutManager(this) } }
apache-2.0
8db53c475fc98979971e221e4932c407
38.548387
157
0.658821
5.561892
false
false
false
false
fabmax/kool
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/helloworld/HelloUi.kt
1
1207
package de.fabmax.kool.demo.helloworld import de.fabmax.kool.KoolContext import de.fabmax.kool.demo.DemoScene import de.fabmax.kool.modules.ui2.* import de.fabmax.kool.scene.Scene import de.fabmax.kool.util.MdColor class HelloUiDemo : DemoScene("Hello UI") { override fun Scene.setupMainScene(ctx: KoolContext) { setupUiScene(clearScreen = true) +Panel(colors = Colors.singleColorLight(MdColor.LIGHT_GREEN)) { modifier .size(400.dp, 300.dp) .align(AlignmentX.Center, AlignmentY.Center) .background(RoundRectBackground(colors.background, 16.dp)) val clickCount = weakRememberState(0) Button("Click me!") { modifier .alignX(AlignmentX.Center) .margin(sizes.largeGap * 4f) .padding(horizontal = sizes.largeGap, vertical = sizes.gap) .font(sizes.largeText) .onClick { clickCount.set(clickCount.value + 1) } } Text("Button clicked ${clickCount.use()} times") { modifier .alignX(AlignmentX.Center) } } } }
apache-2.0
00802b3822f71056eaa0de65fe680f1e
34.529412
79
0.579122
4.310714
false
false
false
false
ingokegel/intellij-community
plugins/git4idea/src/git4idea/branch/GitCompareBranchesLogProperties.kt
10
1974
// 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 git4idea.branch import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.vcs.log.impl.CommonUiProperties import com.intellij.vcs.log.impl.VcsLogUiProperties.VcsLogUiProperty import com.intellij.vcs.log.impl.VcsLogUiPropertiesImpl import git4idea.update.VcsLogUiPropertiesWithSharedRecentFilters @State(name = "Git.Compare.Branches.Top.Log.Properties", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)]) @Service(Service.Level.PROJECT) internal class GitCompareBranchesTopLogProperties(project: Project) : GitCompareBranchesLogProperties(project) @State(name = "Git.Compare.Branches.Bottom.Log.Properties", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)]) @Service(Service.Level.PROJECT) internal class GitCompareBranchesBottomLogProperties(project: Project) : GitCompareBranchesLogProperties(project) abstract class GitCompareBranchesLogProperties(project: Project) : VcsLogUiPropertiesWithSharedRecentFilters<GitCompareBranchesLogProperties.MyState>(project, service()) { class MyState : VcsLogUiPropertiesImpl.State() { var SHOW_DIFF_PREVIEW = false } var commonState = MyState() override fun getState(): MyState { return commonState } override fun loadState(state: MyState) { commonState = state } override fun <T> get(property: VcsLogUiProperty<T>): T = if (CommonUiProperties.SHOW_DIFF_PREVIEW == property) { @Suppress("UNCHECKED_CAST") state.SHOW_DIFF_PREVIEW as T } else { super.get(property) } override fun <T> set(property: VcsLogUiProperty<T>, value: T) { if (CommonUiProperties.SHOW_DIFF_PREVIEW == property) { state.SHOW_DIFF_PREVIEW = (value as Boolean) onPropertyChanged(property) } else { super.set(property, value) } } }
apache-2.0
8cf5045442a227eaf71c53afa2e7d9f8
35.555556
140
0.764438
4.147059
false
false
false
false
mtransitapps/mtransit-for-android
src/main/java/org/mtransit/android/ui/type/rts/RTSAgencyRoutesViewModel.kt
1
4791
package org.mtransit.android.ui.type.rts import androidx.core.content.edit import androidx.lifecycle.LiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.distinctUntilChanged import androidx.lifecycle.liveData import androidx.lifecycle.map import androidx.lifecycle.switchMap import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import org.mtransit.android.common.repository.DefaultPreferenceRepository import org.mtransit.android.commons.ColorUtils import org.mtransit.android.commons.MTLog import org.mtransit.android.commons.data.Route import org.mtransit.android.commons.pref.liveData import org.mtransit.android.data.AgencyBaseProperties import org.mtransit.android.data.IAgencyProperties import org.mtransit.android.datasource.DataSourceRequestManager import org.mtransit.android.datasource.DataSourcesRepository import org.mtransit.android.ui.view.common.PairMediatorLiveData import org.mtransit.android.ui.view.common.getLiveDataDistinct import javax.inject.Inject @HiltViewModel class RTSAgencyRoutesViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val dataSourcesRepository: DataSourcesRepository, private val dataSourceRequestManager: DataSourceRequestManager, private val defaultPrefRepository: DefaultPreferenceRepository, ) : ViewModel(), MTLog.Loggable { companion object { private val LOG_TAG = RTSAgencyRoutesViewModel::class.java.simpleName internal const val EXTRA_AGENCY_AUTHORITY = "extra_agency_authority" internal const val EXTRA_COLOR_INT = "extra_color_int" } override fun getLogTag(): String = agency.value?.shortName?.let { "${LOG_TAG}-$it" } ?: LOG_TAG private val _authority = savedStateHandle.getLiveDataDistinct<String?>(EXTRA_AGENCY_AUTHORITY) val authorityShort: LiveData<String?> = _authority.map { it?.substringAfter(IAgencyProperties.PKG_COMMON) } val colorInt = savedStateHandle.getLiveDataDistinct<Int?>(EXTRA_COLOR_INT) val agency: LiveData<AgencyBaseProperties?> = this._authority.switchMap { authority -> this.dataSourcesRepository.readingAgencyBase(authority) // #onModulesUpdated } val routes: LiveData<List<Route>?> = this._authority.switchMap { authority -> liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) { authority?.let { emit( dataSourceRequestManager.findAllRTSAgencyRoutes(authority) ?.sortedWith(Route.SHORT_NAME_COMPARATOR) ) } } } private val _routeColorInts: LiveData<List<Int>?> = routes.map { routes -> routes?.filter { it.hasColor() }?.map { it.colorInt } } val colorIntDistinct: LiveData<Int?> = PairMediatorLiveData(colorInt, _routeColorInts).map { (colorInt, routeColorInts) -> colorInt?.let { if (routeColorInts == null || (routeColorInts.isNotEmpty() && !routeColorInts.contains(colorInt))) { colorInt } else { val distinctColorInt = routeColorInts.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key ?: colorInt if (ColorUtils.isTooLight(distinctColorInt)) { ColorUtils.darkenColor(distinctColorInt, 0.2F) } else { ColorUtils.lightenColor(distinctColorInt, 0.2F) } } } } val showingListInsteadOfGrid: LiveData<Boolean> = _authority.switchMap { authority -> liveData { authority?.let { emitSource( defaultPrefRepository.pref.liveData( DefaultPreferenceRepository.getPREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID(it), defaultPrefRepository.getValue( DefaultPreferenceRepository.PREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID_LAST_SET, DefaultPreferenceRepository.PREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID_DEFAULT ) ) ) } } }.distinctUntilChanged() fun saveShowingListInsteadOfGrid(showingListInsteadOfGrid: Boolean) { defaultPrefRepository.pref.edit { putBoolean(DefaultPreferenceRepository.PREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID_LAST_SET, showingListInsteadOfGrid) _authority.value?.let { authority -> putBoolean(DefaultPreferenceRepository.getPREFS_RTS_ROUTES_SHOWING_LIST_INSTEAD_OF_GRID(authority), showingListInsteadOfGrid) } } } }
apache-2.0
8a16db315a2558a43d22fd920a603d7a
41.035088
141
0.687957
4.771912
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/source/online/english/Mangapanda.kt
1
7283
/* * This file is part of TachiyomiEX. * * TachiyomiEX 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. * * TachiyomiEX 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 TachiyomiEX. If not, see <http://www.gnu.org/licenses/>. */ package eu.kanade.tachiyomi.data.source.online.english import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.source.EN import eu.kanade.tachiyomi.data.source.Language import eu.kanade.tachiyomi.data.source.Sources import eu.kanade.tachiyomi.data.source.model.MangasPage import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.data.source.online.ParsedOnlineSource import eu.kanade.tachiyomi.util.UrlUtil import eu.kanade.tachiyomi.util.asJsoup import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat class Mangapanda(override val source: Sources) : ParsedOnlineSource() { override val baseUrl = "http://mangapanda.com" override val lang: Language get() = EN override fun supportsLatest() = true override fun popularMangaInitialUrl() = "$baseUrl/popular" override fun latestUpdatesInitialUrl() = "$baseUrl/latest" override fun popularMangaSelector() = "div#mangaresults > div.mangaresultitem" override fun popularMangaFromElement(element: Element, manga: Manga) { element.select("div.manga_name > div > h3 > a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.text() } } override fun popularMangaNextPageSelector() = "div#sp > a:contains(>)" fun latestUpdateSelector() = "table.updates > tbody > tr" override fun latestUpdatesParse(response: Response, page: MangasPage) { val document = response.asJsoup() for (element in document.select(latestUpdateSelector())) { Manga.create(id).apply { latestFromeElement(element, this) page.mangas.add(this) } } popularMangaNextPageSelector().let { selector -> page.nextPageUrl = document.select(selector).first()?.absUrl("href") } } private fun latestFromeElement(element: Element, manga: Manga) { val infoElement = element.select("td > a.chapter") manga.setUrlWithoutDomain(infoElement.attr("href")) manga.title = infoElement.text() } override fun searchMangaInitialUrl(query: String, filters: List<Filter>) = "$baseUrl/search/?w=$query&rd=0&status=0&order=0&genre=${filterString(filters)}&p=0" override fun searchMangaSelector() = "div#mangaresults > div.mangaresultitem" override fun searchMangaFromElement(element: Element, manga: Manga) { popularMangaFromElement(element, manga) } override fun searchMangaNextPageSelector() = "div#sp > a:contains(>)" override fun mangaDetailsParse(document: Document, manga: Manga) { val infoElement = document.select("div#mangaproperties").first().select("table > tbody").first() manga.thumbnail_url = document.select("div#mangaimg > img").first()?.attr("src") manga.status = infoElement.select("tr:eq(3) > td:eq(1)").first()?.text().orEmpty().let { parseStatus(it) } manga.author = infoElement.select("tr:eq(4) > td:eq(1)").first()?.text() manga.artist = infoElement.select("tr:eq(5) > td:eq(1)").first()?.text() manga.genre = infoElement.select("tr:eq(7) > td:eq(1)").first()?.text() manga.description = document.select("div#readmangasum").first()?.text() } private fun parseStatus(status: String) = when { status.contains("Ongoing") -> Manga.ONGOING status.contains("Completed") -> Manga.COMPLETED else -> Manga.UNKNOWN } override fun chapterListSelector() = "table#listing tr:gt(0)" override fun chapterListParse(response: Response, chapters: MutableList<Chapter>) { super.chapterListParse(response, chapters) chapters.reverse() } override fun chapterFromElement(element: Element, chapter: Chapter) { val urlElement = element.select("a").first() chapter.url = UrlUtil.getPath(urlElement.attr("href")) chapter.name = urlElement.text() chapter.date_upload = element.select("td:eq(1)").first()?.text()?.let { SimpleDateFormat("MM/dd/yyyy").parse(it).time } ?: 0 } override fun pageListParse(document: Document, pages: MutableList<Page>) { val url = document.baseUri().toString() document.select("select#pageMenu").first()?.getElementsByTag("option")?.forEach { val page = it.attr("value").substringAfterLast('/') pages.add(Page(pages.size, "$url/$page")) } pages.getOrNull(0)?.imageUrl = imageUrlParse(document) } override fun imageUrlParse(document: Document): String = document.getElementById("img").attr("src") fun filterString(filters: List<Filter>): String { val sb = StringBuilder() var i = 0 if (filters.isEmpty()) return "0000000000000000000000000000000000000" while (i < 37) { for ((id1) in filters) { if (i == id1.toInt()) sb.append("1") else sb.append("0") } ++i } return sb.toString() } override fun getFilterList(): List<Filter> = listOf( Filter("0", "Action"), Filter("1", "Adventure"), Filter("2", "Comedy"), Filter("3", "Demons"), Filter("4", "Drama"), Filter("5", "Ecchi"), Filter("6", "Fantasy"), Filter("7", "Gender Bender"), Filter("8", "Harem"), Filter("9", "Historical"), Filter("10", "Horror"), Filter("11", "Josei"), Filter("12", "Magic"), Filter("13", "Martial Arts"), Filter("14", "Mature"), Filter("15", "Mecha"), Filter("16", "Military"), Filter("17", "Mystery"), Filter("18", "One shot"), Filter("19", "Psychological"), Filter("20", "Romance"), Filter("21", "School Life"), Filter("22", "Sci-fi"), Filter("23", "Seinen"), Filter("24", "Shotacon"), Filter("25", "Shoujo"), Filter("26", "Shoujo Ai"), Filter("27", "Shounen"), Filter("28", "Shounen Ai"), Filter("29", "Slice of Life"), Filter("30", "Smut"), Filter("31", "Sports"), Filter("32", "Supernatural"), Filter("33", "Tragedy"), Filter("34", "Vampire"), Filter("35", "Yaoi"), Filter("36", "Yuri") ) }
gpl-3.0
ff052007db909b75f0b9fdf4c44cc739
37.136126
114
0.618838
4.284118
false
false
false
false