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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hyst329/OpenFool
|
core/src/ru/hyst329/openfool/Card.kt
|
1
|
714
|
package ru.hyst329.openfool
import java.util.Locale
class Card(internal val suit: Suit, internal val rank: Rank) {
internal fun beats(other: Card, trumpSuit: Suit, deuceBeatsAce: Boolean): Boolean {
val thisRankValue = (this.rank.value + 11) % 13
val otherRankValue = (other.rank.value + 11) % 13
if (this.suit === other.suit) {
// deuce: (2 + 11) % 13 == 0, ace: (1 + 11) % 13 == 12
return thisRankValue >= otherRankValue || (deuceBeatsAce && thisRankValue == 0 && otherRankValue == 12)
} else
return this.suit === trumpSuit
}
override fun toString(): String {
return "${rank.value}${suit.name.toLowerCase()[0]}"
}
}
|
gpl-3.0
|
5a57022535eb78d2af1d17db18dbe5fa
| 34.7 | 115 | 0.598039 | 3.624365 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/magic/LoriToolsCommand.kt
|
1
|
1775
|
package net.perfectdreams.loritta.morenitta.commands.vanilla.magic
import mu.KotlinLogging
import net.perfectdreams.loritta.morenitta.api.commands.CommandContext
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
class LoriToolsCommand(loritta: LorittaBot) : DiscordAbstractCommandBase(loritta, listOf("loritools"), net.perfectdreams.loritta.common.commands.CommandCategory.MAGIC) {
companion object {
private val logger = KotlinLogging.logger {}
}
override fun command() = create {
description { "Ferramentas de Administração da Loritta" }
onlyOwner = true
executesDiscord {
logger.info { "Executing Lori Tools!" }
val allExecutors = listOf(
RegisterYouTubeChannelExecutor,
PurgeInactiveGuildsExecutor,
PurgeInactiveUsersExecutor,
PurgeInactiveGuildUsersExecutor,
SetSelfBackgroundExecutor,
SetSelfProfileDesignExecutor,
GenerateDailyShopExecutor,
PriceCorrectionExecutor,
LoriBanIpExecutor,
LoriUnbanIpExecutor,
DeleteAccountDataExecutor,
ChargebackRunExecutor,
EnableBoostExecutor,
DisableBoostExecutor
)
allExecutors.forEach {
val result = it.executes().invoke(this)
if (result) {
logger.info { "Executed ${it::class.simpleName} Executor!" }
return@executesDiscord
}
}
val replies = mutableListOf<LorittaReply>()
allExecutors.forEach {
replies.add(
LorittaReply(
"`${it.args}`",
mentionUser = false
)
)
}
reply(replies)
}
}
interface LoriToolsExecutor {
val args: String
fun executes(): (suspend CommandContext.() -> (Boolean))
}
}
|
agpl-3.0
|
4bfb7db2a67d0a33da9ed2e138c41b66
| 25.477612 | 169 | 0.747885 | 4.020408 | false | false | false | false |
MaibornWolff/codecharta
|
analysis/import/SourceCodeParser/src/main/kotlin/de/maibornwolff/codecharta/importer/sourcecodeparser/ProjectParser.kt
|
1
|
1500
|
package de.maibornwolff.codecharta.importer.sourcecodeparser
import de.maibornwolff.codecharta.importer.sourcecodeparser.metrics.ProjectMetrics
import de.maibornwolff.codecharta.importer.sourcecodeparser.sonaranalyzers.JavaSonarAnalyzer
import de.maibornwolff.codecharta.importer.sourcecodeparser.sonaranalyzers.SonarAnalyzer
import java.io.File
class ProjectParser(private val exclude: Array<String> = arrayOf(), private val verbose: Boolean = false, private val findIssues: Boolean = true) {
var metricKinds: MutableSet<String> = HashSet()
var projectMetrics = ProjectMetrics()
var sonarAnalyzers: MutableList<SonarAnalyzer> = mutableListOf()
fun setUpAnalyzers() {
sonarAnalyzers.add(JavaSonarAnalyzer(verbose, findIssues))
}
fun scanProject(root: File) {
val projectTraverser = ProjectTraverser(root, exclude)
projectTraverser.traverse()
for (analyzer in sonarAnalyzers) {
val files = projectTraverser.getFileListByExtension(analyzer.FILE_EXTENSION)
val metricsForKind: ProjectMetrics = analyzer.scanFiles(files, projectTraverser.root)
projectMetrics.merge(metricsForKind)
updateMetricKinds(metricsForKind)
}
}
private fun updateMetricKinds(metricsMap: ProjectMetrics) {
val sampleFile = metricsMap.getRandomFileName() ?: return
val fileMetrics = metricsMap.getFileMetricMap(sampleFile)!!.fileMetrics
metricKinds.addAll(fileMetrics.keys)
}
}
|
bsd-3-clause
|
1d77cc8062cd634c371d146c505ab7ab
| 43.117647 | 147 | 0.752 | 4.559271 | false | false | false | false |
STUDIO-apps/GeoShare_Android
|
mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/ui/SettingsActivity.kt
|
1
|
2381
|
package uk.co.appsbystudio.geoshare.utils.ui
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.UserProfileChangeRequest
import com.google.firebase.database.FirebaseDatabase
import uk.co.appsbystudio.geoshare.R
import uk.co.appsbystudio.geoshare.utils.ProfileSelectionResult
import uk.co.appsbystudio.geoshare.utils.firebase.UserInformation
class SettingsActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
private var user: FirebaseUser? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
val toolbar = findViewById<Toolbar>(R.id.toolbar_manager)
setSupportActionBar(toolbar)
if (supportActionBar != null) supportActionBar!!.setDisplayHomeAsUpEnabled(true)
fragmentManager.beginTransaction().replace(R.id.frame_content_main, SettingsFragment()).commit()
PreferenceManager.getDefaultSharedPreferences(applicationContext).registerOnSharedPreferenceChangeListener(this)
user = FirebaseAuth.getInstance().currentUser
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
ProfileSelectionResult().profilePictureResult(this, requestCode, resultCode, data, user?.uid)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (key == "display_name") {
val name = sharedPreferences.getString(key, "DEFAULT")
val userInfo = UserInformation(name, name.toLowerCase())
if (user != null) FirebaseDatabase.getInstance().reference.child("users").child(user!!.uid).setValue(userInfo)
val profileChangeRequest = UserProfileChangeRequest.Builder().setDisplayName(name).build()
user?.updateProfile(profileChangeRequest)
}
}
override fun onDestroy() {
super.onDestroy()
PreferenceManager.getDefaultSharedPreferences(applicationContext).unregisterOnSharedPreferenceChangeListener(this)
}
}
|
apache-2.0
|
60d57921872d72493dd16992f78ae98b
| 40.051724 | 122 | 0.765225 | 5.232967 | false | false | false | false |
Bombe/Sone
|
src/main/kotlin/net/pterodactylus/sone/web/pages/CreateReplyPage.kt
|
1
|
1630
|
package net.pterodactylus.sone.web.pages
import net.pterodactylus.sone.data.*
import net.pterodactylus.sone.main.*
import net.pterodactylus.sone.text.*
import net.pterodactylus.sone.utils.*
import net.pterodactylus.sone.web.*
import net.pterodactylus.sone.web.page.*
import net.pterodactylus.util.template.*
import javax.inject.*
/**
* This page lets the user post a reply to a post.
*/
@TemplatePath("/templates/createReply.html")
@ToadletPath("createReply.html")
class CreateReplyPage @Inject constructor(webInterface: WebInterface, loaders: Loaders, templateRenderer: TemplateRenderer) :
LoggedInPage("Page.CreateReply.Title", webInterface, loaders, templateRenderer) {
override fun handleRequest(soneRequest: SoneRequest, currentSone: Sone, templateContext: TemplateContext) {
val postId = soneRequest.httpRequest.getPartAsStringFailsafe("post", 36).apply { templateContext["postId"] = this }
val text = soneRequest.httpRequest.getPartAsStringFailsafe("text", 65536).trim().apply { templateContext["text"] = this }
val returnPage = soneRequest.httpRequest.getPartAsStringFailsafe("returnPage", 256).apply { templateContext["returnPage"] = this }
if (soneRequest.isPOST) {
if (text == "") {
templateContext["errorTextEmpty"] = true
return
}
val post = soneRequest.core.getPost(postId) ?: redirectTo("noPermission.html")
val sender = soneRequest.core.getLocalSone(soneRequest.httpRequest.getPartAsStringFailsafe("sender", 43)) ?: currentSone
soneRequest.core.createReply(sender, post, TextFilter.filter(soneRequest.httpRequest.getHeader("Host"), text))
redirectTo(returnPage)
}
}
}
|
gpl-3.0
|
0eaa11555d50f157ba8ece0d84d7bf4d
| 44.277778 | 132 | 0.770552 | 4.024691 | false | false | false | false |
kyegupov/ido_web_dictionary
|
conversion_tools/backend/src/main/kotlin/org/kyegupov/dictionary/common/load_dictionary.kt
|
1
|
2857
|
package org.kyegupov.dictionary.common
import org.jsoup.Jsoup
import java.io.InputStreamReader
import java.io.BufferedReader
import java.nio.file.*
import java.util.*
import java.util.stream.Collectors
data class DictionaryOfStringArticles(
val entries: List<String>,
val compactIndex: TreeMap<String, List<Int>>
)
var JAR_FS: FileSystem? = null
// https://stackoverflow.com/a/28057735
fun listResources(path: String): List<Path> {
println(path)
val uri = CLASS_LOADER.getResource(path).toURI()
val myPath: Path
if (uri.scheme == "jar") {
if (JAR_FS == null) {
JAR_FS = FileSystems.newFileSystem(uri, Collections.emptyMap<String, Any>())
}
myPath = JAR_FS!!.getPath(path)
} else {
myPath = Paths.get(uri)
}
return Files.walk(myPath, 1).skip(1).collect(Collectors.toList())
}
fun loadDataFromAlphabetizedShards(path: String) : DictionaryOfStringArticles {
val allArticles = mutableListOf<String>()
for (resource in listResources(path).sorted().filter{it.toString().endsWith(".txt")}) {
LOG.info("Reading shard $resource")
Files.newInputStream(resource).use {
val reader = BufferedReader(InputStreamReader(it))
var accumulator = ""
while (reader.ready()) {
val line = reader.readLine()
if (line == "") {
allArticles.add(accumulator)
accumulator = ""
} else {
if (accumulator != "") {
accumulator += " ";
}
accumulator += line
}
}
if (accumulator != "") {
allArticles.add(accumulator)
}
}
}
LOG.info("Building index")
return DictionaryOfStringArticles(
entries = allArticles,
compactIndex = buildIndex(allArticles))
}
private fun positionToWeight(index: Int, size: Int): Double {
return 1.0 - (1.0 * index / size)
}
fun buildIndex(articles: MutableList<String>): TreeMap<String, List<Int>> {
val index = TreeMap<String, MutableMap<Int, Double>>()
articles.forEachIndexed { i, entry ->
val html = Jsoup.parse(entry)
val keywords = html.select("[dict-key]").flatMap {it.attr("dict-key").split(',')}
val weightedKeywords = keywords.mapIndexed{ki, kw -> Weighted(kw, positionToWeight(ki, keywords.size)) }
weightedKeywords.forEach { (value, weight) ->
index.getOrPut(value, {hashMapOf()}).getOrPut(i, {weight})
}
}
val compactIndex = TreeMap<String, List<Int>>()
index.forEach { key, weightedEntryIndices ->
compactIndex.put(key.toLowerCase(), weightedEntryIndices.entries.sortedBy { -it.value }.map{it.key})}
return compactIndex
}
|
mit
|
72fae979fa121856da18737e9e37dce0
| 32.22093 | 112 | 0.60063 | 4.226331 | false | false | false | false |
phase/sbhs
|
src/main/kotlin/io/jadon/sbhs/SBHS.kt
|
1
|
7733
|
package io.jadon.sbhs
import java.awt.Color
import java.awt.Frame
import java.awt.Image
import java.io.File
import java.io.RandomAccessFile
import javax.swing.*
import javax.swing.filechooser.FileNameExtensionFilter
/**
* @author https://github.com/phase
*/
object SBHS {
val VERSION = BuildInfo.VERSION
var gameLocation = ""
var raf: RandomAccessFile = // Start with null file
if (System.getProperty("os.name").toLowerCase().contains("win"))
RandomAccessFile("NUL", "r")
else RandomAccessFile("/dev/null", "r") // If not windows, assume unix.
val WIDTH = 1280
val HEIGHT = 840
var frame: JFrame = JFrame("Sonic Battle Hack Suite $VERSION - By Phase")
lateinit var spriteTabs: JTabbedPane
fun getImage(name: String): Image = ImageIcon(SBHS::class.java.getResource("/$name")
?: File("src/main/resources/$name").toURL()).image
val iconImage = getImage("icon.png")
val splashImage = getImage("splash.png")
@JvmStatic
fun main(args: Array<String>) {
val timer = System.nanoTime()
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
val splash = SplashScreen()
splash.setLocationRelativeTo(null)
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
frame.setSize(WIDTH, HEIGHT)
frame.isResizable = true
frame.setLocationRelativeTo(null) // Center of screen
frame.extendedState = Frame.MAXIMIZED_BOTH // Full screen
frame.iconImage = iconImage
splash.message = "Config"
val config = File("config.txt")
gameLocation = if (config.exists() && config.isFile) config.readText()
else {
val file: File? = getFile("GBA ROM", "gba")
if (file == null) {
System.err.println("File not found!")
System.exit(-1)
}
file.toString()
}
try {
raf = RandomAccessFile(gameLocation, "rw")
} catch (e: Exception) {
e.printStackTrace()
System.exit(-1)
}
val mainTabs = JTabbedPane()
run {
// Palette Editor
val paletteTabs = JTabbedPane()
Character.values().forEach {
splash.message = "${it.name} Palette"
PaletteManager.addPaletteTab(paletteTabs, it.name, it.paletteOffset)
}
PaletteData.values().forEach {
splash.message = "${it.name} Palette"
PaletteManager.addPaletteTab(paletteTabs, it.name, it.paletteOffset)
}
mainTabs.addTab("Palettes", null, paletteTabs, "Palette Editor")
}
run {
val textTabs = JTabbedPane()
Character.values().filter(Character::hasStory).forEach {
splash.message = "Text Editor (${it.name})"
TextManager.addTextTab(textTabs, it.name, it.textOffsets.first, it.textOffsets.second)
}
mainTabs.addTab("Story", null, textTabs, "Story Editor")
}
run {
// Sprite Editor
spriteTabs = JTabbedPane()
// TODO: Add this back in
// SpriteManager.addSpriteTab(spriteTabs, "Ground Shadow", 0x47ABB8, 3)
Character.values().forEach {
if (it == Character.Emerl) return@forEach
splash.message = "${it.name} Sprites"
SpriteManager.addCharacterSpriteTab(spriteTabs, it.name, it.paletteOffset, it.spriteData)
}
val emerl = Character.Emerl
val emerlTabs = JTabbedPane()
var characterByteOffset = 0
Character.values().forEachIndexed { i: Int, char: Character ->
if (char == Character.Emerl || char == Character.Eggman) return@forEachIndexed
splash.message = "Emerl Sprites (${char.name})"
val spriteData = mutableListOf<Pair<Int, Int>>()
var o = 0
char.spriteFrames.forEach {
// offset the palette data before the sprites
val paletteOffset = i * 32
spriteData.add(Pair(emerl.spriteOffset + 0x480 * o + paletteOffset + characterByteOffset, it))
o += it
}
// skip the sprites that have already been drawn
val frames = char.spriteFrames.sum()
characterByteOffset += frames * 0x480
// Add the image to the tabs
val image = SpriteManager.readImage("Emerl", spriteData, true)
emerlTabs.addTab(char.name, null,
SpriteManager.createSpritePanel("Emerl/${char.name}", image, spriteData, emerl.paletteOffset, true),
"Edit Emerl/${char.name} Sprite")
}
spriteTabs.addTab("Emerl", null, emerlTabs, "Emerl")
mainTabs.addTab("Sprites", null, spriteTabs, "Sprite Editor")
}
run {
val effectTabs = JTabbedPane()
PaletteManager.PALETTES["Effects"] = PaletteManager.PALETTES["Sonic"]!!
PaletteManager.PALETTES["Emerl Effects"] = PaletteManager.PALETTES["Sonic"]!!
// o B1800
SpriteManager.addSpritePageTab(effectTabs, "Effects", 0xa8f038, 89, 16, 4)
SpriteManager.addSpritePageTab(effectTabs, "Emerl Effects", 0xa8f038 + 0xB1820, 89, 16, 4)
mainTabs.addTab("Effects", null, effectTabs, "Effect Editor")
}
run {
splash.message = "About Page"
// About Page
val t = JTextPane()
t.text = "Sonic Battle Hack Suite $VERSION was made by Phase.\n" +
"You can find the source at https://github.com/phase/sbhs\n" +
"Current ROM open: $gameLocation\n\n" +
"Build Info:\n" +
"JVM: ${BuildInfo.JVM_INFO}\n" +
"Gradle: ${BuildInfo.GRADLE_INFO}\n"
t.isEditable = false
mainTabs.addTab("About", null, t, "About Page")
}
frame.contentPane.add(mainTabs)
splash.message = "nothing"
splash.isVisible = false
frame.isVisible = true
val time = System.nanoTime() - timer
println("Total time: ${time / 1000000000.0}s")
}
fun findFreeSpace(amount: Int): Int {
var currentOffset = -1
var a = 0
try {
// 00 00 00 01 10 -(read())-> 0 0 0 1 16
for (i in 0xF9EE30..0x1048559) {
raf.seek(i.toLong())
val value = raf.read()
if (value != 0) {
currentOffset = -1
a = 0
continue
}
if (a == amount && currentOffset != -1) return currentOffset
if (currentOffset == -1 && value == 0)
currentOffset = i
else
a++
}
} catch (e: Exception) {
e.printStackTrace()
}
return -1
}
fun getFile(extensionDescription: String, extension: String): File? {
val fc = JFileChooser()
fc.fileFilter = FileNameExtensionFilter(extensionDescription, extension)
return if (fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION)
fc.selectedFile else null
}
fun getColorInput(previousColor: Color): Color {
val c = JColorChooser.showDialog(frame, "Pick Color", previousColor)
return c ?: previousColor
}
fun hex(i: Int): String {
return (if (i < 0x10) "0" else "") + Integer.toHexString(i)
}
}
|
mpl-2.0
|
03defe6fc2784468af02d12bc09b7408
| 37.282178 | 124 | 0.555412 | 4.43406 | false | false | false | false |
owncloud/android
|
owncloudTestUtil/src/main/java/com/owncloud/android/testutil/oauth/ClientRegistrationInfo.kt
|
2
|
1212
|
/**
* ownCloud Android client application
*
* @author Abel García de Prada
* Copyright (C) 2021 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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.owncloud.android.testutil.oauth
import com.owncloud.android.domain.authentication.oauth.model.ClientRegistrationInfo
import com.owncloud.android.testutil.OC_CLIENT_ID
import com.owncloud.android.testutil.OC_CLIENT_SECRET
import com.owncloud.android.testutil.OC_CLIENT_SECRET_EXPIRATION
val OC_CLIENT_REGISTRATION = ClientRegistrationInfo(
clientId = OC_CLIENT_ID,
clientSecret = OC_CLIENT_SECRET,
clientIdIssuedAt = null,
clientSecretExpiration = OC_CLIENT_SECRET_EXPIRATION
)
|
gpl-2.0
|
25e055c2695effee25ccb261def2c915
| 38.064516 | 84 | 0.770438 | 4.119048 | false | true | false | false |
facebook/litho
|
sample/src/main/java/com/facebook/samples/litho/kotlin/errors/KErrorBoundary.kt
|
1
|
1508
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.samples.litho.kotlin.errors
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Style
import com.facebook.litho.core.margin
import com.facebook.litho.dp
import com.facebook.litho.useErrorBoundary
import com.facebook.litho.useState
// start_example
class KErrorBoundary(private val childComponent: Component) : KComponent() {
override fun ComponentScope.render(): Component? {
val errorState = useState<Exception?> { null }
useErrorBoundary { exception: Exception -> errorState.update(exception) }
errorState.value?.let {
return Column(style = Style.margin(all = 16.dp)) {
child(KDebugComponent(message = "KComponent's Error Boundary", throwable = it))
}
}
return childComponent
}
}
// end_example
|
apache-2.0
|
bf2c6e5d413b035bdc2fa0a07e8bb950
| 32.511111 | 87 | 0.747347 | 4.053763 | false | false | false | false |
xfournet/intellij-community
|
platform/script-debugger/backend/src/debugger/CallFrameBase.kt
|
6
|
1418
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.openapi.util.NotNullLazyValue
const val RECEIVER_NAME = "this"
@Deprecated("")
/**
* Use kotlin - base class is not required in this case (no boilerplate code)
*/
/**
* You must initialize [.scopes] or override [.getVariableScopes]
*/
abstract class CallFrameBase(override val functionName: String?, override val line: Int, override val column: Int, override val evaluateContext: EvaluateContext) : CallFrame {
protected var scopes: NotNullLazyValue<List<Scope>>? = null
override var hasOnlyGlobalScope: Boolean = false
protected set(value: Boolean) {
field = value
}
override val variableScopes: List<Scope>
get() = scopes!!.value
override val asyncFunctionName: String? = null
override val isFromAsyncStack: Boolean = false
}
|
apache-2.0
|
26b9d14f7c6b29262f8ae94018a2705c
| 32 | 175 | 0.739069 | 4.283988 | false | false | false | false |
AllanWang/Frost-for-Facebook
|
app/src/main/kotlin/com/pitchedapps/frost/utils/BiometricUtils.kt
|
1
|
4671
|
/*
* Copyright 2019 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.utils
import android.content.Context
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import androidx.biometric.BiometricPrompt
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import ca.allanwang.kau.utils.string
import com.pitchedapps.frost.R
import com.pitchedapps.frost.prefs.Prefs
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlinx.coroutines.CompletableDeferred
typealias BiometricDeferred = CompletableDeferred<BiometricPrompt.CryptoObject?>
/** Container for [BiometricPrompt] Inspired by coroutine's CommonPool */
object BiometricUtils {
private val executor: Executor
get() = pool ?: getOrCreatePoolSync()
@Volatile private var pool: ExecutorService? = null
private var lastUnlockTime = -1L
private const val UNLOCK_TIME_INTERVAL = 15 * 60 * 1000
/**
* Checks if biometric authentication is possible Currently, this means checking for enrolled
* fingerprints
*/
@Suppress("DEPRECATION")
fun isSupported(context: Context): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false
val fingerprintManager =
context.getSystemService(FingerprintManager::class.java) ?: return false
return fingerprintManager.isHardwareDetected && fingerprintManager.hasEnrolledFingerprints()
}
private fun getOrCreatePoolSync(): Executor =
pool ?: Executors.newSingleThreadExecutor().also { pool = it }
private fun shouldPrompt(context: Context, prefs: Prefs): Boolean {
return prefs.biometricsEnabled &&
System.currentTimeMillis() - lastUnlockTime > UNLOCK_TIME_INTERVAL
}
/**
* Generates a prompt dialog and attempt to return an auth object. Note that the underlying
* request will call [androidx.fragment.app.FragmentTransaction.commit], so this cannot happen
* after onSaveInstanceState.
*/
fun authenticate(
activity: FragmentActivity,
prefs: Prefs,
force: Boolean = false
): BiometricDeferred {
val deferred: BiometricDeferred = CompletableDeferred()
if (!force && !shouldPrompt(activity, prefs)) {
deferred.complete(null)
return deferred
}
val info =
BiometricPrompt.PromptInfo.Builder()
.setTitle(activity.string(R.string.biometrics_prompt_title))
.setNegativeButtonText(activity.string(R.string.kau_cancel))
.build()
val prompt = BiometricPrompt(activity, executor, Callback(activity, deferred))
activity.lifecycle.addObserver(
object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
if (!deferred.isCompleted) {
prompt.cancelAuthentication()
deferred.cancel()
activity.finish()
}
activity.lifecycle.removeObserver(this)
}
}
)
prompt.authenticate(info)
return deferred
}
private class Callback(val activity: FragmentActivity, val deferred: BiometricDeferred) :
BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
deferred.cancel()
activity.finish()
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
lastUnlockTime = System.currentTimeMillis()
deferred.complete(result.cryptoObject)
}
override fun onAuthenticationFailed() {
deferred.cancel()
activity.finish()
}
}
/**
* For completeness we provide a shutdown function. In practice, we initialize the executor only
* when it is first used, and keep it alive throughout the app lifecycle, as it will be used an
* arbitrary number of times, with unknown frequency
*/
@Synchronized
fun shutdown() {
pool?.shutdown()
pool = null
}
}
|
gpl-3.0
|
f149ababc7ec9d191f06877dcac1b02b
| 33.6 | 98 | 0.732605 | 4.776074 | false | false | false | false |
chrisbanes/tivi
|
common/ui/view/src/main/java/app/tivi/util/TiviDateFormatter.kt
|
1
|
3004
|
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.util
import android.text.format.DateUtils
import app.tivi.inject.MediumDate
import app.tivi.inject.MediumDateTime
import app.tivi.inject.ShortDate
import app.tivi.inject.ShortTime
import org.threeten.bp.LocalTime
import org.threeten.bp.OffsetDateTime
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.temporal.Temporal
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class TiviDateFormatter @Inject constructor(
@ShortTime private val shortTimeFormatter: DateTimeFormatter,
@ShortDate private val shortDateFormatter: DateTimeFormatter,
@MediumDate private val mediumDateFormatter: DateTimeFormatter,
@MediumDateTime private val mediumDateTimeFormatter: DateTimeFormatter
) {
fun formatShortDate(temporalAmount: Temporal): String = shortDateFormatter.format(temporalAmount)
fun formatMediumDate(temporalAmount: Temporal): String = mediumDateFormatter.format(temporalAmount)
fun formatMediumDateTime(temporalAmount: Temporal): String = mediumDateTimeFormatter.format(temporalAmount)
fun formatShortTime(localTime: LocalTime): String = shortTimeFormatter.format(localTime)
fun formatShortRelativeTime(dateTime: OffsetDateTime): String {
val now = OffsetDateTime.now()
return if (dateTime.isBefore(now)) {
if (dateTime.year == now.year || dateTime.isAfter(now.minusDays(7))) {
// Within the past week
DateUtils.getRelativeTimeSpanString(
dateTime.toInstant().toEpochMilli(),
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_SHOW_DATE
).toString()
} else {
// More than 7 days ago
formatShortDate(dateTime)
}
} else {
if (dateTime.year == now.year || dateTime.isBefore(now.plusDays(14))) {
// In the near future (next 2 weeks)
DateUtils.getRelativeTimeSpanString(
dateTime.toInstant().toEpochMilli(),
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_SHOW_DATE
).toString()
} else {
// In the far future
formatShortDate(dateTime)
}
}
}
}
|
apache-2.0
|
0c968993048087a607a98f8b5c684218
| 38.012987 | 111 | 0.67277 | 4.932677 | false | false | false | false |
vsch/idea-multimarkdown
|
src/main/java/com/vladsch/md/nav/inspections/JekyllFrontMatterFoundNotificationProvider.kt
|
1
|
3734
|
// 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.inspections
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.vladsch.md.nav.MdBundle
import com.vladsch.md.nav.MdFileType
import com.vladsch.md.nav.MdProjectComponent
import com.vladsch.md.nav.psi.element.MdFile
import com.vladsch.md.nav.settings.*
import org.jetbrains.annotations.NotNull
class JekyllFrontMatterFoundNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>(), DumbAware {
override fun getKey(): Key<EditorNotificationPanel> {
return KEY
}
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project:Project): EditorNotificationPanel? {
if (file.fileType !== MdFileType.INSTANCE) {
return null
}
if (MdApplicationSettings.instance.wasShownSettings.jekyllFrontMatter) {
return null
}
if (fileEditor !is TextEditor) {
return null
}
val profileManager = MdRenderingProfileManager.getInstance(project)
val renderingProfile = profileManager.getRenderingProfile(file)
val parserSettings = renderingProfile.parserSettings
if (parserSettings.optionsFlags and ParserOptions.JEKYLL_FRONT_MATTER.flags != 0L || parserSettings.optionsFlags and ParserOptions.FLEXMARK_FRONT_MATTER.flags != 0L) {
return null
}
// see if the file has jekyll front matter
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
val jekyllFrontMatterOffset = MdFile.frontMatterOffset(document.charsSequence, true, false)
if (jekyllFrontMatterOffset <= 0) return null
val panel = EditorNotificationPanel()
panel.setText(MdBundle.message("editor.jekyll-front-matter.is.available"))
panel.createActionLabel(MdBundle.message("editor.jekyll-front-matter.enable")) {
//MarkdownRenderingProfile newProfile = new MarkdownRenderingProfile(renderingProfile);
val newParserSettings = MdParserSettings(
parserSettings.pegdownFlags,
parserSettings.optionsFlags or ParserOptions.JEKYLL_FRONT_MATTER.flags,
parserSettings.gitHubSyntaxChange,
parserSettings.emojiShortcuts,
parserSettings.emojiImages
)
if (renderingProfile.profileName.isEmpty()) {
MdProjectSettings.getInstance(project).parserSettings = newParserSettings
} else {
renderingProfile.parserSettings = newParserSettings
profileManager.replaceProfile(renderingProfile.profileName, renderingProfile)
}
MdProjectComponent.getInstance(project).reparseMarkdown(true)
EditorNotifications.updateAll()
}
panel.createActionLabel(MdBundle.message("editor.javafx.dont.show.again")) {
MdApplicationSettings.instance.wasShownSettings.jekyllFrontMatter = true
EditorNotifications.updateAll()
}
return panel
}
companion object {
private val KEY = Key.create<EditorNotificationPanel>("editor.jekyll-front-matter.is.available")
}
}
|
apache-2.0
|
44863316a67301eb1d4f4efc92af7213
| 42.929412 | 177 | 0.720407 | 5.200557 | false | false | false | false |
google/prefab
|
cli/src/test/kotlin/com/google/prefab/cli/PackageTest.kt
|
1
|
4879
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.prefab.cli
import com.google.prefab.api.Android
import com.google.prefab.api.InvalidDirectoryNameException
import com.google.prefab.api.LibraryReference
import com.google.prefab.api.MissingArtifactIDException
import com.google.prefab.api.MissingPlatformIDException
import com.google.prefab.api.Package
import com.google.prefab.api.PlatformDataInterface
import com.google.prefab.api.SchemaVersion
import com.google.prefab.api.UnsupportedPlatformException
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.nio.file.Paths
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
@RunWith(Parameterized::class)
class PackageTest(override val schemaVersion: SchemaVersion) : PerSchemaTest {
companion object {
@Parameterized.Parameters(name = "schema version = {0}")
@JvmStatic
fun data(): List<SchemaVersion> = SchemaVersion.values().toList()
}
private val android: PlatformDataInterface =
Android(Android.Abi.Arm64, 21, Android.Stl.CxxShared, 21)
@Test
fun `can load basic package`() {
val packagePath = packagePath("foo")
val pkg = Package(packagePath)
assertEquals(packagePath, pkg.path)
assertEquals("foo", pkg.name)
assertEquals(listOf("qux", "quux"), pkg.dependencies)
assertEquals(2, pkg.modules.size)
val (bar, baz) = pkg.modules.sortedBy { it.name }
assertEquals("bar", bar.name)
assertEquals(packagePath.resolve("modules/bar"), bar.path)
assertEquals("libbar", bar.libraryNameForPlatform(android))
assertEquals(
listOf(LibraryReference.Literal("-landroid")),
bar.linkLibsForPlatform(android)
)
assertEquals("baz", baz.name)
assertEquals(packagePath.resolve("modules/baz"), baz.path)
assertEquals("libbaz", baz.libraryNameForPlatform(android))
assertEquals(
listOf(
LibraryReference.Literal("-llog"),
LibraryReference.Local("bar"),
LibraryReference.External("qux", "libqux")
), baz.linkLibsForPlatform(android)
)
}
@Test
fun `can load package with unexpected files`() {
val packagePath = packagePath("has_unexpected_files")
val pkg = Package(packagePath)
assertEquals(packagePath, pkg.path)
assertEquals("has_unexpected_files", pkg.name)
assertEquals(emptyList(), pkg.dependencies)
assertEquals(1, pkg.modules.size)
val bar = pkg.modules.single()
assertEquals("bar", bar.name)
assertEquals(packagePath.resolve("modules/bar"), bar.path)
assertEquals("libbar", bar.libraryNameForPlatform(android))
assertEquals(emptyList(), bar.linkLibsForPlatform(android))
}
@Test
fun `package with unsupported platforms does not load`() {
assertFailsWith(UnsupportedPlatformException::class) {
Package(packagePath("unsupported_platform"))
}
}
@Test
fun `package with invalid directory name does not load`(){
assertFailsWith(InvalidDirectoryNameException::class) {
Package(packagePath("invalid_directory_name"))
}
}
@Test
fun `package with missing platform id does not load`() {
assertFailsWith(MissingPlatformIDException::class) {
Package(packagePath("missing_platform_id"))
}
}
@Test
fun `package with missing artifact id does not load`() {
assertFailsWith(MissingArtifactIDException::class) {
Package(packagePath("missing_artifact_id"))
}
}
@Test
fun `package with unsupported schema version is rejected`() {
assertFailsWith(IllegalArgumentException::class) {
val packagePath =
Paths.get(
this.javaClass.getResource(
"packages/wrong_schema_version"
).toURI()
)
Package(packagePath)
}
}
@Test
fun `package with invalid package version is rejected`() {
assertFailsWith(IllegalArgumentException::class) {
Package(packagePath("bad_package_version"))
}
}
}
|
apache-2.0
|
a3efad4eb436cd3345d5f506d56bf028
| 33.118881 | 78 | 0.666325 | 4.624645 | false | true | false | false |
Fitbit/MvRx
|
mvrx/src/main/kotlin/com/airbnb/mvrx/CoroutinesStateStore.kt
|
1
|
4214
|
package com.airbnb.mvrx
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
import java.util.concurrent.Executors
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
class CoroutinesStateStore<S : MavericksState>(
initialState: S,
private val scope: CoroutineScope,
private val contextOverride: CoroutineContext = EmptyCoroutineContext
) : MavericksStateStore<S> {
private val setStateChannel = Channel<S.() -> S>(capacity = Channel.UNLIMITED)
private val withStateChannel = Channel<(S) -> Unit>(capacity = Channel.UNLIMITED)
private val stateSharedFlow = MutableSharedFlow<S>(
replay = 1,
extraBufferCapacity = SubscriberBufferSize,
onBufferOverflow = BufferOverflow.SUSPEND,
).apply { tryEmit(initialState) }
@Volatile
override var state = initialState
/**
* Returns a [Flow] for this store's state. It will begin by immediately emitting
* the latest set value and then continue with all subsequent updates.
*
* This doesn't need distinctUntilChanged() because the de-dupinng is done once
* for all subscriptions in [flushQueuesOnce].
*
* This flow never completes
*/
override val flow: Flow<S> = stateSharedFlow.asSharedFlow()
init {
setupTriggerFlushQueues(scope)
}
/**
* Poll [withStateChannel] and [setStateChannel] to respond to set/get state requests.
*/
private fun setupTriggerFlushQueues(scope: CoroutineScope) {
if (MavericksTestOverrides.FORCE_SYNCHRONOUS_STATE_STORES) return
scope.launch(flushDispatcher + contextOverride) {
while (isActive) {
flushQueuesOnce()
}
}
}
/**
* Flush the setState and withState queues.
* All pending setState reducers will be run prior to every single withState lambda.
* This ensures that situations such as the following will work correctly:
*
* Situation 1
*
* setState { ... }
* withState { ... }
*
* Situation 2
*
* withState {
* setState { ... }
* withState { ... }
* }
*/
private suspend fun flushQueuesOnce() {
select<Unit> {
setStateChannel.onReceive { reducer ->
val newState = state.reducer()
if (newState != state) {
state = newState
stateSharedFlow.emit(newState)
}
}
withStateChannel.onReceive { block ->
block(state)
}
}
}
private fun flushQueuesOnceBlocking() {
if (scope.isActive) {
runBlocking { flushQueuesOnce() }
}
}
override fun get(block: (S) -> Unit) {
withStateChannel.offer(block)
if (MavericksTestOverrides.FORCE_SYNCHRONOUS_STATE_STORES) {
flushQueuesOnceBlocking()
}
}
override fun set(stateReducer: S.() -> S) {
setStateChannel.offer(stateReducer)
if (MavericksTestOverrides.FORCE_SYNCHRONOUS_STATE_STORES) {
flushQueuesOnceBlocking()
}
}
companion object {
private val flushDispatcher = Executors.newCachedThreadPool().asCoroutineDispatcher()
/**
* The buffer size that will be allocated by [MutableSharedFlow].
* If it falls behind by more than 64 state updates, it will start suspending.
* Slow consumers should consider using `stateFlow.buffer(onBufferOverflow = BufferOverflow.DROP_OLDEST)`.
*
* The internally allocated buffer is replay + extraBufferCapacity but always allocates 2^n space.
* We use replay=1 so buffer = 64-1.
*/
internal const val SubscriberBufferSize = 63
}
}
|
apache-2.0
|
d8190ed25b2a09794fa2dc6a4761d63a
| 31.666667 | 114 | 0.653061 | 4.911422 | false | false | false | false |
bornest/KotlinUtils
|
rx2/src/androidTest/java/com/github/kotlinutils/rx2/RxMutExOperationTypesCallerITest.kt
|
1
|
7812
|
//package com.github.kotlinutils.rx2
//
//import android.os.HandlerThread
//import android.support.test.runner.AndroidJUnit4
//import com.github.kotlinutils.random.extensions.randomBoolean
//import com.github.kotlinutils.random.extensions.sleepRandomTime
//import com.github.kotlinutils.concurrent.android.extensions.tryToQuitSafely
//import com.github.kotlinutils.concurrent.java.extensions.curThreadNameInBr
//import com.github.kotlinutils.rx2.RxMutExOperationTypesCaller
//import com.github.kotlinutils.rx2.extensions.scheduler
//import com.github.unitimber.core.extensions.v
//import com.github.unitimber.core.loggable.Loggable
//import com.github.unitimber.core.loggable.extensions.d
//import io.reactivex.Observable
//import io.reactivex.Scheduler
//import io.reactivex.Single
//import org.junit.Test
//import org.junit.runner.RunWith
//import java.util.concurrent.CountDownLatch
//import java.util.concurrent.TimeUnit
//
///**
// * Created by nbv54 on 20-Apr-17.
// */
//@RunWith(AndroidJUnit4::class)
//class RxMutExOperationTypesCallerITest : Loggable {
// override var loggingEnabled = true
// override val logTag = "OpCallerITest"
//
// @Test
// fun simpleHandlerThreadCall() {
// val handlerThread = HandlerThread("testHandlerThread").also { it.start() }
// val testObj = TestClassRegular("handlerThreadOpCaller", 20, TimeUnit.SECONDS)
// val latch = CountDownLatch(4)
//
// val aOneD = testObj.aOne(handlerThread.scheduler)
// .take(3)
// .doOnNext {
// d { "$curThreadNameInBr Observable Received: $it" }
// latch.countDown()
// }
// .doFinally {
// latch.countDown()
// }
// .test()
//
// assert(latch.await(10, TimeUnit.SECONDS))
// aOneD.dispose()
// handlerThread.tryToQuitSafely()
// }
//
// //region inner Test Classes
// abstract class AbstractTestClass(opCallerName: String, keepAliveTime: Long, timeUnit: TimeUnit) {
// val opCaller = RxMutExOperationTypesCaller(opCallerName, keepAliveTime, timeUnit)
//
// abstract protected fun waitShort()
// abstract protected fun waitLong()
//
// fun aOne(scheduler: Scheduler): Observable<String> {
// val opName = "aOne"
// val disposed = VarWithLock(false)
// return opCaller.callObservable(TestOperationType.A, opName,
// Observable.create<String> {
// emitter ->
// v{"$curThreadNameInBr $opName: performing initial setup"}
// waitShort() //imitate initial setup
//
// v{"$curThreadNameInBr $opName: sending initial value: 0"}
// emitter.onNext("$opName: 0 (initial value)") //send initial value
//
// var i = 0
// while ( !(disposed{v}) )
// {
// waitLong() //imitate work/delay
//// v{"$curThreadNameInBr $opName: sending next value: $i"}
// emitter.onNext("$curThreadNameInBr $opName: $i") //send next value
// i++
// }
// }
// .doFinally {
// disposed {
// v = true
// }
// }
// .subscribeOn(scheduler)
// )
//
// }
//
// fun aTwo(scheduler: Scheduler): Single<String> {
// val opName = "aTwo"
// return opCaller.callSingle(TestOperationType.A, opName,
// Single.create<String> {
// emitter ->
// v{"$curThreadNameInBr $opName: doing work"}
//
// waitLong() //imitate work/delay
// if (randomBoolean(0.9)){
// v{"$curThreadNameInBr $opName: sending onSuccess"}
// emitter.onSuccess("$opName: ")
// } else {
// v{"$curThreadNameInBr $opName: sending onError"}
// emitter.onError(Throwable("$opName: "))
// }
// }
// .subscribeOn(scheduler)
// )
// }
//
// fun bOne(scheduler: Scheduler): Observable<String> {
// val opName = "bOne"
// val disposed = VarWithLock(false)
// return opCaller.callObservable(TestOperationType.B, opName,
// Observable.create<String> {
// emitter ->
// v{"$curThreadNameInBr $opName: performing initial setup"}
// waitShort() //imitate initial setup
//
// v{"$curThreadNameInBr $opName: sending initial value: 0"}
// emitter.onNext("$opName: 0 (initial value)") //send initial value
//
// var i = 0
// while ( !(disposed{v}) )
// {
// waitLong() //imitate work/delay
//// v{"$curThreadNameInBr $opName: sending next value: $i"}
// emitter.onNext("$curThreadNameInBr $opName: $i") //send next value
// i++
// }
// }
// .doFinally {
// disposed {
// v = true
// }
// }
// .subscribeOn(scheduler)
// )
// }
//
// fun bTwo(scheduler: Scheduler): Single<String> {
// val opName = "bTwo"
// return opCaller.callSingle(TestOperationType.B, opName,
// Single.create<String> {
// emitter ->
// v{"$curThreadNameInBr $opName: doing work"}
// waitLong() //imitate work/delay
// if (randomBoolean(0.9)){
// v{"$curThreadNameInBr $opName: sending onSuccess"}
// emitter.onSuccess("$opName: ")
// } else {
// v{"$curThreadNameInBr $opName: sending onError"}
// emitter.onError(Throwable("$opName: "))
// }
// }
// .subscribeOn(scheduler)
// )
// }
// }
//
// class TestClassRandom(opCallerName: String, keepAliveTime: Long, timeUnit: TimeUnit) : AbstractTestClass(opCallerName, keepAliveTime, timeUnit){
// override fun waitShort() {
// sleepRandomTime(10, 300)
// }
//
// override fun waitLong() {
// sleepRandomTime(10, 1000)
// }
// }
//
// class TestClassRegular(opCallerName: String, keepAliveTime: Long, timeUnit: TimeUnit) : AbstractTestClass(opCallerName, keepAliveTime, timeUnit){
// override fun waitShort() {
// Thread.sleep(150)
// }
//
// override fun waitLong() {
// Thread.sleep(500)
// }
// }
//
// class TestOperationType(name: String) : RxMutExOperationTypesCaller.OperationType(name)
// {
// companion object {
// val A = TestOperationType("A")
// val B = TestOperationType("B")
// }
// }
// //endregion
//}
|
apache-2.0
|
50bfb6c02d22d40234ed261a4af4e917
| 40.558511 | 155 | 0.483871 | 4.458904 | false | true | false | false |
jcgay/gradle-notifier
|
src/main/kotlin/fr/jcgay/gradle/notifier/extension/AnyBar.kt
|
1
|
421
|
package fr.jcgay.gradle.notifier.extension
import java.util.Properties
class AnyBar: NotifierConfiguration {
var host: String? = null
var port: Int? = null
override fun asProperties(): Properties {
val prefix = "notifier.anybar"
val result = Properties()
host?.let { result["${prefix}.host"] = it }
port?.let { result["${prefix}.port"] = it }
return result
}
}
|
mit
|
5ada699c3d4e494305e772c55f6b887a
| 23.764706 | 51 | 0.619952 | 4.087379 | false | true | false | false |
nithia/xkotlin
|
exercises/roman-numerals/src/example/kotlin/RomanNumeral.kt
|
1
|
767
|
object RomanNumeral {
private val numeralValues = listOf(
Pair(1000, "M"),
Pair(900, "CM"),
Pair(500, "D"),
Pair(400, "CD"),
Pair(100, "C"),
Pair(90, "XC"),
Pair(50, "L"),
Pair(40, "XL"),
Pair(10, "X"),
Pair(9, "IX"),
Pair(5, "V"),
Pair(4, "IV"),
Pair(1, "I")
)
private tailrec fun fromNumber(n: Int, numerals: String): String {
val numeralPair = numeralValues.find { it.first <= n }
if (numeralPair != null) {
return fromNumber(n - numeralPair.first, numerals + numeralPair.second)
}
return numerals
}
fun value(n: Int) = fromNumber(n, "")
}
|
mit
|
f0f908b13e5ff94fbaba83633fa6dc3e
| 25.448276 | 83 | 0.453716 | 3.470588 | false | false | false | false |
matkoniecz/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/quests/bus_stop_lit/AddBusStopLit.kt
|
1
|
2343
|
package de.westnordost.streetcomplete.quests.bus_stop_lit
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.quest.DayNightCycle.ONLY_NIGHT
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN
import de.westnordost.streetcomplete.ktx.arrayOfNotNull
import de.westnordost.streetcomplete.ktx.containsAnyKey
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddBusStopLit : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
nodes with
(
(public_transport = platform and ~bus|trolleybus|tram ~ yes)
or
(highway = bus_stop and public_transport != stop_position)
)
and physically_present != no and naptan:BusStopType != HAR
and (
!lit
or lit = no and lit older today -8 years
or lit older today -16 years
)
"""
override val commitMessage = "Add whether a bus stop is lit"
override val wikiLink = "Key:lit"
override val icon = R.drawable.ic_quest_bus_stop_lit
override val dayNightVisibility = ONLY_NIGHT
override val questTypeAchievements = listOf(PEDESTRIAN)
override fun getTitle(tags: Map<String, String>): Int {
val hasName = tags.containsAnyKey("name", "ref")
val isTram = tags["tram"] == "yes"
return when {
isTram && hasName -> R.string.quest_busStopLit_tram_name_title
isTram -> R.string.quest_busStopLit_tram_title
hasName -> R.string.quest_busStopLit_name_title
else -> R.string.quest_busStopLit_title
}
}
override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> =
arrayOfNotNull(tags["name"] ?: tags["ref"])
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.updateWithCheckDate("lit", answer.toYesNo())
}
}
|
gpl-3.0
|
09cde885a53c6ead026fa98f4754a1c0
| 40.105263 | 101 | 0.694836 | 4.412429 | false | false | false | false |
tomatrocho/insapp-android
|
app/src/main/java/fr/insapp/insapp/components/CommentEditText.kt
|
2
|
1631
|
package fr.insapp.insapp.components
import android.content.Context
import android.util.AttributeSet
import android.widget.AdapterView
import android.widget.TextView
import androidx.appcompat.widget.AppCompatMultiAutoCompleteTextView
import fr.insapp.insapp.R
import fr.insapp.insapp.adapters.AutoCompleterAdapter
import fr.insapp.insapp.models.Tag
import fr.insapp.insapp.utility.TagTokenizer
import java.util.*
/**
* Created by thomas on 27/02/2017.
* Kotlin rewrite on 03/09/2019.
*/
class CommentEditText : AppCompatMultiAutoCompleteTextView {
private lateinit var adapter: AutoCompleterAdapter
val tags = ArrayList<Tag>()
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
fun setupComponent() {
threshold = 1
setTokenizer(TagTokenizer())
this.adapter = AutoCompleterAdapter(context, R.id.comment_event_input)
setAdapter<AutoCompleterAdapter>(adapter)
onItemClickListener = AdapterView.OnItemClickListener { _, view, _, _ ->
val itemString = (view.findViewById<TextView>(R.id.dropdown_textview)).text.toString()
var userId = ""
for ((id, _, username1) in adapter.filteredUsers) {
val username = "@$username1"
if (username == itemString) {
userId = id
break
}
}
tags.add(Tag(null, userId, itemString))
}
}
}
|
mit
|
fb422588febc9726b938c0271bb85b2d
| 29.203704 | 111 | 0.675046 | 4.543175 | false | false | false | false |
rainmatic/data-structures-and-algorithms-in-kotlin
|
SelectionSort.kt
|
1
|
1029
|
class SelectionSort {
data class Result(val smallestItem: Int, val smallestIndex: Int)
private fun getSmallestInList (inputList: MutableList<Int>): Result {
var smallestItem = inputList[0]
var smallestIndex = 0
for((index, element) in inputList.withIndex()) {
if (element < smallestItem) {
smallestItem = element
smallestIndex = index
}
}
return Result(smallestItem, smallestIndex)
}
fun doSelectionSort () {
println("Please, enter some integer numbers using spacebar")
val inputList = readLine()!!.split(' ').map(String::toInt)
val listToSort = inputList.toMutableList()
val listSorted = mutableListOf<Int>()
for(item in inputList) {
val (smallestItem, smallestIndex) = getSmallestInList(listToSort)
listSorted.add(smallestItem)
listToSort.removeAt(smallestIndex)
}
println("Sorted list is $listSorted")
}
}
|
mit
|
16dcf641f4331b0c49738008818a7a83
| 25.410256 | 77 | 0.608358 | 4.853774 | false | false | false | false |
KotlinKit/Reactant
|
Core/src/main/kotlin/org/brightify/reactant/core/component/ComponentBase.kt
|
1
|
774
|
package org.brightify.reactant.core.component
import io.reactivex.Observable
/**
* @author <a href="mailto:[email protected]">Filip Dolnik</a>
*/
open class ComponentBase<STATE, ACTION>(initialState: STATE): ComponentWithDelegate<STATE, ACTION> {
override val componentDelegate = ComponentDelegate<STATE, ACTION>(initialState)
override val actions: List<Observable<ACTION>> = emptyList()
open val initialCanUpdate: Boolean = true
fun init() {
componentDelegate.ownerComponent = this
resetActions()
afterInit()
componentDelegate.canUpdate = initialCanUpdate
}
open fun afterInit() {
}
override fun needsUpdate(): Boolean = true
override fun update(previousComponentState: STATE?) {
}
}
|
mit
|
7779230562735342bfb3b1890b9df7a7
| 22.454545 | 100 | 0.700258 | 4.473988 | false | false | false | false |
hellenxu/AndroidAdvanced
|
AndroidAdvanced/app/src/main/java/six/ca/androidadvanced/network/NetworkStateMonitor.kt
|
1
|
2316
|
package six.ca.androidadvanced.network
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
/**
* @author hellenxu
* @date 2020-07-15
* Copyright 2020 Six. All rights reserved.
*/
@ExperimentalCoroutinesApi
class NetworkStateMonitor private constructor(context: Context) {
private val connectivityManager: ConnectivityManager by lazy {
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
}
fun subscribeNetworkState(): Flow<NetworkState> = callbackFlow {
val netReqBuilder = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
val connectCallback = object : ConnectivityManager.NetworkCallback(){
override fun onAvailable(network: Network?) {
println("xxl-available")
offer(NetworkState.Connected)
}
override fun onLost(network: Network?) {
println("xxl-lost")
offer(NetworkState.Disconnected)
}
}
connectivityManager.registerNetworkCallback(netReqBuilder.build(), connectCallback)
println("xxl-register-network-callback")
awaitClose {
println("xxl-close-flow-unregister")
connectivityManager.unregisterNetworkCallback(connectCallback)
}
}
fun isConnected(): Boolean {
val netInfo = connectivityManager.activeNetworkInfo
return netInfo != null && netInfo.isConnected
}
interface CloseChannelCallback {
fun onClose()
}
companion object {
private lateinit var instance: NetworkStateMonitor
val INSTANCE: NetworkStateMonitor
get() = instance
fun initialize(ctx: Context) {
instance = NetworkStateMonitor(ctx)
}
}
}
sealed class NetworkState {
object Connected: NetworkState()
object Disconnected: NetworkState()
}
|
apache-2.0
|
5716fa0c69d445efbce99e98ce08ed7d
| 29.486842 | 91 | 0.689551 | 5.527446 | false | false | false | false |
SimonVT/cathode
|
cathode-sync/src/main/java/net/simonvt/cathode/actions/user/SyncShowsWatchlist.kt
|
1
|
3164
|
/*
* Copyright (C) 2013 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.actions.user
import android.content.Context
import androidx.work.WorkManager
import net.simonvt.cathode.actions.CallAction
import net.simonvt.cathode.actions.user.SyncShowsWatchlist.Params
import net.simonvt.cathode.api.entity.WatchlistItem
import net.simonvt.cathode.api.service.SyncService
import net.simonvt.cathode.common.database.forEach
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.provider.DatabaseContract.ShowColumns
import net.simonvt.cathode.provider.DatabaseSchematic
import net.simonvt.cathode.provider.ProviderSchematic.Shows
import net.simonvt.cathode.provider.helper.ShowDatabaseHelper
import net.simonvt.cathode.provider.query
import net.simonvt.cathode.settings.TraktTimestamps
import net.simonvt.cathode.work.enqueueUniqueNow
import net.simonvt.cathode.work.shows.SyncPendingShowsWorker
import retrofit2.Call
import javax.inject.Inject
class SyncShowsWatchlist @Inject constructor(
private val context: Context,
private val showHelper: ShowDatabaseHelper,
private val syncService: SyncService,
private val workManager: WorkManager
) : CallAction<Params, List<WatchlistItem>>() {
override fun key(params: Params): String = "SyncShowsWatchlist"
override fun getCall(params: Params): Call<List<WatchlistItem>> = syncService.getShowWatchlist()
override suspend fun handleResponse(params: Params, response: List<WatchlistItem>) {
val showIds = mutableListOf<Long>()
val localWatchlist = context.contentResolver.query(
Shows.SHOWS,
arrayOf(DatabaseSchematic.Tables.SHOWS + "." + ShowColumns.ID),
ShowColumns.IN_WATCHLIST
)
localWatchlist.forEach { cursor -> showIds.add(cursor.getLong(ShowColumns.ID)) }
localWatchlist.close()
for (watchlistItem in response) {
val listedAt = watchlistItem.listed_at.timeInMillis
val traktId = watchlistItem.show!!.ids.trakt!!
val showResult = showHelper.getIdOrCreate(traktId)
val showId = showResult.showId
if (!showIds.remove(showId)) {
showHelper.setIsInWatchlist(showId, true, listedAt)
}
}
for (showId in showIds) {
showHelper.setIsInWatchlist(showId, false)
}
workManager.enqueueUniqueNow(SyncPendingShowsWorker.TAG, SyncPendingShowsWorker::class.java)
if (params.userActivityTime > 0L) {
TraktTimestamps.getSettings(context)
.edit()
.putLong(TraktTimestamps.SHOW_WATCHLIST, params.userActivityTime)
.apply()
}
}
data class Params(val userActivityTime: Long = 0L)
}
|
apache-2.0
|
a6737059125962c88ce7d58ed79b354e
| 36.223529 | 98 | 0.764855 | 4.258412 | false | false | false | false |
lightem90/Sismic
|
app/src/main/java/com/polito/sismic/Presenters/CustomLayout/DangerLayout.kt
|
1
|
2695
|
package com.polito.sismic.Presenters.CustomLayout
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.widget.LinearLayout
import com.polito.sismic.R
/**
* Created by Matteo on 31/07/2017.
*/
enum class DangerState(val color: Int) {
High(R.color.report_danger_high),
Medium(R.color.report_danger_medium),
Normal(R.color.report_danger_normal),
Low(R.color.report_danger_low),
Default(-1)
}
//To add border color according to danger
class DangerLayout : LinearLayout {
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0)
: super(context, attrs, defStyleAttr)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
constructor(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int)
: super(context, attrs, defStyleAttr, defStyleRes)
private var mDangerState: DangerState = DangerState.Default
private val STATE_REPORT_DANGER_HIGH = intArrayOf(R.attr.state_report_danger_high)
private val STATE_REPORT_DANGER_MEDIUM = intArrayOf(R.attr.state_report_danger_medium)
private val STATE_REPORT_DANGER_NORMAL = intArrayOf(R.attr.state_report_danger_normal)
private val STATE_REPORT_DANGER_LOW = intArrayOf(R.attr.state_report_danger_low)
fun SetDangerState(state: DangerState) {
mDangerState = state
refreshDrawableState()
}
override fun onCreateDrawableState(extraSpace: Int): IntArray {
//In the case its loaded too soon dont remove the null checks!
if (mDangerState == null) return super.onCreateDrawableState(extraSpace)
mDangerState?.let {
val drawableState = super.onCreateDrawableState(extraSpace + 1)
return when (it) {
DangerState.High -> pushState(drawableState, STATE_REPORT_DANGER_HIGH, extraSpace)
DangerState.Medium -> pushState(drawableState, STATE_REPORT_DANGER_MEDIUM, extraSpace)
DangerState.Normal -> pushState(drawableState, STATE_REPORT_DANGER_NORMAL, extraSpace)
DangerState.Low -> pushState(drawableState, STATE_REPORT_DANGER_LOW, extraSpace)
DangerState.Default -> super.onCreateDrawableState(extraSpace)
}
}
}
private fun pushState(drawableState: IntArray, stateToPush: IntArray?, extraSpace: Int): IntArray {
if (stateToPush == null) super.onCreateDrawableState(extraSpace)
mergeDrawableStates(drawableState, stateToPush)
return drawableState
}
}
|
mit
|
644874a4e81372357f50c3c943d3a285
| 34.473684 | 103 | 0.687199 | 4.197819 | false | false | false | false |
FHannes/intellij-community
|
platform/diff-impl/tests/com/intellij/diff/DiffTestCase.kt
|
10
|
8315
|
/*
* Copyright 2000-2016 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.diff.comparison.ComparisonManagerImpl
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.util.ThreeSide
import com.intellij.openapi.editor.Document
import com.intellij.openapi.progress.DumbProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.LocalFilePath
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.containers.HashMap
import com.intellij.util.text.CharSequenceSubSequence
import junit.framework.ComparisonFailure
import junit.framework.TestCase
import java.util.*
import java.util.concurrent.atomic.AtomicLong
abstract class DiffTestCase : TestCase() {
companion object {
private val DEFAULT_CHAR_COUNT = 12
private val DEFAULT_CHAR_TABLE: Map<Int, Char> = {
val map = HashMap<Int, Char>()
listOf('\n', '\n', '\t', ' ', ' ', '.', '<', '!').forEachIndexed { i, c -> map.put(i, c) }
map
}()
}
val RNG: Random = Random()
private var gotSeedException = false
val INDICATOR: ProgressIndicator = DumbProgressIndicator.INSTANCE
val MANAGER: ComparisonManagerImpl = ComparisonManagerImpl()
override fun setUp() {
super.setUp()
DiffIterableUtil.setVerifyEnabled(true)
}
override fun tearDown() {
DiffIterableUtil.setVerifyEnabled(Registry.`is`("diff.verify.iterable"))
super.tearDown()
}
fun getTestName() = UsefulTestCase.getTestName(name, true)
//
// Assertions
//
fun assertTrue(actual: Boolean, message: String = "") {
assertTrue(message, actual)
}
fun assertFalse(actual: Boolean, message: String = "") {
assertFalse(message, actual)
}
fun assertEquals(expected: Any?, actual: Any?, message: String = "") {
assertEquals(message, expected, actual)
}
fun assertEquals(expected: CharSequence?, actual: CharSequence?, message: String = "") {
if (!StringUtil.equals(expected, actual)) throw ComparisonFailure(message, expected?.toString(), actual?.toString())
}
fun assertOrderedEquals(expected: Collection<*>, actual: Collection<*>, message: String = "") {
UsefulTestCase.assertOrderedEquals(message, actual, expected)
}
fun assertEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) {
if (skipLastNewline && !ignoreSpaces) {
assertTrue(StringUtil.equals(chunk1, chunk2) ||
StringUtil.equals(stripNewline(chunk1), chunk2) ||
StringUtil.equals(chunk1, stripNewline(chunk2)))
}
else {
assertTrue(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces))
}
}
fun assertNotEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) {
if (skipLastNewline && !ignoreSpaces) {
assertTrue(!StringUtil.equals(chunk1, chunk2) ||
!StringUtil.equals(stripNewline(chunk1), chunk2) ||
!StringUtil.equals(chunk1, stripNewline(chunk2)))
}
else {
assertFalse(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces))
}
}
fun isEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean): Boolean {
if (ignoreSpaces) {
return StringUtil.equalsIgnoreWhitespaces(chunk1, chunk2)
}
else {
return StringUtil.equals(chunk1, chunk2)
}
}
fun assertSetsEquals(expected: BitSet, actual: BitSet, message: String = "") {
val sb = StringBuilder(message)
sb.append(": \"")
for (i in 0..actual.length()) {
sb.append(if (actual[i]) '-' else ' ')
}
sb.append('"')
val fullMessage = sb.toString()
assertEquals(expected, actual, fullMessage)
}
//
// Parsing
//
fun textToReadableFormat(text: CharSequence?): String {
if (text == null) return "null"
return "'" + text.toString().replace('\n', '*').replace('\t', '+') + "'"
}
fun parseSource(string: CharSequence): String = string.toString().replace('_', '\n')
fun parseMatching(matching: String): BitSet {
val set = BitSet()
matching.filterNot { it == '.' }.forEachIndexed { i, c -> if (c != ' ') set.set(i) }
return set
}
//
// Misc
//
fun getLineCount(document: Document): Int {
return Math.max(1, document.lineCount)
}
fun createFilePath(path: String) = LocalFilePath(path, path.endsWith('/') || path.endsWith('\\'))
//
// AutoTests
//
fun doAutoTest(seed: Long, runs: Int, test: (DebugData) -> Unit) {
RNG.setSeed(seed)
var lastSeed: Long = -1
val debugData = DebugData()
for (i in 1..runs) {
if (i % 1000 == 0) println(i)
try {
lastSeed = getCurrentSeed()
test(debugData)
debugData.reset()
}
catch (e: Throwable) {
println("Seed: " + seed)
println("Runs: " + runs)
println("I: " + i)
println("Current seed: " + lastSeed)
debugData.dump()
throw e
}
}
}
fun generateText(maxLength: Int, charCount: Int, predefinedChars: Map<Int, Char>): String {
val length = RNG.nextInt(maxLength + 1)
val builder = StringBuilder(length)
for (i in 1..length) {
val rnd = RNG.nextInt(charCount)
val char = predefinedChars[rnd] ?: (rnd + 97).toChar()
builder.append(char)
}
return builder.toString()
}
fun generateText(maxLength: Int): String {
return generateText(maxLength, DEFAULT_CHAR_COUNT, DEFAULT_CHAR_TABLE)
}
fun getCurrentSeed(): Long {
if (gotSeedException) return -1
try {
val seedField = RNG.javaClass.getDeclaredField("seed")
seedField.isAccessible = true
val seedFieldValue = seedField.get(RNG) as AtomicLong
return seedFieldValue.get() xor 0x5DEECE66DL
}
catch (e: Exception) {
gotSeedException = true
System.err.println("Can't get random seed: " + e.message)
return -1
}
}
private fun stripNewline(text: CharSequence): CharSequence? {
return when (StringUtil.endsWithChar(text, '\n')) {
true -> CharSequenceSubSequence(text, 0, text.length - 1)
false -> null
}
}
class DebugData {
private val data: MutableList<Pair<String, Any>> = ArrayList()
fun put(key: String, value: Any) {
data.add(Pair(key, value))
}
fun reset() {
data.clear()
}
fun dump() {
data.forEach { println(it.first + ": " + it.second) }
}
}
//
// Helpers
//
open class Trio<out T>(val data1: T, val data2: T, val data3: T) {
companion object {
fun <V> from(f: (ThreeSide) -> V): Trio<V> = Trio(f(ThreeSide.LEFT), f(ThreeSide.BASE), f(ThreeSide.RIGHT))
}
fun <V> map(f: (T) -> V): Trio<V> = Trio(f(data1), f(data2), f(data3))
fun <V> map(f: (T, ThreeSide) -> V): Trio<V> = Trio(f(data1, ThreeSide.LEFT), f(data2, ThreeSide.BASE), f(data3, ThreeSide.RIGHT))
fun forEach(f: (T, ThreeSide) -> Unit): Unit {
f(data1, ThreeSide.LEFT)
f(data2, ThreeSide.BASE)
f(data3, ThreeSide.RIGHT)
}
operator fun invoke(side: ThreeSide): T = side.select(data1, data2, data3) as T
override fun toString(): String {
return "($data1, $data2, $data3)"
}
override fun equals(other: Any?): Boolean {
return other is Trio<*> && other.data1 == data1 && other.data2 == data2 && other.data3 == data3
}
override fun hashCode(): Int {
var h = 0
if (data1 != null) h = h * 31 + data1.hashCode()
if (data2 != null) h = h * 31 + data2.hashCode()
if (data3 != null) h = h * 31 + data3.hashCode()
return h
}
}
}
|
apache-2.0
|
82c623c388f6468e1b717c246491028c
| 28.806452 | 134 | 0.653037 | 3.98228 | false | false | false | false |
NextFaze/dev-fun
|
devfun-annotations/src/main/java/com/nextfaze/devfun/category/ContextCategory.kt
|
1
|
635
|
package com.nextfaze.devfun.category
import com.nextfaze.devfun.DeveloperAnnotation
const val CONTEXT_CAT_NAME = "Context"
const val CONTEXT_CAT_ORDER = -10_000
/**
* [DeveloperCategory] annotation used to declare the "Context" category.
*
* By default functions declared within some sort of Android "scope" (Activity/Fragment/View/etc) will have this category.
*/
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
@DeveloperAnnotation(developerCategory = true)
annotation class ContextCategory(
val value: String = CONTEXT_CAT_NAME,
val group: String = "",
val order: Int = CONTEXT_CAT_ORDER
)
|
apache-2.0
|
2434793c0ed2655fd82bbdaffc7dafe9
| 30.75 | 122 | 0.76378 | 3.96875 | false | false | false | false |
d3xter/bo-android
|
app/src/main/java/org/blitzortung/android/app/AppService.kt
|
1
|
10553
|
/*
Copyright 2015 Andreas Würl
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.blitzortung.android.app
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import android.util.Log
import org.blitzortung.android.alert.event.AlertEvent
import org.blitzortung.android.alert.handler.AlertHandler
import org.blitzortung.android.app.view.PreferenceKey
import org.blitzortung.android.app.view.get
import org.blitzortung.android.data.DataChannel
import org.blitzortung.android.data.DataHandler
import org.blitzortung.android.data.Parameters
import org.blitzortung.android.data.provider.result.ClearDataEvent
import org.blitzortung.android.data.provider.result.DataEvent
import org.blitzortung.android.data.provider.result.ResultEvent
import org.blitzortung.android.data.provider.result.StatusEvent
import org.blitzortung.android.location.LocationHandler
import org.blitzortung.android.util.Period
import java.util.*
class AppService protected constructor(private val handler: Handler, private val updatePeriod: Period) : Service(), Runnable, SharedPreferences.OnSharedPreferenceChangeListener {
private val binder = DataServiceBinder()
var period: Int = 0
private set
var backgroundPeriod: Int = 0
private set
private var lastParameters: Parameters? = null
private var updateParticipants: Boolean = false
var isEnabled: Boolean = false
private set
private val dataHandler: DataHandler = BOApplication.dataHandler
private val locationHandler: LocationHandler = BOApplication.locationHandler
private val alertHandler: AlertHandler = BOApplication.alertHandler
private val preferences = BOApplication.sharedPreferences
private var alertEnabled: Boolean = false
private var alarmManager: AlarmManager? = null
private var pendingIntent: PendingIntent? = null
private val wakeLock = BOApplication.wakeLock
private val dataEventConsumer = { event: DataEvent ->
if (event is ClearDataEvent) {
restart()
} else if (event is ResultEvent) {
lastParameters = event.parameters
configureServiceMode()
}
releaseWakeLock()
}
@SuppressWarnings("UnusedDeclaration")
constructor() : this(Handler(), Period()) {
Log.d(Main.LOG_TAG, "AppService() created with new handler")
}
init {
Log.d(Main.LOG_TAG, "AppService() create")
AppService.instance = this
}
fun reloadData() {
if (isEnabled) {
restart()
} else {
dataHandler.updateData(setOf(DataChannel.STRIKES))
}
}
override fun onCreate() {
Log.i(Main.LOG_TAG, "AppService.onCreate()")
super.onCreate()
preferences.registerOnSharedPreferenceChangeListener(this)
dataHandler.requestUpdates(dataEventConsumer)
onSharedPreferenceChanged(preferences, PreferenceKey.QUERY_PERIOD)
onSharedPreferenceChanged(preferences, PreferenceKey.ALERT_ENABLED)
onSharedPreferenceChanged(preferences, PreferenceKey.BACKGROUND_QUERY_PERIOD)
onSharedPreferenceChanged(preferences, PreferenceKey.SHOW_PARTICIPANTS)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.i(Main.LOG_TAG, "AppService.onStartCommand() startId: $startId $intent")
if (intent != null && RETRIEVE_DATA_ACTION == intent.action) {
acquireWakeLock()
Log.v(Main.LOG_TAG, "AppService.onStartCommand() acquired wake lock " + wakeLock)
isEnabled = false
handler.removeCallbacks(this)
handler.post(this)
}
return Service.START_STICKY
}
private fun acquireWakeLock() {
wakeLock.acquire()
}
fun releaseWakeLock() {
if (wakeLock.isHeld) {
try {
wakeLock.release()
Log.v(Main.LOG_TAG, "AppService.releaseWakeLock() " + wakeLock)
} catch (e: RuntimeException) {
Log.v(Main.LOG_TAG, "AppService.releaseWakeLock() failed", e)
}
}
}
override fun onBind(intent: Intent): IBinder? {
Log.i(Main.LOG_TAG, "AppService.onBind() " + intent)
return binder
}
override fun run() {
if (dataHandler.hasConsumers) {
if (alertEnabled && backgroundPeriod > 0) {
Log.v(Main.LOG_TAG, "AppService.run() in background")
dataHandler.updateDatainBackground()
} else {
isEnabled = false
handler.removeCallbacks(this)
}
} else {
releaseWakeLock()
val currentTime = Period.currentTime
val updateTargets = HashSet<DataChannel>()
if (updatePeriod.shouldUpdate(currentTime, period)) {
updateTargets.add(DataChannel.STRIKES)
if (updateParticipants && updatePeriod.isNthUpdate(10)) {
updateTargets.add(DataChannel.PARTICIPANTS)
}
}
if (!updateTargets.isEmpty()) {
dataHandler.updateData(updateTargets)
}
val statusString = "" + updatePeriod.getCurrentUpdatePeriod(currentTime, period) + "/" + period
dataHandler.broadcastEvent(StatusEvent(statusString))
// Schedule the next update
handler.postDelayed(this, 1000)
}
}
fun restart() {
configureServiceMode()
updatePeriod.restart()
}
override fun onDestroy() {
super.onDestroy()
Log.v(Main.LOG_TAG, "AppService.onDestroy()")
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, keyString: String) {
onSharedPreferenceChanged(sharedPreferences, PreferenceKey.fromString(keyString))
}
private fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: PreferenceKey) {
when (key) {
PreferenceKey.ALERT_ENABLED -> {
alertEnabled = sharedPreferences.get(key, false)
configureServiceMode()
}
PreferenceKey.QUERY_PERIOD -> period = Integer.parseInt(sharedPreferences.get(key, "60"))
PreferenceKey.BACKGROUND_QUERY_PERIOD -> {
backgroundPeriod = Integer.parseInt(sharedPreferences.get(key, "0"))
Log.v(Main.LOG_TAG, "AppService.onSharedPreferenceChanged() backgroundPeriod=%d".format(backgroundPeriod))
discardAlarm()
configureServiceMode()
}
PreferenceKey.SHOW_PARTICIPANTS -> updateParticipants = sharedPreferences.get(key, true)
}
}
fun configureServiceMode() {
Log.v(Main.LOG_TAG, "AppService.configureServiceMode() entered")
val backgroundOperation = dataHandler.hasConsumers
if (backgroundOperation) {
if (alertEnabled && backgroundPeriod > 0) {
locationHandler.enableBackgroundMode()
locationHandler.updateProvider()
createAlarm()
} else {
alertHandler.unsetAlertListener()
discardAlarm()
}
} else {
discardAlarm()
if (dataHandler.isRealtime) {
Log.v(Main.LOG_TAG, "AppService.configureServiceMode() realtime data")
if (!isEnabled) {
isEnabled = true
handler.removeCallbacks(this)
handler.post(this)
}
} else {
Log.v(Main.LOG_TAG, "AppService.configureServiceMode() historic data")
isEnabled = false
handler.removeCallbacks(this)
if (lastParameters != null && lastParameters != dataHandler.activeParameters) {
dataHandler.updateData()
}
}
locationHandler.disableBackgroundMode()
Log.v(Main.LOG_TAG, "AppService.configureServiceMode() set alert event consumer")
}
Log.v(Main.LOG_TAG, "AppService.configureServiceMode() done")
}
private fun createAlarm() {
if (alarmManager == null && dataHandler.hasConsumers && backgroundPeriod > 0) {
Log.v(Main.LOG_TAG, "AppService.createAlarm() with backgroundPeriod=%d".format(backgroundPeriod))
val intent = Intent(this, AppService::class.java)
intent.action = RETRIEVE_DATA_ACTION
pendingIntent = PendingIntent.getService(this, 0, intent, 0)
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager?
if (alarmManager != null) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 0, (backgroundPeriod * 1000).toLong(), pendingIntent)
} else {
Log.e(Main.LOG_TAG, "AppService.createAlarm() failed")
}
this.alarmManager = alarmManager
}
}
private fun discardAlarm() {
val alarmManager = alarmManager
if (alarmManager != null) {
Log.v(Main.LOG_TAG, "AppService.discardAlarm()")
alarmManager.cancel(pendingIntent)
pendingIntent!!.cancel()
pendingIntent = null
this.alarmManager = null
}
}
fun alertEvent(): AlertEvent {
return alertHandler.alertEvent
}
inner class DataServiceBinder : Binder() {
internal val service: AppService
get() {
Log.d(Main.LOG_TAG, "DataServiceBinder.getService() " + this@AppService)
return this@AppService
}
}
companion object {
val RETRIEVE_DATA_ACTION = "retrieveData"
var instance: AppService? = null
private set
}
}
|
apache-2.0
|
f565cd893cc03f1ce24bb23af69f173a
| 33.825083 | 178 | 0.638362 | 4.937763 | false | false | false | false |
jonalmeida/focus-android
|
app/src/main/java/org/mozilla/focus/session/ui/SessionViewHolder.kt
|
1
|
2483
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.session.ui
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.widget.TextView
import mozilla.components.browser.session.Session
import org.mozilla.focus.R
import org.mozilla.focus.ext.beautifyUrl
import org.mozilla.focus.ext.requireComponents
import org.mozilla.focus.telemetry.TelemetryWrapper
import java.lang.ref.WeakReference
class SessionViewHolder internal constructor(
private val fragment: SessionsSheetFragment,
private val textView: TextView
) : RecyclerView.ViewHolder(textView), View.OnClickListener {
companion object {
@JvmField
internal val LAYOUT_ID = R.layout.item_session
}
private var sessionReference: WeakReference<Session> = WeakReference<Session>(null)
init {
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_link, 0, 0, 0)
textView.setOnClickListener(this)
}
fun bind(session: Session) {
this.sessionReference = WeakReference(session)
updateTitle(session)
val isCurrentSession = fragment.requireComponents.sessionManager.selectedSession == session
updateTextBackgroundColor(isCurrentSession)
}
private fun updateTextBackgroundColor(isCurrentSession: Boolean) {
val drawable = if (isCurrentSession) {
R.drawable.background_list_item_current_session
} else {
R.drawable.background_list_item_session
}
textView.setBackgroundResource(drawable)
}
private fun updateTitle(session: Session) {
textView.text =
if (session.title.isEmpty()) session.url.beautifyUrl()
else session.title
}
override fun onClick(view: View) {
val session = sessionReference.get() ?: return
selectSession(session)
}
private fun selectSession(session: Session) {
fragment.animateAndDismiss().addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
fragment.requireComponents.sessionManager.select(session)
TelemetryWrapper.switchTabInTabsTrayEvent()
}
})
}
}
|
mpl-2.0
|
9473c47e3470817acc308a18732f5e39
| 32.554054 | 99 | 0.712847 | 4.802708 | false | false | false | false |
apollo-rsps/apollo
|
game/plugin/shops/src/org/apollo/game/plugin/shops/Shop.kt
|
1
|
8946
|
package org.apollo.game.plugin.shops
import org.apollo.cache.def.ItemDefinition
import org.apollo.game.model.Item
import org.apollo.game.model.entity.Player
import org.apollo.game.model.inv.Inventory
import org.apollo.game.model.inv.Inventory.StackMode.STACK_ALWAYS
import org.apollo.game.plugin.shops.Shop.Companion.ExchangeType.BUYING
import org.apollo.game.plugin.shops.Shop.Companion.ExchangeType.SELLING
import org.apollo.game.plugin.shops.Shop.PurchasePolicy.ANY
import org.apollo.game.plugin.shops.Shop.PurchasePolicy.NOTHING
import org.apollo.game.plugin.shops.Shop.PurchasePolicy.OWNED
/**
* Contains shop-related interface ids.
*/
object Interfaces {
/**
* The container interface id for the player's inventory.
*/
const val INVENTORY_CONTAINER = 3823
/**
* The sidebar id for the inventory, when a Shop window is open.
*/
const val INVENTORY_SIDEBAR = 3822
/**
* The shop window interface id.
*/
const val SHOP_WINDOW = 3824
/**
* The container interface id for the shop's inventory.
*/
const val SHOP_CONTAINER = 3900
/**
* The id of the text widget that displays a shop's name.
*/
const val SHOP_NAME = 3901
}
/**
* The [Map] from npc ids to [Shop]s.
*/
val SHOPS = mutableMapOf<Int, Shop>()
/**
* An in-game shop, operated by one or more npcs.
*
* @param name The name of the shop.
* @param action The id of the NpcActionMessage sent (by the client) when a player opens this shop.
* @param sells The [Map] from item id to amount sold.
* @param operators The [List] of Npc ids that can open this shop.
* @param currency The [Currency] used when making exchanges with this [Shop].
* @param purchases This [Shop]'s attitude towards purchasing items from players.
*/
class Shop(
val name: String,
val action: Int,
private val sells: Map<Int, Int>,
val operators: List<Int>,
private val currency: Currency = Currency.COINS,
private val purchases: PurchasePolicy = OWNED
) {
/**
* The [Inventory] containing this [Shop]'s current items.
*/
val inventory = Inventory(CAPACITY, STACK_ALWAYS)
init {
sells.forEach { (id, amount) -> inventory.add(id, amount) }
}
/**
* Restocks this [Shop], adding and removing items as necessary to move the stock closer to its initial state.
*/
fun restock() {
for (item in inventory.items.filterNotNull()) {
val id = item.id
if (!sells(id) || item.amount > sells[id]!!) {
inventory.remove(id)
} else if (item.amount < sells[id]!!) {
inventory.add(id)
}
}
}
/**
* Sells an item to a [Player].
*/
fun sell(player: Player, slot: Int, option: Int) {
val item = inventory.get(slot)
val id = item.id
val itemCost = value(id, SELLING)
if (option == VALUATION_OPTION) {
val itemId = ItemDefinition.lookup(id).name
player.sendMessage("$itemId: currently costs $itemCost ${currency.name(itemCost)}.")
return
}
var buying = amount(option)
var unavailable = false
val amount = item.amount
if (buying > amount) {
buying = amount
unavailable = true
}
val stackable = item.definition.isStackable
val slotsRequired = when {
stackable && player.inventory.contains(id) -> 0
!stackable -> buying
else -> 1
}
val freeSlots = player.inventory.freeSlots()
var full = false
if (slotsRequired > freeSlots) {
buying = freeSlots
full = true
}
val totalCost = buying * itemCost
val totalCurrency = player.inventory.getAmount(currency.id)
var unaffordable = false
if (totalCost > totalCurrency) {
buying = totalCurrency / itemCost
unaffordable = true
}
if (buying > 0) {
player.inventory.remove(currency.id, totalCost)
val remaining = player.inventory.add(id, buying)
if (remaining > 0) {
player.inventory.add(currency.id, remaining * itemCost)
}
if (buying >= amount && sells(id)) {
// If the item is from the shop's main stock, set its amount to zero so it can be restocked over time.
inventory.set(slot, Item(id, 0))
} else {
inventory.remove(id, buying - remaining)
}
}
val message = when {
unaffordable -> "You don't have enough ${currency.name}."
full -> "You don't have enough inventory space."
unavailable -> "The shop has run out of stock."
else -> return
}
player.sendMessage(message)
}
/**
* Purchases the item from the specified [Player].
*/
fun buy(seller: Player, slot: Int, option: Int) {
val player = seller.inventory
val id = player.get(slot).id
if (!verifyPurchase(seller, id)) {
return
}
val value = value(id, BUYING)
if (option == VALUATION_OPTION) {
seller.sendMessage("${ItemDefinition.lookup(id).name}: shop will buy for $value ${currency.name(value)}.")
return
}
val amount = Math.min(player.getAmount(id), amount(option))
player.remove(id, amount)
inventory.add(id, amount)
if (value != 0) {
player.add(currency.id, value * amount)
}
}
/**
* Returns the value of the item with the specified id.
*
* @param method The [ExchangeType].
*/
private fun value(item: Int, method: ExchangeType): Int {
val value = ItemDefinition.lookup(item).value
return when (method) {
BUYING -> when (purchases) {
NOTHING -> throw UnsupportedOperationException("Cannot get sell value in shop that doesn't buy.")
OWNED -> (value * 0.6).toInt()
ANY -> (value * 0.4).toInt()
}
SELLING -> when (purchases) {
ANY -> Math.ceil(value * 0.8).toInt()
else -> value
}
}
}
/**
* Verifies that the [Player] can actually sell an item with the given id to this [Shop].
*
* @param id The id of the [Item] to sell.
*/
private fun verifyPurchase(player: Player, id: Int): Boolean {
val item = ItemDefinition.lookup(id)
if (!purchases(id) || item.isMembersOnly && !player.isMembers || item.value == 0) {
player.sendMessage("You can't sell this item to this shop.")
return false
} else if (inventory.freeSlots() == 0 && !inventory.contains(id)) {
player.sendMessage("The shop is currently full at the moment.")
return false
}
return true
}
/**
* Returns whether or not this [Shop] will purchase an item with the given id.
*
* @param id The id of the [Item] purchase buy.
*/
private fun purchases(id: Int): Boolean {
return id != currency.id && when (purchases) {
NOTHING -> false
OWNED -> sells.containsKey(id)
ANY -> true
}
}
/**
* Returns whether or not this [Shop] sells the item with the given id.
*
* @param id The id of the [Item] to sell.
*/
private fun sells(id: Int): Boolean = sells.containsKey(id)
/**
* The [Shop]s policy regarding purchasing items from players.
*/
enum class PurchasePolicy {
/**
* Never purchase anything from players.
*/
NOTHING,
/**
* Only purchase items that this Shop sells by default.
*/
OWNED,
/**
* Purchase any tradeable items.
*/
ANY
}
companion object {
/**
* The amount of pulses between shop inventory restocking.
*/
const val RESTOCK_INTERVAL = 100
/**
* The capacity of a [Shop].
*/
private const val CAPACITY = 30
/**
* The type of exchange occurring between the [Player] and [Shop].
*/
private enum class ExchangeType { BUYING, SELLING }
/**
* The option id for item valuation.
*/
private const val VALUATION_OPTION = 1
/**
* Returns the amount that a player tried to buy or sell.
*
* @param option The id of the option the player selected.
*/
private fun amount(option: Int): Int {
return when (option) {
2 -> 1
3 -> 5
4 -> 10
else -> throw IllegalArgumentException("Option must be 1-4")
}
}
}
}
|
isc
|
06604a3ae5b9d22c0128e6e49526a5e6
| 27.676282 | 118 | 0.565728 | 4.198029 | false | false | false | false |
cbeust/kobalt
|
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/api/Project.kt
|
2
|
11262
|
package com.beust.kobalt.api
import com.beust.kobalt.TestConfig
import com.beust.kobalt.api.annotation.Directive
import com.beust.kobalt.maven.DependencyManager
import com.beust.kobalt.maven.aether.AetherDependency
import com.beust.kobalt.maven.aether.KobaltMavenResolver
import com.beust.kobalt.misc.KFiles
import com.beust.kobalt.misc.kobaltLog
import org.apache.maven.model.Model
import java.io.File
import java.util.*
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
import java.util.regex.Pattern
open class Project(
@Directive open var name: String = "",
@Directive open var version: String? = null,
@Directive open var directory: String = ".",
@Directive open var buildDirectory: String = KFiles.KOBALT_BUILD_DIR,
@Directive open var group: String? = null,
@Directive open var artifactId: String? = null,
@Directive open var packaging: String? = null,
@Directive open var description : String = "",
@Directive open var url: String? = null,
@Directive open var pom: Model? = null,
@Directive open var dependsOn: ArrayList<Project> = arrayListOf<Project>(),
@Directive open var testsDependOn: ArrayList<Project> = arrayListOf<Project>(),
@Directive open var packageName: String? = group)
: IBuildConfig, IDependencyHolder by DependencyHolder() {
init {
this.project = this
}
fun allProjectDependedOn() = project.dependsOn + project.testsDependOn
class ProjectExtra(project: Project) {
var isDirty = false
/**
* @return true if any of the projects we depend on is dirty.
*/
fun dependsOnDirtyProjects(project: Project) = project.allProjectDependedOn().any { it.projectExtra.isDirty }
}
/**
* This field caches a bunch of things we don't want to recalculate all the time, such as the list of suffixes
* found in this project.
*/
val projectExtra = ProjectExtra(this)
val testConfigs = arrayListOf<TestConfig>()
// If one is specified by default, we only generateAndSave a BuildConfig, find a way to fix that
override var buildConfig : BuildConfig? = null // BuildConfig()
val projectProperties = ProjectProperties()
override fun equals(other: Any?) = name == (other as Project).name
override fun hashCode() = name.hashCode()
companion object {
val DEFAULT_SOURCE_DIRECTORIES = setOf("src/main/java", "src/main/kotlin", "src/main/resources")
val DEFAULT_SOURCE_DIRECTORIES_TEST = setOf("src/test/java", "src/test/kotlin", "src/test/resources")
}
//
// Directories
//
@Directive
fun sourceDirectories(init: Sources.() -> Unit) : Sources {
return Sources(this, sourceDirectories).apply { init() }
}
var sourceDirectories = hashSetOf<String>().apply { addAll(DEFAULT_SOURCE_DIRECTORIES)}
@Directive
fun sourceDirectoriesTest(init: Sources.() -> Unit) : Sources {
return Sources(this, sourceDirectoriesTest).apply { init() }
}
var sourceDirectoriesTest = hashSetOf<String>().apply { addAll(DEFAULT_SOURCE_DIRECTORIES_TEST)}
//
// Dependencies
//
@Directive
fun dependenciesTest(init: Dependencies.() -> Unit) : Dependencies {
dependencies = Dependencies(this, testDependencies, arrayListOf(),
testProvidedDependencies, compileOnlyDependencies, compileRuntimeDependencies,
excludedDependencies, nativeDependencies)
dependencies!!.init()
return dependencies!!
}
val testDependencies : ArrayList<IClasspathDependency> = arrayListOf()
val testProvidedDependencies : ArrayList<IClasspathDependency> = arrayListOf()
fun testsDependOn(vararg projects: Project) = testsDependOn.addAll(projects)
fun dependsOn(vararg projects: Project) = dependsOn.addAll(projects)
/** Used to disambiguate various name properties */
@Directive
val projectName: String get() = name
val productFlavors = hashMapOf<String, ProductFlavorConfig>()
fun addProductFlavor(name: String, pf: ProductFlavorConfig) {
productFlavors.put(name, pf)
}
var defaultConfig : BuildConfig? = null
val buildTypes = hashMapOf<String, BuildTypeConfig>()
fun addBuildType(name: String, bt: BuildTypeConfig) {
buildTypes.put(name, bt)
}
fun classesDir(context: KobaltContext): String {
val initial = KFiles.joinDir(buildDirectory, "classes")
val result = context.pluginInfo.buildDirectoryInterceptors.fold(initial, { dir, intercept ->
intercept.intercept(this, context, dir)
})
return result
}
class Dep(val file: File, val id: String)
/**
* @return a list of the transitive dependencies (absolute paths to jar files) for the given dependencies.
* Can be used for example as `collect(compileDependencies)`.
*/
@Directive
fun collect(dependencies: List<IClasspathDependency>) : List<Dep> {
return (Kobalt.context?.dependencyManager?.transitiveClosure(dependencies) ?: emptyList())
.map { Dep(it.jarFile.get(), it.id) }
}
override fun toString() = "[Project $name]"
}
class Sources(val project: Project, val sources: HashSet<String>) {
@Directive
fun path(vararg paths: String) {
sources.addAll(paths)
}
}
class Dependencies(val project: Project,
val dependencies: ArrayList<IClasspathDependency>,
val optionalDependencies: ArrayList<IClasspathDependency>,
val providedDependencies: ArrayList<IClasspathDependency>,
val compileOnlyDependencies: ArrayList<IClasspathDependency>,
val runtimeDependencies: ArrayList<IClasspathDependency>,
val excludedDependencies: ArrayList<IClasspathDependency>,
val nativeDependencies: ArrayList<IClasspathDependency>) {
/**
* Add the dependencies to the given ArrayList and return a list of future jar files corresponding to
* these dependencies. Futures are necessary here since this code is invoked from the build file and
* we might not have set up the extra IRepositoryContributors just yet. By the time these
* future tasks receive a get(), the repos will be correct.
*/
private fun addToDependencies(project: Project, dependencies: ArrayList<IClasspathDependency>,
dep: Array<out String>, optional: Boolean = false, excludeConfig: ExcludeConfig? = null): List<Future<File>>
= with(dep.map {
val resolved =
if (KobaltMavenResolver.isRangeVersion(it)) {
// Range id
val node = Kobalt.INJECTOR.getInstance(KobaltMavenResolver::class.java).resolveToArtifact(it)
val result = KobaltMavenResolver.artifactToId(node)
kobaltLog(2, "Resolved range id $it to $result")
result
} else {
it
}
DependencyManager.create(resolved, optional, project.directory)
}) {
dependencies.addAll(this)
if (excludeConfig != null) {
this.forEach { it.excluded.add(excludeConfig) }
}
this.map { FutureTask { it.jarFile.get() } }
}
@Directive
fun compile(vararg dep: String) = addToDependencies(project, dependencies, dep)
class ExcludeConfig {
val ids = arrayListOf<String>()
@Directive
fun exclude(vararg passedIds: String) = ids.addAll(passedIds)
class ArtifactConfig(
var groupId: String? = null,
var artifactId: String? = null,
var version: String? = null
)
val artifacts = arrayListOf<ArtifactConfig>()
@Directive
fun exclude(groupId: String? = null, artifactId: String? = null, version: String? = null)
= artifacts.add(ArtifactConfig(groupId, artifactId, version))
fun match(pattern: String?, id: String) : Boolean {
return pattern == null || Pattern.compile(pattern).matcher(id).matches()
}
/**
* @return true if the dependency is excluded with any of the exclude() directives. The matches
* are performed by a regular expression match against the dependency.
*/
fun isExcluded(dep: IClasspathDependency) : Boolean {
// Straight id match
var result = ids.any { match(it, dep.id) }
// Match on any combination of (groupId, artifactId, version)
if (! result && dep.isMaven) {
val mavenDep = dep as AetherDependency
val artifact = mavenDep.artifact
result = artifacts.any {
val match1 = it.groupId == null || match(it.groupId, artifact.groupId)
val match2 = it.artifactId == null || match(it.artifactId, artifact.artifactId)
val match3 = it.version == null || match(it.version, artifact.version)
match1 && match2 && match3
}
}
return result
}
}
@Directive
fun compile(dep: String, init: ExcludeConfig.() -> Unit) {
val excludeConfig = ExcludeConfig().apply {
init()
}
addToDependencies(project, dependencies, arrayOf(dep), excludeConfig = excludeConfig)
}
@Directive
fun compileOnly(vararg dep: String) = addToDependencies(project, compileOnlyDependencies, dep)
@Directive
fun compileOptional(vararg dep: String) {
addToDependencies(project, optionalDependencies, dep, optional = true)
addToDependencies(project, dependencies, dep, optional = true)
}
@Directive
fun provided(vararg dep: String) {
addToDependencies(project, providedDependencies, dep)
}
@Directive
fun runtime(vararg dep: String) = addToDependencies(project, runtimeDependencies, dep)
@Directive
fun exclude(vararg dep: String) = addToDependencies(project, excludedDependencies, dep)
@Directive
fun native(vararg dep: String) = addToDependencies(project, nativeDependencies, dep)
}
class BuildConfig {
class Field(val name: String, val type: String, val value: Any) {
override fun hashCode() = name.hashCode()
override fun equals(other: Any?) = (other as Field).name == name
}
val fields = arrayListOf<Field>()
fun field(type: String, name: String, value: Any) {
fields.add(Field(name, type, value))
}
}
interface IBuildConfig {
var buildConfig: BuildConfig?
fun buildConfig(init: BuildConfig.() -> Unit) {
buildConfig = BuildConfig().apply {
init()
}
}
}
fun Project.defaultConfig(init: BuildConfig.() -> Unit) = let { project ->
BuildConfig().apply {
init()
project.defaultConfig = this
}
}
@Directive
fun Project.buildType(name: String, init: BuildTypeConfig.() -> Unit) = BuildTypeConfig(name).apply {
init()
addBuildType(name, this)
}
@Directive
fun Project.productFlavor(name: String, init: ProductFlavorConfig.() -> Unit) = ProductFlavorConfig(name).apply {
init()
addProductFlavor(name, this)
}
|
apache-2.0
|
7c7ce17b9975e6c0b8f92927d36bf2f6
| 34.866242 | 120 | 0.654147 | 4.647957 | false | true | false | false |
FFlorien/AmpachePlayer
|
app/src/main/java/be/florien/anyflow/feature/customView/IconAnimator.kt
|
1
|
3644
|
package be.florien.anyflow.feature.customView
import android.content.Context
import android.graphics.Rect
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import androidx.core.graphics.BlendModeColorFilterCompat
import androidx.core.graphics.BlendModeCompat
import androidx.vectordrawable.graphics.drawable.Animatable2Compat
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import be.florien.anyflow.R
abstract class IconAnimator(val context: Context) {
lateinit var icon: Drawable
protected var oldState: Int = -1
private var oldCallback: Animatable2Compat.AnimationCallback? = null
protected var iconColor = ContextCompat.getColor(context, R.color.iconInApp)
open fun computeIcon(newState: Int, iconPosition: Rect) {
val startIcon = getStartAnimation(newState)
val endIcon = getEndAnimation(newState)
val fixedIcon = getFixedIcon(newState)
when {
startIcon != null -> {
assignIcon(startIcon, iconPosition) {
if (endIcon != null) {
assignIcon(endIcon, iconPosition) {
assignIcon(fixedIcon, iconPosition)
}
} else {
assignIcon(fixedIcon, iconPosition)
}
}
}
endIcon != null -> {
assignIcon(endIcon, iconPosition) {
assignIcon(fixedIcon, iconPosition)
}
}
else -> {
assignIcon(fixedIcon, iconPosition)
}
}
oldState = newState
}
private fun assignIcon(newIcon: Drawable, playPausePosition: Rect, onAnimationEndAction: (() -> Unit)? = null) {
val nullSafeCallback = oldCallback
if (nullSafeCallback != null) {
(icon as? AnimatedVectorDrawableCompat)?.unregisterAnimationCallback(nullSafeCallback)
}
if (onAnimationEndAction != null && newIcon is AnimatedVectorDrawableCompat) {
val callback = object : Animatable2Compat.AnimationCallback() {
override fun onAnimationEnd(drawable: Drawable) {
onAnimationEndAction()
}
}
oldCallback = callback
newIcon.registerAnimationCallback(callback)
} else {
oldCallback = null
}
icon = newIcon
icon.bounds = playPausePosition
(icon as? AnimatedVectorDrawableCompat)?.start()
}
protected fun getIcon(animIconRes: Int): VectorDrawableCompat {
val icon = VectorDrawableCompat.create(context.resources, animIconRes, context.theme)
?: throw IllegalArgumentException("Icon wasn't found !")
icon.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(iconColor, BlendModeCompat.SRC_IN)
return icon
}
protected fun getAnimatedIcon(animIconRes: Int): AnimatedVectorDrawableCompat {
val icon = AnimatedVectorDrawableCompat.create(context, animIconRes)
?: throw IllegalArgumentException("Icon wasn't found !")
icon.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(iconColor, BlendModeCompat.SRC_IN)
return icon
}
abstract fun getStartAnimation(newState: Int): AnimatedVectorDrawableCompat?
abstract fun getEndAnimation(newState: Int): AnimatedVectorDrawableCompat?
abstract fun getFixedIcon(newState: Int): Drawable
}
|
gpl-3.0
|
885378fa4e12ef42f1a3aeb13fbf2b27
| 40.420455 | 121 | 0.657794 | 5.422619 | false | false | false | false |
ibaton/3House
|
mobile/src/main/java/treehou/se/habit/ui/widget/WidgetButtonFactory.kt
|
1
|
2135
|
package treehou.se.habit.ui.widget
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Switch
import se.treehou.ng.ohcommunicator.connector.models.OHItem
import se.treehou.ng.ohcommunicator.connector.models.OHLinkedPage
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import se.treehou.ng.ohcommunicator.connector.models.OHWidget
import se.treehou.ng.ohcommunicator.services.IServerHandler
import treehou.se.habit.R
import treehou.se.habit.connector.Constants
import treehou.se.habit.ui.adapter.WidgetAdapter
import treehou.se.habit.util.logging.Logger
import javax.inject.Inject
class WidgetButtonFactory @Inject constructor() : WidgetFactory {
@Inject lateinit var logger: Logger
@Inject lateinit var server: OHServer
@Inject lateinit var page: OHLinkedPage
@Inject lateinit var serverHandler: IServerHandler
override fun createViewHolder(parent: ViewGroup): WidgetAdapter.WidgetViewHolder {
val context = parent.context
val view = LayoutInflater.from(context).inflate(R.layout.widget_switch_button, parent, false)
return SwitchWidgetViewHolder(view)
}
inner class SwitchWidgetViewHolder(view: View) : WidgetBaseHolder(view, server, page) {
private val buttonView: Button = view.findViewById(R.id.widgetButton)
init {
setupClickListener()
}
private fun setupClickListener() {
buttonView.setOnClickListener {
val mapSingle = widget.mapping[0]
logger.d(TAG, "${widget.label} $mapSingle")
val item: OHItem? = widget.item
if (item != null && item.stateDescription?.isReadOnly != true) {
serverHandler.sendCommand(item.name, mapSingle.command)
}
}
}
override fun bind(itemWidget: WidgetAdapter.WidgetItem) {
super.bind(itemWidget)
buttonView.text = widget.mapping[0].label
}
}
companion object {
const val TAG = "WidgetButtonFactory"
}
}
|
epl-1.0
|
9983c93eb042dd0872b42fd1b508b5a4
| 34.6 | 101 | 0.703513 | 4.532909 | false | false | false | false |
Orchextra/orchextra-android-sdk
|
geofence/src/main/java/com/gigigo/orchextra/geofence/GeofenceTransitionsJobIntentService.kt
|
1
|
8381
|
package com.gigigo.orchextra.geofence
import android.content.Context
import android.content.Intent
import android.location.Location
import android.preference.PreferenceManager
import androidx.core.app.JobIntentService
import com.gigigo.orchextra.core.domain.entities.Trigger
import com.gigigo.orchextra.core.domain.entities.TriggerType
import com.gigigo.orchextra.core.domain.location.OxLocationUpdates
import com.gigigo.orchextra.core.receiver.TriggerBroadcastReceiver
import com.gigigo.orchextra.core.utils.LogUtils.LOGD
import com.gigigo.orchextra.core.utils.LogUtils.LOGE
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_ENTER
import com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_EXIT
import com.google.android.gms.location.GeofencingEvent
/**
* Listener for geofence transition changes.
*
* Receives geofence transition events from Location Services in the form of an Intent containing
* the transition type and geofence id(s) that triggered the transition.
*/
class GeofenceTransitionsJobIntentService : JobIntentService() {
val GEOFENCE_REQUEST_ID: String = "GEOFENCE_REQUEST_ID"
/**
* Handles incoming intents.
* @param intent sent by Location Services. This Intent is provided to Location
* Services (inside a PendingIntent) when addGeofences() is called.
*/
override fun onHandleWork(intent: Intent) {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
if (geofencingEvent.hasError()) {
val errorMessage = GeofenceErrorMessages.getErrorString(
this,
geofencingEvent.errorCode
)
LOGE(TAG, errorMessage)
return
}
// Get the transition type.
val geofenceTransition = geofencingEvent.geofenceTransition
val transition = getTransitionString(geofenceTransition)
LOGD(TAG, "OX Geofence triggered $transition")
// checkGeofenceByRadius(geofenceTransition, geofencingEvent)
if (geofenceTransition == GEOFENCE_TRANSITION_ENTER || geofenceTransition == GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger multiple geofences.
val triggeringGeofences = geofencingEvent.triggeringGeofences
triggeringGeofences.firstOrNull()?.requestId?.let { requestId ->
if (geofenceTransition == GEOFENCE_TRANSITION_ENTER) {
if (!isSent(geofenceTransition, requestId)) {
LOGE(TAG, "Geofence $requestId saved, showing notification EXIT")
saveRequestId(geofenceTransition, requestId)
deleteTransitionExit(requestId)
sendTriggerBroadcast(transition, requestId)
} else {
LOGE(TAG, "Geofence $requestId already saved ENTER")
}
}else if (geofenceTransition == GEOFENCE_TRANSITION_EXIT){
if (!isSent(geofenceTransition, requestId)) {
LOGE(TAG, "Geofence $requestId saved, showing notification EXIT")
saveRequestId(geofenceTransition, requestId)
deleteTransitionEnter(requestId)
sendTriggerBroadcast(transition, requestId)
} else {
LOGE(TAG, "Geofence $requestId already saved EXIT")
}
}
}
} else {
// Log the error.
LOGE(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition))
}
}
private fun checkGeofenceByRadius(
geofenceTransition: Int,
geofencingEvent: GeofencingEvent
) {
val lastLocationSaved = OxLocationUpdates.getLastLocationSaved(applicationContext)
val transitionLocation = geofencingEvent.triggeringLocation
geofencingEvent.triggeringGeofences.firstOrNull()?.requestId?.let { requestId ->
val radius = OxGeofenceImp.getGeofenceRadius(applicationContext, requestId)
when (geofenceTransition) {
GEOFENCE_TRANSITION_ENTER -> {
val geofenceLocation = insideGeofenceLocation(lastLocationSaved, transitionLocation, radius.toFloat())
if (geofenceLocation != null) {
LOGD(TAG, "OX Geofence in!!")
}
}
GEOFENCE_TRANSITION_EXIT -> {
val geofenceLocation = insideGeofenceLocation(lastLocationSaved, transitionLocation, radius.toFloat())
if (geofenceLocation == null) {
LOGD(TAG, "OX Geofence Out!!")
}
}
else -> // Log the error.
LOGE(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition))
}
}
}
private fun deleteTransitionExit(requestId: String) {
val key = "$GEOFENCE_REQUEST_ID-$requestId-$GEOFENCE_TRANSITION_EXIT"
PreferenceManager.getDefaultSharedPreferences(applicationContext).edit().remove(key).apply()
}
private fun deleteTransitionEnter(requestId: String) {
val key = "$GEOFENCE_REQUEST_ID-$requestId-$GEOFENCE_TRANSITION_ENTER"
PreferenceManager.getDefaultSharedPreferences(applicationContext).edit().remove(key).apply()
}
fun insideGeofenceLocation(
currentLocation: Location,
listOfGeofenceLocations: ArrayList<Location>,
triggerRadius: Float
): Location? {
for (geoFenceLocation in listOfGeofenceLocations) {
if (currentLocation.distanceTo(geoFenceLocation) < triggerRadius)
return geoFenceLocation
}
return null
}
fun insideGeofenceLocation(
currentLocation: Location,
geofenceLocation: Location,
triggerRadius: Float
): Location? {
if (currentLocation.distanceTo(geofenceLocation) < triggerRadius)
return geofenceLocation
return null
}
/**
* Save requestId on preferences.
*/
private fun saveRequestId(geofenceTransition: Int, requestId: String) {
val key = "$GEOFENCE_REQUEST_ID-$requestId-$geofenceTransition"
PreferenceManager.getDefaultSharedPreferences(applicationContext).edit()
.putString(key, key).apply()
}
/**
* Check if requestId was sent
*/
private fun isSent(geofenceTransition: Int, requestId: String): Boolean {
val key = "$GEOFENCE_REQUEST_ID-$requestId-$geofenceTransition"
val value = PreferenceManager.getDefaultSharedPreferences(applicationContext)
.getString(key, null)
return value.equals(key)
}
private fun sendTriggerBroadcast(transition: String, requestId: String) {
LOGD(TAG, "OX sending Trigger broadcast")
val trigger = Trigger(
type = TriggerType.GEOFENCE,
value = requestId,
event = transition
)
sendBroadcast(TriggerBroadcastReceiver.getTriggerIntent(this, trigger))
}
/**
* Maps geofence transition types to their human-readable equivalents.
*
* @param transitionType A transition type constant defined in Geofence
* @return A String indicating the type of transition
*/
private fun getTransitionString(transitionType: Int): String {
return when (transitionType) {
GEOFENCE_TRANSITION_ENTER -> getString(R.string.geofence_transition_entered)
GEOFENCE_TRANSITION_EXIT -> getString(R.string.geofence_transition_exited)
Geofence.GEOFENCE_TRANSITION_DWELL -> getString(R.string.geofence_transition_stay)
else -> getString(R.string.unknown_geofence_transition)
}
}
companion object {
private const val JOB_ID = 573
private const val TAG = "GeofenceTransitionsIS"
/**
* Convenience method for enqueuing work in to this service.
*/
fun enqueueWork(context: Context, intent: Intent) {
enqueueWork(
context, GeofenceTransitionsJobIntentService::class.java,
JOB_ID, intent
)
}
}
}
|
apache-2.0
|
f1f6c099e4911e1cb88a6af9cbf7d3ea
| 39.492754 | 122 | 0.646224 | 5.218555 | false | false | false | false |
pyamsoft/pasterino
|
app/src/main/java/com/pyamsoft/pasterino/service/monitor/notification/PasteNotificationDispatcher.kt
|
1
|
4219
|
/*
* Copyright 2020 Peter Kenji Yamanaka
*
* 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.pyamsoft.pasterino.service.monitor.notification
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationChannelGroup
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import com.pyamsoft.pasterino.R
import com.pyamsoft.pasterino.service.single.SinglePasteReceiver
import com.pyamsoft.pydroid.core.requireNotNull
import com.pyamsoft.pydroid.notify.NotifyChannelInfo
import com.pyamsoft.pydroid.notify.NotifyData
import com.pyamsoft.pydroid.notify.NotifyDispatcher
import com.pyamsoft.pydroid.notify.NotifyId
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
import com.pyamsoft.pydroid.ui.R as R2
@Singleton
internal class PasteNotificationDispatcher
@Inject
internal constructor(private val context: Context) : NotifyDispatcher<PasteNotification> {
private val notificationManager by lazy {
context.applicationContext.getSystemService<NotificationManager>().requireNotNull()
}
private val pendingIntent by lazy {
val flags =
PendingIntent.FLAG_UPDATE_CURRENT or
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_IMMUTABLE
} else {
0
}
PendingIntent.getBroadcast(
context,
RC,
Intent(context, SinglePasteReceiver::class.java),
flags,
)
}
private fun setupNotificationChannel(channelInfo: NotifyChannelInfo) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
Timber.d("No channel below Android O")
return
}
val channel: NotificationChannel? = notificationManager.getNotificationChannel(channelInfo.id)
if (channel != null) {
Timber.d("Channel already exists: ${channel.id}")
return
}
val notificationGroup = NotificationChannelGroup(channelInfo.id, channelInfo.title)
val notificationChannel =
NotificationChannel(channelInfo.id, channelInfo.title, NotificationManager.IMPORTANCE_MIN)
.apply {
group = notificationGroup.id
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
description = channelInfo.description
enableLights(false)
enableVibration(false)
setSound(null, null)
}
Timber.d(
"Create notification channel and group ${notificationChannel.id} ${notificationGroup.id}")
notificationManager.apply {
createNotificationChannelGroup(notificationGroup)
createNotificationChannel(notificationChannel)
}
}
override fun build(
id: NotifyId,
channelInfo: NotifyChannelInfo,
notification: PasteNotification
): Notification {
setupNotificationChannel(channelInfo)
return NotificationCompat.Builder(context, channelInfo.id)
.setSmallIcon(R.drawable.ic_paste_notification)
.setContentText("Pasterino Plzarino")
.setContentIntent(pendingIntent)
.setWhen(0)
.setOngoing(true)
.setAutoCancel(false)
.setNumber(0)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setColor(ContextCompat.getColor(context, R2.color.green500))
.build()
}
override fun canShow(notification: NotifyData): Boolean {
return notification is PasteNotification
}
companion object {
private const val RC = 1005
}
}
|
apache-2.0
|
28c7ee6fe8d651bebfdcbc69f21f3948
| 32.220472 | 98 | 0.727187 | 4.729821 | false | false | false | false |
vanita5/twittnuker
|
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/sync/FileBasedFiltersDataSyncAction.kt
|
1
|
4615
|
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.sync
import android.content.Context
import android.util.Xml
import org.mariotaku.ktextension.nullableContentEquals
import de.vanita5.twittnuker.extension.model.*
import de.vanita5.twittnuker.model.FiltersData
import de.vanita5.twittnuker.provider.TwidereDataStore.Filters
import de.vanita5.twittnuker.util.content.ContentResolverUtils
import java.io.Closeable
import java.io.File
import java.io.IOException
abstract class FileBasedFiltersDataSyncAction<DownloadSession : Closeable, UploadSession : Closeable>(
val context: Context
) : SingleFileBasedDataSyncAction<FiltersData, File, DownloadSession, UploadSession>() {
override fun File.loadSnapshot(): FiltersData {
return reader().use {
val snapshot = FiltersData()
val parser = Xml.newPullParser()
parser.setInput(it)
snapshot.parse(parser)
return@use snapshot
}
}
override fun File.saveSnapshot(data: FiltersData) {
writer().use {
val serializer = Xml.newSerializer()
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true)
serializer.setOutput(it)
data.serialize(serializer)
}
}
override var File.snapshotLastModified: Long
get() = this.lastModified()
set(value) {
this.setLastModified(value)
}
override fun loadFromLocal(): FiltersData {
return FiltersData().apply {
read(context.contentResolver)
initFields()
}
}
override fun addToLocal(data: FiltersData) {
data.write(context.contentResolver, deleteOld = false)
}
override fun removeFromLocal(data: FiltersData) {
ContentResolverUtils.bulkDelete(context.contentResolver, Filters.Users.CONTENT_URI,
Filters.Users.USER_KEY, false, data.users?.map { it.userKey }, null, null)
ContentResolverUtils.bulkDelete(context.contentResolver, Filters.Keywords.CONTENT_URI,
Filters.Keywords.VALUE, false, data.keywords?.map { it.value }, null, null)
ContentResolverUtils.bulkDelete(context.contentResolver, Filters.Sources.CONTENT_URI,
Filters.Sources.VALUE, false, data.sources?.map { it.value }, null, null)
ContentResolverUtils.bulkDelete(context.contentResolver, Filters.Links.CONTENT_URI,
Filters.Links.VALUE, false, data.links?.map { it.value }, null, null)
}
override fun newData(): FiltersData {
return FiltersData()
}
override fun FiltersData.minus(data: FiltersData): FiltersData {
val diff = FiltersData()
diff.addAll(this, true)
diff.removeAllData(data)
return diff
}
override fun FiltersData.addAllData(data: FiltersData): Boolean {
return this.addAll(data, ignoreDuplicates = true)
}
override fun FiltersData.removeAllData(data: FiltersData): Boolean {
return this.removeAll(data)
}
override fun FiltersData.isDataEmpty(): Boolean {
return this.isEmpty()
}
override fun newSnapshotStore(): File {
val syncDataDir: File = context.syncDataDir.mkdirIfNotExists() ?: throw IOException()
return File(syncDataDir, "filters.xml")
}
override fun FiltersData.dataContentEquals(localData: FiltersData): Boolean {
return this.users.nullableContentEquals(localData.users)
&& this.keywords.nullableContentEquals(localData.keywords)
&& this.sources.nullableContentEquals(localData.sources)
&& this.links.nullableContentEquals(localData.links)
}
override val whatData: String = "filters"
}
|
gpl-3.0
|
49d7d1ab885b719698dabae9e612c81d
| 36.528455 | 102 | 0.691224 | 4.395238 | false | false | false | false |
ajoz/kotlin-workshop
|
aoc16/src/main/kotlin/io/github/ajoz/workshop/day2/solution/Day2Solution.kt
|
1
|
6612
|
package io.github.ajoz.workshop.day2.solution
import io.github.ajoz.workshop.fsm.FSM
import io.github.ajoz.workshop.fsm.State
import io.github.ajoz.workshop.fsm.Symbol
import io.github.ajoz.workshop.fsm.Transitions.Companion.transitions
import io.github.ajoz.workshop.sequences.scan
import io.github.ajoz.workshop.strings.head
import io.github.ajoz.workshop.strings.tail
/**
* We can see the solution to this puzzle in terms of a deterministic FSM (finite state machine). An input alphabet of
* a FSM consists of a set of symbols, states change to next states due to a transition function. Each function can be
* easily expressed just as a map of some value to another value. We can define FSM transition function in terms of a
* mapping (State, Symbol) -> State. This can be expressed as a Map<Pair<State, Symbol>, State>. We can now prepare
* a transition function with a DSL made just for this puzzle.
*
* Our set of possible states is subset of Int: 1, 2, 3, 4, 5, 6, 7, 8, 9
* Our set of possible symbols is subset of Char: U, R, L, D
*
* We want to have a DSL expressive enough to allow writing like:
*
* 1 or 2 or 3 cycles after U
*
* In the fsm package you can find a simple implementation of such DSL.
*/
val Char.symbol: Symbol<Char>
get() = Symbol(this)
tailrec fun acceptIntChar(fsm: FSM<Int, Char>, instruction: String): FSM<Int, Char> = when {
instruction.isEmpty() -> fsm
else -> acceptIntChar(fsm.accept(instruction.head.symbol), instruction.tail)
}
val day2part1Transition = transitions(
(State(1) or State(2) or State(3)) cyclesAfter Symbol('U'),
(State(1) or State(4) or State(7)) cyclesAfter Symbol('L'),
(State(3) or State(6) or State(9)) cyclesAfter Symbol('R'),
(State(7) or State(8) or State(9)) cyclesAfter Symbol('D'),
State(1) after Symbol('R') transitionsTo State(2),
State(1) after Symbol('D') transitionsTo State(4),
State(2) after Symbol('L') transitionsTo State(1),
State(2) after Symbol('R') transitionsTo State(3),
State(2) after Symbol('D') transitionsTo State(5),
State(3) after Symbol('L') transitionsTo State(2),
State(3) after Symbol('D') transitionsTo State(6),
State(4) after Symbol('U') transitionsTo State(1),
State(4) after Symbol('R') transitionsTo State(5),
State(4) after Symbol('D') transitionsTo State(7),
State(5) after Symbol('U') transitionsTo State(2),
State(5) after Symbol('L') transitionsTo State(4),
State(5) after Symbol('R') transitionsTo State(6),
State(5) after Symbol('D') transitionsTo State(8),
State(6) after Symbol('U') transitionsTo State(3),
State(6) after Symbol('L') transitionsTo State(5),
State(6) after Symbol('D') transitionsTo State(9),
State(7) after Symbol('U') transitionsTo State(4),
State(7) after Symbol('R') transitionsTo State(8),
State(8) after Symbol('U') transitionsTo State(5),
State(8) after Symbol('L') transitionsTo State(7),
State(8) after Symbol('R') transitionsTo State(9),
State(9) after Symbol('U') transitionsTo State(6),
State(9) after Symbol('L') transitionsTo State(8)
)
fun getPart1BathroomAccessCode(instructions: String): Int {
val fsm = FSM(State(5), day2part1Transition)
return instructions.splitToSequence(delimiters = '\n')
.scan(fsm, ::acceptIntChar)
.map { fsm -> fsm.state.value }
.fold("") {
str, value ->
str + value
}.toInt()
}
val day2part2Transition = transitions(
State('1') or State('2') or State('5') or State('A') or State('D') cyclesAfter Symbol('L'),
State('1') or State('4') or State('9') or State('C') or State('D') cyclesAfter Symbol('R'),
State('5') or State('2') or State('1') or State('4') or State('9') cyclesAfter Symbol('U'),
State('5') or State('A') or State('D') or State('C') or State('9') cyclesAfter Symbol('D'),
State('1') after Symbol('D') transitionsTo State('3'),
State('2') after Symbol('D') transitionsTo State('6'),
State('4') after Symbol('D') transitionsTo State('8'),
State('2') after Symbol('R') transitionsTo State('3'),
State('4') after Symbol('L') transitionsTo State('3'),
State('5') after Symbol('R') transitionsTo State('6'),
State('9') after Symbol('L') transitionsTo State('8'),
State('A') after Symbol('U') transitionsTo State('6'),
State('A') after Symbol('R') transitionsTo State('B'),
State('C') after Symbol('U') transitionsTo State('8'),
State('C') after Symbol('L') transitionsTo State('B'),
State('D') after Symbol('U') transitionsTo State('B'),
State('3') after Symbol('U') transitionsTo State('1'),
State('3') after Symbol('L') transitionsTo State('2'),
State('3') after Symbol('R') transitionsTo State('4'),
State('3') after Symbol('D') transitionsTo State('7'),
State('6') after Symbol('U') transitionsTo State('2'),
State('6') after Symbol('L') transitionsTo State('5'),
State('6') after Symbol('R') transitionsTo State('7'),
State('6') after Symbol('D') transitionsTo State('A'),
State('7') after Symbol('U') transitionsTo State('3'),
State('7') after Symbol('L') transitionsTo State('6'),
State('7') after Symbol('R') transitionsTo State('8'),
State('7') after Symbol('D') transitionsTo State('B'),
State('8') after Symbol('U') transitionsTo State('4'),
State('8') after Symbol('L') transitionsTo State('7'),
State('8') after Symbol('R') transitionsTo State('9'),
State('8') after Symbol('D') transitionsTo State('C'),
State('B') after Symbol('U') transitionsTo State('7'),
State('B') after Symbol('L') transitionsTo State('A'),
State('B') after Symbol('R') transitionsTo State('C'),
State('B') after Symbol('D') transitionsTo State('D')
)
tailrec fun acceptCharChar(fsm: FSM<Char, Char>, instruction: String): FSM<Char, Char> = when {
instruction.isEmpty() -> fsm
else -> acceptCharChar(fsm.accept(instruction.head.symbol), instruction.tail)
}
fun getPart2BathroomAccessCode(instructions: String): String {
val fsm = FSM(State('5'), day2part2Transition)
return instructions.splitToSequence(delimiters = '\n')
.scan(fsm, ::acceptCharChar)
.map { fsm -> fsm.state.value }
.fold("") {
str, value ->
str + value
}
}
|
apache-2.0
|
fee52efa7d667e8876aea058ff343dc2
| 49.480916 | 118 | 0.631125 | 3.632967 | false | false | false | false |
kittinunf/Fuel
|
fuel/src/main/kotlin/com/github/kittinunf/fuel/core/interceptors/RedirectionInterceptor.kt
|
1
|
2467
|
package com.github.kittinunf.fuel.core.interceptors
import com.github.kittinunf.fuel.core.Encoding
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.Headers
import com.github.kittinunf.fuel.core.Method
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.fuel.core.isStatusRedirection
import java.net.URI
import java.net.URL
import javax.net.ssl.HttpsURLConnection
private val redirectStatusWithGets = listOf(
HttpsURLConnection.HTTP_MOVED_PERM,
HttpsURLConnection.HTTP_MOVED_TEMP,
HttpsURLConnection.HTTP_SEE_OTHER
)
fun redirectResponseInterceptor(manager: FuelManager) =
{ next: (Request, Response) -> Response ->
inner@{ request: Request, response: Response ->
if (!response.isStatusRedirection || request.executionOptions.allowRedirects == false) {
return@inner next(request, response)
}
val redirectedUrl = response[Headers.LOCATION]
.ifEmpty { response[Headers.CONTENT_LOCATION] }
.lastOrNull()
if (redirectedUrl.isNullOrEmpty()) {
return@inner next(request, response)
}
val newUrl = if (URI(redirectedUrl.split('?').first()).isAbsolute) URL(redirectedUrl) else URL(request.url, redirectedUrl)
val newMethod = when {
response.statusCode in redirectStatusWithGets -> Method.GET
else -> request.method
}
val encoding = Encoding(httpMethod = newMethod, urlString = newUrl.toString())
val newRequest = manager.request(encoding)
.header(Headers.from(request.headers))
.also {
// Check whether it is the same host or not
if (newUrl.host != request.url.host)
it.headers.remove(Headers.AUTHORIZATION)
}
.requestProgress(request.executionOptions.requestProgress)
.responseProgress(request.executionOptions.responseProgress)
.let {
if (newMethod === request.method && !request.body.isEmpty() && !request.body.isConsumed())
it.body(request.body)
else
it
}
// Redirect
next(request, newRequest.response().second)
}
}
|
mit
|
66f2bf517611fe24ef3b2c14da0ae392
| 38.790323 | 134 | 0.619376 | 4.885149 | false | false | false | false |
noud02/Akatsuki
|
src/main/kotlin/moe/kyubey/akatsuki/extensions/User.kt
|
1
|
1954
|
/*
* Copyright (c) 2017-2019 Yui
*
* 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 moe.kyubey.akatsuki.extensions
import me.aurieh.ares.exposed.async.asyncTransaction
import moe.kyubey.akatsuki.Akatsuki
import moe.kyubey.akatsuki.db.DBContract
import moe.kyubey.akatsuki.db.schema.Contracts
import net.dv8tion.jda.core.entities.User
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.select
import org.joda.time.DateTime
fun User.createContract(wish: String) {
asyncTransaction(Akatsuki.pool) {
Contracts.insert {
it[userId] = idLong
it[this.wish] = wish
it[date] = DateTime.now()
it[gem] = "common"
it[corruption] = 0
it[level] = 1
it[experience] = 0
it[inventory] = arrayOf()
it[balance] = 5000
}
}.execute()
}
|
mit
|
1947d287cb69d467da36505f4757e7b7
| 37.333333 | 70 | 0.697544 | 4.06237 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/ide/intentions/GenerateDocStubIntention.kt
|
2
|
3588
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.util.text.CharArrayUtil
import org.rust.lang.core.psi.RsValueParameter
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.psi.impl.RsFunctionImpl
import org.rust.lang.core.types.ty.Ty
import kotlin.math.max
class GenerateDocStubIntention : RsElementBaseIntentionAction<GenerateDocStubIntention.Context>() {
override fun getText() = "Generate documentation stub"
override fun getFamilyName() = text
data class Context(
val func: RsElement,
val params: List<RsValueParameter>,
val returnType: Ty
)
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val targetFunc = element.ancestorOrSelf<RsGenericDeclaration>() ?: return null
if (targetFunc !is RsFunctionImpl) return null
if (targetFunc.name != element.text) return null
if (targetFunc.text.startsWith("///")) return null
val params = targetFunc.valueParameters
if (params.isEmpty()) {
return null
}
val returnType = targetFunc.rawReturnType
return Context(targetFunc, params, returnType)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val (targetFunc, params, returnType) = ctx
val document = editor.document
var commentStartOffset: Int = targetFunc.textRange.startOffset
val lineStartOffset = document.getLineStartOffset(document.getLineNumber(commentStartOffset))
if (lineStartOffset in 1 until commentStartOffset) {
val nonWhiteSpaceOffset = CharArrayUtil.shiftBackward(document.charsSequence, commentStartOffset - 1, " \t")
commentStartOffset = max(nonWhiteSpaceOffset, lineStartOffset)
}
val buffer = StringBuilder()
var commentBodyRelativeOffset = 0
val indentOffset = targetFunc.startOffset - lineStartOffset
val indentation = " ".repeat(indentOffset)
buffer.append("$indentation/// \n")
commentBodyRelativeOffset += buffer.length
document.insertString(commentStartOffset, buffer)
val docManager = PsiDocumentManager.getInstance(project)
docManager.commitDocument(document)
val stub = generateDocumentStub(indentation, params, returnType)
if (stub.isNotEmpty()) {
val insertionOffset = commentStartOffset + commentBodyRelativeOffset
document.insertString(insertionOffset, stub)
docManager.commitDocument(document)
}
editor.caretModel.moveToOffset(targetFunc.startOffset + buffer.length - indentOffset - 1)
}
}
private fun generateDocumentStub(
indentation: String,
params: List<RsValueParameter>,
returnType: Ty
): String = buildString {
append("$indentation/// \n")
append("$indentation/// # Arguments \n")
append("$indentation/// \n")
for (param in params) {
append("$indentation/// * `${param.patText}`: \n")
}
append("$indentation/// \n")
append("$indentation/// returns: $returnType \n")
append("$indentation/// \n")
append("$indentation/// # Examples \n")
append("$indentation/// \n")
append("$indentation/// ```\n")
append("$indentation/// \n")
append("$indentation/// ```\n")
}
|
mit
|
8f0957d94cafb847d99781640e774193
| 38.428571 | 120 | 0.689799 | 4.65974 | false | false | false | false |
brianwernick/ExoMedia
|
library/src/main/kotlin/com/devbrackets/android/exomedia/util/Repeater.kt
|
1
|
1174
|
package com.devbrackets.android.exomedia.util
import android.os.Handler
import android.os.Looper
import java.util.concurrent.atomic.AtomicBoolean
/**
* A method repeater to easily perform update functions on a timed basis.
* The duration between repeats isn't exact, if you require an exact
* amount of elapsed time use the [StopWatch] instead.
*/
class Repeater(
private val delayMillis: Long = DEFAULT_REPEAT_DELAY,
private val handler: Handler = Handler(Looper.myLooper() ?: Looper.getMainLooper()),
private val callback: () -> Unit
) {
companion object {
private const val DEFAULT_REPEAT_DELAY = 33L // ~30 fps
}
private val started = AtomicBoolean(false)
private var pollRunnable = PollRunnable()
val running: Boolean
get() = started.get()
fun start() {
if (!started.getAndSet(true)) {
pollRunnable.performPoll()
}
}
fun stop() {
started.getAndSet(false)
}
private inner class PollRunnable : Runnable {
override fun run() {
callback.invoke()
if (started.get()) {
performPoll()
}
}
fun performPoll() {
handler.postDelayed(pollRunnable, delayMillis)
}
}
}
|
apache-2.0
|
ed7a4fbd9a97d9bfec61d5f6261fd2d0
| 22.48 | 86 | 0.680579 | 4.133803 | false | false | false | false |
jean79/yested
|
src/main/docsite/bootstrap/mediaObject.kt
|
2
|
2139
|
package bootstrap
import net.yested.Div
import net.yested.div
import net.yested.bootstrap.row
import net.yested.bootstrap.pageHeader
import net.yested.bootstrap.Medium
import net.yested.bootstrap.mediaObject
import net.yested.bootstrap.MediaAlign
fun createMediaObjectSection(id: String): Div {
return div {
this.id = id
row {
col(Medium(12)) {
pageHeader { h3 { +"Media Object" } }
}
}
row {
col(Medium(4)) {
div {
+"""Media object is used for creating components that should contain left- or rightaligned
media (image, video, or audio) alongside some textual content. It is best
suited for creating features such as a comments section, displaying tweets, or
showing product details where a product image is present."""
}
br()
h4 { +"Demo" }
mediaObject(MediaAlign.Left) {
media {
img(src = "demo-site/img/leaf.gif")
}
content {
heading {
+"Media Object"
}
content {
p {
+"""Media object is used for creating components that should contain left- or rightaligned
media (image, video, or audio) alongside some textual content. It is best
suited for creating features such as a comments section, displaying tweets, or
showing product details where a product image is present."""
}
mediaObject(MediaAlign.Left) {
media {
img(src = "demo-site/img/leaf.gif")
}
content {
heading {
+"Nested Media Object"
}
content {
p {+" Nested Text"}
}
}
}
}
}
}
}
col(Medium(8)) {
h4 { +"Code" }
code(lang = "kotlin", content = """
mediaObject(MediaAlign.Left) {
media {
img(src = "demo-site/img/leaf.gif")
}
content {
heading {
+ "Media Object"
}
content {
+ p { "Media object is used ..." }
mediaObject(MediaAlign.Left) {
media {
img(src = "demo-site/img/leaf.gif")
}
content {
heading {
+ "Nested Media Object"
}
content {
+ p { "Nested Text" }
}
}
}
}
}
}
""")
}
}
}
}
|
mit
|
d7d3b5b81bf589ff12a8ff79778911a6
| 21.526316 | 98 | 0.58345 | 3.342188 | false | false | false | false |
arkon/LISTEN.moe-Unofficial-Android-App
|
app/src/main/java/me/echeung/moemoekyun/client/stream/Stream.kt
|
1
|
1953
|
package me.echeung.moemoekyun.client.stream
import android.content.Context
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import me.echeung.moemoekyun.client.stream.player.LocalStreamPlayer
import me.echeung.moemoekyun.client.stream.player.StreamPlayer
import me.echeung.moemoekyun.util.ext.launchIO
import me.echeung.moemoekyun.util.ext.launchNow
@OptIn(ExperimentalCoroutinesApi::class)
class Stream(context: Context) {
val channel = ConflatedBroadcastChannel<State>()
private var localPlayer: StreamPlayer<*> = LocalStreamPlayer(context)
private var altPlayer: StreamPlayer<*>? = null
val isStarted: Boolean
get() = getCurrentPlayer().isStarted
val isPlaying: Boolean
get() = getCurrentPlayer().isPlaying
/**
* Used to "replace" the local player with a Cast player.
*/
fun setAltPlayer(player: StreamPlayer<*>?) {
val wasPlaying = isPlaying
getCurrentPlayer().pause()
altPlayer = player
if (wasPlaying || altPlayer != null) {
getCurrentPlayer().play()
}
}
private fun getCurrentPlayer(): StreamPlayer<*> {
return altPlayer ?: localPlayer
}
fun toggle() {
if (isPlaying) {
pause()
} else {
play()
}
}
fun play() {
getCurrentPlayer().play()
launchNow {
channel.send(State.PLAY)
}
}
fun pause() {
getCurrentPlayer().pause()
launchNow {
channel.send(State.PAUSE)
}
}
fun stop() {
getCurrentPlayer().stop()
launchNow {
channel.send(State.STOP)
}
}
fun fadeOut() {
launchIO {
getCurrentPlayer().fadeOut()
channel.send(State.STOP)
}
}
enum class State {
PLAY,
PAUSE,
STOP,
}
}
|
mit
|
bf60942016fb96c5d7e5e9fa999f46d6
| 21.193182 | 73 | 0.606759 | 4.672249 | false | false | false | false |
stfalcon-studio/uaroads_android
|
app/src/main/java/com/stfalcon/new_uaroads_android/common/injection/modules/AppModule.kt
|
1
|
5136
|
/*
* 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.injection.modules
/*
* Created by Anton Bevza on 4/5/17.
*/
import android.accounts.Account
import android.accounts.AccountManager
import android.content.Context
import android.content.Context.SENSOR_SERVICE
import android.hardware.Sensor
import android.hardware.SensorManager
import android.os.Build
import android.provider.Settings
import com.stfalcon.new_uaroads_android.UaroadsApp
import com.stfalcon.new_uaroads_android.common.injection.InjectionConsts
import com.stfalcon.new_uaroads_android.features.autostart.AutoStartServiceSubComponent
import com.stfalcon.new_uaroads_android.features.main.MainScreenSubComponent
import com.stfalcon.new_uaroads_android.features.places.BestRouteSubComponent
import com.stfalcon.new_uaroads_android.features.places.LocationChooserSubComponent
import com.stfalcon.new_uaroads_android.features.record.service.RecordServiceSubComponent
import com.stfalcon.new_uaroads_android.features.settings.SettingsScreenSubComponent
import com.stfalcon.new_uaroads_android.features.settings.TracksSubComponent
import com.stfalcon.new_uaroads_android.features.tracks.autoupload.AutoUploadServiceSubComponent
import com.stfalcon.new_uaroads_android.features.tracks.service.TracksServiceSubComponent
import com.stfalcon.new_uaroads_android.utils.DataUtils
import dagger.Module
import dagger.Provides
import javax.inject.Named
import javax.inject.Singleton
@Module(subcomponents = arrayOf(
MainScreenSubComponent::class,
LocationChooserSubComponent::class,
BestRouteSubComponent::class,
SettingsScreenSubComponent::class,
RecordServiceSubComponent::class,
TracksServiceSubComponent::class,
AutoUploadServiceSubComponent::class,
AutoStartServiceSubComponent::class,
TracksSubComponent::class)
)
class AppModule {
@Singleton
@Provides
internal fun provideContext(application: UaroadsApp): Context {
return application.applicationContext
}
@Singleton
@Provides @Named(InjectionConsts.NAME_USER_ID)
internal fun provideUserId(application: UaroadsApp): String {
return Settings.Secure.getString(
application.contentResolver,
android.provider.Settings.Secure.ANDROID_ID)
}
@Singleton
@Provides @Named(InjectionConsts.NAME_APP_VERSION)
internal fun provideAppVersion(application: UaroadsApp): String {
try {
return application.packageManager.getPackageInfo(application.packageName, 0).versionName
} catch (ignore: Exception) {
return ""
}
}
@Singleton
@Provides @Named(InjectionConsts.NAME_ACCOUNT_EMAIL)
internal fun provideAccountEmail(application: UaroadsApp): String {
val accountManager = AccountManager.get(application)
val account = getAccount(accountManager) ?: return ""
return account.name
}
@Singleton
@Provides
internal fun provideDataUtils(): DataUtils {
return DataUtils()
}
private fun getAccount(accountManager: AccountManager): Account? {
val accounts = accountManager.getAccountsByType("com.google")
return if (accounts.isNotEmpty()) accounts[0] else null
}
@Singleton
@Provides @Named(InjectionConsts.NAME_SENSOR_INFO)
internal fun getSensorInfo(application: UaroadsApp): String {
val sensorManager = application.getSystemService(SENSOR_SERVICE) as SensorManager
val sensor: Sensor? = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
var sensorInfo = StringBuilder()
sensor?.let {
sensorInfo.append("TYPE_ACCELEROMETER - ")
.append(it.name)
.append("\n Version - ")
.append(it.version)
.append("\n Type - ${it.type}")
.append("\n Vendor - ${it.vendor}")
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
sensorInfo.append("\n FifoMaxEventCount - ${it.fifoMaxEventCount}")
.append("\n FifoReservedEventCount - ${it.fifoReservedEventCount}")
}
sensorInfo.append("\n MaximumRange - ${it.maximumRange}")
.append("\n MinDelay - ${it.minDelay} microsecond")
.append("\n Power - ${it.power}")
.append("\n Resolution - ${it.resolution}")
}
return sensorInfo.toString()
}
}
|
apache-2.0
|
b11c8e95d26915666a13e2c093df83e4
| 38.813953 | 100 | 0.706386 | 4.557232 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/query/rest/debugger/MarkLogicDebugFrame.kt
|
1
|
2924
|
/*
* Copyright (C) 2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.marklogic.query.rest.debugger
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.text.nullize
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XNamedValue
import com.intellij.xdebugger.frame.XStackFrame
import uk.co.reecedunn.intellij.plugin.core.xml.dom.XmlElement
import uk.co.reecedunn.intellij.plugin.core.xml.dom.children
import uk.co.reecedunn.intellij.plugin.processor.debug.frame.ComputeChildren
import uk.co.reecedunn.intellij.plugin.processor.debug.frame.VirtualFileStackFrame
import uk.co.reecedunn.intellij.plugin.processor.debug.frame.addChildren
import uk.co.reecedunn.intellij.plugin.xpm.module.path.XpmModuleUri
class MarkLogicDebugFrame private constructor(private val frame: XmlElement) : ComputeChildren {
override fun computeChildren(node: XCompositeNode, evaluator: XDebuggerEvaluator?) {
node.addChildren(computeVariables("dbg:global-variables", "dbg:global-variable", evaluator), false)
node.addChildren(computeVariables("dbg:external-variables", "dbg:external-variable", evaluator), false)
node.addChildren(computeVariables("dbg:variables", "dbg:variable", evaluator), true)
}
private fun computeVariables(list: String, child: String, evaluator: XDebuggerEvaluator?): Sequence<XNamedValue> {
return frame.children(list).children(child).map { variable ->
MarkLogicVariable.create(variable, evaluator)
}
}
companion object {
fun create(frame: XmlElement, queryFile: VirtualFile, evaluator: XDebuggerEvaluator): XStackFrame {
val path = frame.child("dbg:uri")?.text()?.nullize()
val line = (frame.child("dbg:line")?.text()?.toIntOrNull() ?: 1) - 1
val column = frame.child("dbg:column")?.text()?.toIntOrNull() ?: 0
val context = frame.child("dbg:operation")?.text()?.nullize()
val children = MarkLogicDebugFrame(frame)
return when (path) {
null -> VirtualFileStackFrame(queryFile, line, column, context, children, evaluator)
else -> VirtualFileStackFrame(XpmModuleUri(queryFile, path), line, column, context, children, evaluator)
}
}
}
}
|
apache-2.0
|
b29f66b7b232f0bc0bdc21a4261e3443
| 50.298246 | 120 | 0.732558 | 4.306333 | false | false | false | false |
campos20/tnoodle
|
webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/wcif/model/result/MultiBldResult.kt
|
1
|
2183
|
package org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model.result
import kotlinx.serialization.Serializable
import org.worldcubeassociation.tnoodle.server.webscrambles.serial.DurationSecondsSerializer
import java.time.Duration
@Serializable
data class MultiBldResult(val solved: Int, val attempted: Int, val time: @Serializable(with = DurationSecondsSerializer::class) Duration) {
val unsolved: Int
get() = attempted - solved
val points: Int
get() = solved - unsolved
fun isDnf(): Boolean {
if (attempted == 2) {
return solved == 2 // 1/2 is not a valid result despite hitting the 50% mark.
}
return points >= 0
}
fun encodeToWCA(): String {
val dd = (MULTIBLD_NEW_BASE_VALUE - points).toString().padStart(2, PREFIX_MULTIBLD_FORMAT_NEW)
val mm = unsolved.toString().padStart(2, PREFIX_MULTIBLD_FORMAT_NEW)
val ttttt = time.seconds.toString().padStart(5, PREFIX_MULTIBLD_FORMAT_NEW)
return "${PREFIX_MULTIBLD_FORMAT_NEW}$dd$ttttt$mm"
}
companion object {
const val PREFIX_MULTIBLD_FORMAT_NEW = '0'
const val LENGTH_MULTIBLD_FORMAT_NEW = 10
private const val MULTIBLD_NEW_BASE_VALUE = 99
fun parse(encodedWcaValue: Int): MultiBldResult? {
val padded = encodedWcaValue.toString().padStart(LENGTH_MULTIBLD_FORMAT_NEW, PREFIX_MULTIBLD_FORMAT_NEW)
return parse(padded)
}
fun parse(encodedValue: String): MultiBldResult? {
if (!encodedValue.startsWith(PREFIX_MULTIBLD_FORMAT_NEW) || encodedValue.length != LENGTH_MULTIBLD_FORMAT_NEW) {
return null
}
val dd = encodedValue.substring(1, 3)
val ttttt = encodedValue.substring(3, 8)
val mm = encodedValue.substring(8, 10)
val duration = Duration.ofSeconds(ttttt.toLong())
val difference = MULTIBLD_NEW_BASE_VALUE - dd.toInt()
val missed = mm.toInt()
val solved = difference + missed
val attempted = solved + missed
return MultiBldResult(solved, attempted, duration)
}
}
}
|
gpl-3.0
|
dc41c25d7b253189ab1c3dba7a12f322
| 34.786885 | 139 | 0.644984 | 3.969091 | false | false | false | false |
jiaminglu/kotlin-native
|
backend.native/tests/external/codegen/box/casts/asSafeForConstants.kt
|
2
|
1147
|
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
fun box(): String {
if ((1 as? Int) == null) return "fail 1"
if ((1 as? Byte) != null) return "fail 2"
if ((1 as? Short) != null) return "fail 3"
if ((1 as? Long) != null) return "fail 4"
if ((1 as? Char) != null) return "fail 5"
if ((1 as? Double) != null) return "fail 6"
if ((1 as? Float) != null) return "fail 7"
if ((1.0 as? Int) != null) return "fail 11"
if ((1.0 as? Byte) != null) return "fail 12"
if ((1.0 as? Short) != null) return "fail 13"
if ((1.0 as? Long) != null) return "fail 14"
if ((1.0 as? Char) != null) return "fail 15"
if ((1.0 as? Double) == null) return "fail 16"
if ((1.0 as? Float) != null) return "fail 17"
if ((1f as? Int) != null) return "fail 21"
if ((1f as? Byte) != null) return "fail 22"
if ((1f as? Short) != null) return "fail 23"
if ((1f as? Long) != null) return "fail 24"
if ((1f as? Char) != null) return "fail 25"
if ((1f as? Double) != null) return "fail 26"
if ((1f as? Float) == null) return "fail 27"
return "OK"
}
|
apache-2.0
|
adf34cbd9897fe5c3e4e5f4b8ece148b
| 37.233333 | 72 | 0.551003 | 2.911168 | false | false | false | false |
apollostack/apollo-android
|
apollo-adapters/src/jsMain/kotlin/com/apollographql/apollo3/adapters/BigDecimal.kt
|
1
|
2437
|
package com.apollographql.apollo3.api
@JsModule("big.js")
@JsNonModule
internal external fun jsBig(raw: dynamic): Big
@JsName("Number")
internal external fun jsNumber(raw: dynamic): Number
internal external class Big {
fun plus(other: Big): Big
fun minus(other: Big): Big
fun times(other: Big): Big
fun div(other: Big): Big
fun cmp(other: Big): Int
fun eq(other: Big): Boolean
fun round(dp: Int, rm: Int): Big
}
actual class BigDecimal {
internal val raw: Big
internal constructor(raw: Big) {
this.raw = raw
}
constructor() : this(raw = jsBig(0))
actual constructor(strVal: String) : this(raw = jsBig(strVal))
actual constructor(doubleVal: Double) {
check(!doubleVal.isNaN() && !doubleVal.isInfinite())
raw = jsBig(doubleVal)
}
actual constructor(intVal: Int) : this(raw = jsBig(intVal))
// JS does not support 64-bit integer natively.
actual constructor(longVal: Long) : this(raw = jsBig(longVal.toString()))
actual fun add(augend: BigDecimal): BigDecimal = BigDecimal(raw = raw.plus(augend.raw))
actual fun subtract(subtrahend: BigDecimal): BigDecimal = BigDecimal(raw = raw.minus(subtrahend.raw))
actual fun multiply(multiplicand: BigDecimal): BigDecimal = BigDecimal(raw = raw.times(multiplicand.raw))
actual fun divide(divisor: BigDecimal): BigDecimal = BigDecimal(raw = raw.div(divisor.raw))
actual fun negate(): BigDecimal = BigDecimal().subtract(this)
actual fun signum(): Int {
return raw.cmp(jsBig(0))
}
fun toInt(): Int {
return jsNumber(raw).toInt()
}
fun toLong(): Long {
// JSNumber is double precision, so it cannot exactly represent 64-bit `Long`.
return toString().toLong()
}
fun toShort(): Short {
return jsNumber(raw).toShort()
}
fun toByte(): Byte {
return jsNumber(raw).toByte()
}
fun toChar(): Char {
return jsNumber(raw).toChar()
}
fun toDouble(): Double {
return jsNumber(raw).toDouble()
}
fun toFloat(): Float {
return jsNumber(raw).toFloat()
}
override fun equals(other: Any?): Boolean {
if (other is BigDecimal) {
return raw.eq(other.raw)
}
return false
}
override fun hashCode(): Int = raw.toString().hashCode()
override fun toString(): String = raw.toString()
}
actual fun BigDecimal.toNumber(): Number {
val rounded = raw.round(0, 0)
return if (raw.minus(rounded).eq(jsBig(0))) {
toLong()
} else {
toDouble()
}
}
|
mit
|
90d34047d69f2498b38b5c386191aa74
| 22.432692 | 107 | 0.670907 | 3.648204 | false | false | false | false |
stefanodacchille/calculator-kotlin-android
|
app/src/main/kotlin/com/stefanodacchille/playground/ReactiveModel.kt
|
1
|
5228
|
package com.stefanodacchille.playground
import rx.lang.kotlin.PublishSubject
class ReactiveModel {
companion object {
val actionSubject = PublishSubject<Action>()
val updateObservable = actionSubject.startWith(Action.ZERO)
.scan(State.initialState, { state, action ->
when (action) {
Action.ADD, Action.DIV, Action.MUL, Action.SUB -> applyBinaryOperation(action, state)
Action.EQUALS -> applyEquals(state)
Action.DECIMAL -> applyDecimal(state)
Action.NEGATE -> applyNegate(state)
Action.PERCENT -> applyPercent(state)
Action.CLEAR -> State.initialState
else -> applyDigit(action, state)
}
}).cache(1)
private fun applyDigit(action: Action, state: State): State {
when (state) {
is State.Init -> {
val newValue = if (state.displayNumber.value == "0") {
action.ordinal().toString()
} else {
state.displayNumber.value + action.ordinal().toString()
}
return state.copy(displayNumber = state.displayNumber.copy(value = newValue))
}
is State.Operation -> {
val newValue = if (state.displayNumber == DisplayNumber.zero) {
action.ordinal().toString()
} else {
state.displayNumber.value + action.ordinal().toString()
}
return state.copy(displayNumber = state.displayNumber.copy(value = newValue))
}
is State.Error ->
return State.Init(displayNumber = DisplayNumber.fromDecimal(action.ordinal().toDouble()))
else -> throw AssertionError("Unknown state $state")
}
}
private fun applyPercent(state: State?): State {
when (state) {
is State.Init -> {
val newPercent = state.displayNumber.percent + 1
return state.copy(displayNumber = state.displayNumber.copy(percent = newPercent))
}
is State.Operation -> {
val newPercent = state.displayNumber.percent + 1
return state.copy(displayNumber = state.displayNumber.copy(percent = newPercent))
}
is State.Error -> return state
else -> throw AssertionError("Unexpected state $state")
}
}
private fun applyBinaryOperation(a: Action, state: State): State {
when (state) {
is State.Init ->
return State.Operation(state.displayNumber.toDecimal(), a, DisplayNumber.zero)
is State.Operation -> {
try {
return state.copy(action = a, displayNumber = DisplayNumber.zero)
} catch (e: ArithmeticException) {
return State.nan
}
}
is State.Error -> return state
else -> throw AssertionError("Unexpected state $state")
}
}
private fun applyEquals(state: State): State {
when (state) {
is State.Operation -> {
val right = if (state.displayNumber == DisplayNumber.zero) {
state.latestRightOperand
} else {
state.displayNumber.toDecimal()
}
val result = executeBinaryOperation(state.left, state.action, right)
return state.copy(left = result, displayNumber = DisplayNumber.zero,
lastRightOperand = right)
}
else -> return state
}
}
private fun applyNegate(state: State?): State {
when (state) {
is State.Init ->
return State.Init(state.displayNumber.copy(negative = !state.displayNumber.negative))
is State.Operation -> {
val displayNumber = state.displayNumber.copy(negative = !state.displayNumber.negative)
return state.copy(left = state.left, action = state.action, displayNumber = displayNumber)
}
is State.Error -> return state
else -> throw AssertionError("Unexpected state $state")
}
}
private fun applyDecimal(state: State?): State {
fun isDecimal(n: DisplayNumber): Boolean {
return n.value.contains('.')
}
fun toDecimal(n: DisplayNumber): DisplayNumber {
if (isDecimal(n)) return n else return n.copy(value = n.value + ".")
}
when (state) {
is State.Init ->
return state.copy(toDecimal(state.displayNumber))
is State.Operation -> {
val displayNumber = toDecimal(state.displayNumber)
return state.copy(left = state.left, action = state.action, displayNumber = displayNumber)
}
is State.Error -> return state
else -> throw AssertionError("Unexpected state $state")
}
}
private fun executeBinaryOperation(left: Double, action: Action, right: Double): Double {
return toBinaryOperation(action) (left, right)
}
private fun toBinaryOperation(action: Action): (Double, Double) -> Double {
when (action) {
Action.ADD -> return { x: Double, y: Double -> x + y }
Action.SUB -> return { x: Double, y: Double -> x - y }
Action.DIV -> return { x: Double, y: Double -> x / y }
Action.MUL -> return { x: Double, y: Double -> x * y }
else -> throw AssertionError("Unknown binary action ${action.name()}")
}
}
}
}
|
mit
|
b3a8ac4088f5045a69097be7442ccb34
| 35.566434 | 100 | 0.599847 | 4.426757 | false | false | false | false |
kevinhinterlong/archwiki-viewer
|
app/src/main/java/com/jtmcn/archwiki/viewer/utils/SettingsUtils.kt
|
2
|
1422
|
package com.jtmcn.archwiki.viewer.utils
import android.content.Context
import android.content.SharedPreferences
import androidx.preference.PreferenceManager
import com.jtmcn.archwiki.viewer.Prefs
@Deprecated("Use getTextZoom", replaceWith = ReplaceWith("getTextZoom(this)"))
fun getTextSize(prefs: SharedPreferences): Int? {
if(!prefs.contains(Prefs.KEY_TEXT_SIZE)) {
return null
}
// https://stackoverflow.com/questions/11346916/listpreference-use-string-array-as-entry-and-integer-array-as-entry-values-does
// the value of this preference must be parsed as a string
val fontSizePref = prefs.getString(Prefs.KEY_TEXT_SIZE, "2")!!
return Integer.valueOf(fontSizePref)
}
@Deprecated("Use getTextZoom")
fun textSizeToTextZoom(fontSize: Int) = when(fontSize) {
0 -> 50
1 -> 75
2 -> 100
3 -> 150
4 -> 200
else -> 100
}
/**
* gets the [Prefs.KEY_TEXT_ZOOM] preference, and if needed migrates from [getTextSize=]
*/
fun getTextZoom(context: Context): Int {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val textSize = getTextSize(prefs)
if(textSize != null) {
val textZoom = textSizeToTextZoom(textSize)
prefs.edit()
.putInt(Prefs.KEY_TEXT_ZOOM, textZoom)
.remove(Prefs.KEY_TEXT_SIZE)
.apply()
return textZoom
}
return prefs.getInt(Prefs.KEY_TEXT_ZOOM, 100)
}
|
apache-2.0
|
4093fad98b1337d026d130c66e0b5a45
| 28.625 | 131 | 0.692686 | 3.822581 | false | false | false | false |
jainsahab/AndroidSnooper
|
Snooper/src/main/java/com/prateekj/snooper/customviews/DividerItemDecoration.kt
|
1
|
2504
|
package com.prateekj.snooper.customviews
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class DividerItemDecoration(context: Context, orientation: Int, drawableId: Int) :
RecyclerView.ItemDecoration() {
private val mDivider: Drawable? = ContextCompat.getDrawable(context, drawableId)
private var mOrientation: Int = 0
init {
setOrientation(orientation)
}
fun setOrientation(orientation: Int) {
require(!(orientation != HORIZONTAL && orientation != VERTICAL)) { "invalid orientation" }
mOrientation = orientation
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (mOrientation == VERTICAL) {
drawVertical(c, parent)
} else {
drawHorizontal(c, parent)
}
}
private fun drawVertical(c: Canvas, parent: RecyclerView) {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child
.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + mDivider!!.intrinsicHeight
mDivider.setBounds(left, top, right, bottom)
mDivider.draw(c)
}
}
private fun drawHorizontal(c: Canvas, parent: RecyclerView) {
val top = parent.paddingTop
val bottom = parent.height - parent.paddingBottom
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child
.layoutParams as RecyclerView.LayoutParams
val left = child.right + params.rightMargin
val right = left + mDivider!!.intrinsicHeight
mDivider.setBounds(left, top, right, bottom)
mDivider.draw(c)
}
}
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
if (mOrientation == VERTICAL) {
outRect.set(0, 0, 0, mDivider!!.intrinsicHeight)
} else {
outRect.set(0, 0, mDivider!!.intrinsicWidth, 0)
}
}
companion object {
const val HORIZONTAL = LinearLayoutManager.HORIZONTAL
const val VERTICAL = LinearLayoutManager.VERTICAL
}
}
|
apache-2.0
|
ff709d10da9791e1766611cf97eeadae
| 29.168675 | 94 | 0.706869 | 4.586081 | false | false | false | false |
Maccimo/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/WrapWithSafeLetCallFix.kt
|
2
|
6790
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.intentions.canBeReplacedWithInvokeCall
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullable
import org.jetbrains.kotlin.types.typeUtil.isNullabilityMismatch
class WrapWithSafeLetCallFix(
expression: KtExpression,
nullableExpression: KtExpression
) : KotlinQuickFixAction<KtExpression>(expression), HighPriorityAction {
private val nullableExpressionPointer = nullableExpression.createSmartPointer()
override fun getFamilyName() = text
override fun getText() = KotlinBundle.message("wrap.with.let.call")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val nullableExpression = nullableExpressionPointer.element ?: return
val qualifiedExpression = element.getQualifiedExpressionForSelector()
val receiverExpression = qualifiedExpression?.receiverExpression
val canBeReplacedWithInvokeCall = (nullableExpression.parent as? KtCallExpression)?.canBeReplacedWithInvokeCall() == true
val factory = KtPsiFactory(element)
val nullableText = if (receiverExpression != null && canBeReplacedWithInvokeCall) {
"${receiverExpression.text}${qualifiedExpression.operationSign.value}${nullableExpression.text}"
} else {
nullableExpression.text
}
val validator = Fe10KotlinNewDeclarationNameValidator(
element,
nullableExpression,
KotlinNameSuggestionProvider.ValidatorTarget.PARAMETER
)
val name = Fe10KotlinNameSuggester.suggestNameByName("it", validator)
nullableExpression.replace(factory.createExpression(name))
val underLetExpression = when {
receiverExpression != null && !canBeReplacedWithInvokeCall ->
factory.createExpressionByPattern("$0.$1", receiverExpression, element)
else -> element
}
val wrapped = when (name) {
"it" -> factory.createExpressionByPattern("($0)?.let { $1 }", nullableText, underLetExpression)
else -> factory.createExpressionByPattern("($0)?.let { $1 -> $2 }", nullableText, name, underLetExpression)
}
val replaced = (qualifiedExpression ?: element).replace(wrapped) as KtSafeQualifiedExpression
val receiver = replaced.receiverExpression
if (receiver is KtParenthesizedExpression && KtPsiUtil.areParenthesesUseless(receiver)) {
receiver.replace(KtPsiUtil.safeDeparenthesize(receiver))
}
}
object UnsafeFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = diagnostic.psiElement
if (element is KtNameReferenceExpression) {
val resolvedCall = element.resolveToCall()
if (resolvedCall?.call?.callType != Call.CallType.INVOKE) return null
}
val expression = element.getStrictParentOfType<KtExpression>() ?: return null
val (targetExpression, nullableExpression) = if (expression is KtQualifiedExpression) {
val argument = expression.parent as? KtValueArgument ?: return null
val call = argument.getStrictParentOfType<KtCallExpression>() ?: return null
val parameter = call.resolveToCall()?.getParameterForArgument(argument) ?: return null
if (parameter.type.isNullable()) return null
val targetExpression = call.getLastParentOfTypeInRow<KtQualifiedExpression>() ?: call
targetExpression to expression.receiverExpression
} else {
val nullableExpression = (element.parent as? KtCallExpression)?.calleeExpression ?: return null
expression to nullableExpression
}
return WrapWithSafeLetCallFix(targetExpression, nullableExpression)
}
}
object TypeMismatchFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = diagnostic.psiElement as? KtExpression ?: return null
val argument = element.parent as? KtValueArgument ?: return null
val call = argument.getParentOfType<KtCallExpression>(true) ?: return null
val expectedType: KotlinType
val actualType: KotlinType
when (diagnostic.factory) {
Errors.TYPE_MISMATCH -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH.cast(diagnostic)
expectedType = diagnosticWithParameters.a
actualType = diagnosticWithParameters.b
}
Errors.TYPE_MISMATCH_WARNING -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH_WARNING.cast(diagnostic)
expectedType = diagnosticWithParameters.a
actualType = diagnosticWithParameters.b
}
ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS -> {
val diagnosticWithParameters = ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS.cast(diagnostic)
expectedType = diagnosticWithParameters.a
actualType = diagnosticWithParameters.b
}
else -> return null
}
if (element.isNull() || !isNullabilityMismatch(expected = expectedType, actual = actualType)) return null
return WrapWithSafeLetCallFix(call.getLastParentOfTypeInRow<KtQualifiedExpression>() ?: call, element)
}
}
}
|
apache-2.0
|
8a2b2592ae372b8118a4c7d7a9c7d49c
| 52.896825 | 158 | 0.701031 | 5.998233 | false | false | false | false |
Maccimo/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ForEachParameterNotUsedInspection.kt
|
2
|
7048
|
// 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.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl.WithDestructuringDeclaration
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.refactoring.getThisLabelName
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
class ForEachParameterNotUsedInspection : AbstractKotlinInspection() {
companion object {
private const val FOREACH_NAME = "forEach"
private val COLLECTIONS_FOREACH_FQNAME = FqName("kotlin.collections.$FOREACH_NAME")
private val SEQUENCES_FOREACH_FQNAME = FqName("kotlin.sequences.$FOREACH_NAME")
private val TEXT_FOREACH_FQNAME = FqName("kotlin.text.$FOREACH_NAME")
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return callExpressionVisitor(fun(it: KtCallExpression) {
val calleeExpression = it.calleeExpression as? KtNameReferenceExpression
if (calleeExpression?.getReferencedName() != FOREACH_NAME) return
val lambda = it.lambdaArguments.singleOrNull()?.getLambdaExpression()
if (lambda == null || lambda.functionLiteral.arrow != null) return
val context = it.analyze()
when (it.getResolvedCall(context)?.resultingDescriptor?.fqNameOrNull()) {
COLLECTIONS_FOREACH_FQNAME, SEQUENCES_FOREACH_FQNAME, TEXT_FOREACH_FQNAME -> {
val descriptor = context[BindingContext.FUNCTION, lambda.functionLiteral] ?: return
val iterableParameter = descriptor.valueParameters.singleOrNull() ?: return
if (iterableParameter !is WithDestructuringDeclaration &&
!lambda.bodyExpression.usesDescriptor(iterableParameter, context)
) {
val fixes = mutableListOf<LocalQuickFix>()
if (it.parent is KtDotQualifiedExpression) {
fixes += ReplaceWithRepeatFix()
}
fixes += IntroduceAnonymousParameterFix()
holder.registerProblem(
calleeExpression,
KotlinBundle.message("loop.parameter.0.is.unused", iterableParameter.getThisLabelName()),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixes.toTypedArray()
)
}
}
}
})
}
private class IntroduceAnonymousParameterFix : LocalQuickFix {
override fun getFamilyName() = KotlinBundle.message("introduce.anonymous.parameter.fix.family.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val callExpression = descriptor.psiElement.parent as? KtCallExpression ?: return
val literal = callExpression.lambdaArguments.singleOrNull()?.getLambdaExpression()?.functionLiteral ?: return
val psiFactory = KtPsiFactory(project)
val newParameterList = psiFactory.createLambdaParameterList("_")
with(SpecifyExplicitLambdaSignatureIntention) {
literal.setParameterListIfAny(psiFactory, newParameterList)
}
}
}
private class ReplaceWithRepeatFix : LocalQuickFix {
override fun getFamilyName() = KotlinBundle.message("replace.with.repeat.fix.family.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val callExpression = descriptor.psiElement.parent as? KtCallExpression ?: return
val qualifiedExpression = callExpression.parent as? KtDotQualifiedExpression ?: return
val receiverExpression = qualifiedExpression.receiverExpression
val receiverClass =
receiverExpression.resolveToCall()?.resultingDescriptor?.returnType?.constructor?.declarationDescriptor as? ClassDescriptor
val collection = callExpression.builtIns.collection
val charSequence = callExpression.builtIns.charSequence
val sizeText = when {
receiverClass != null && DescriptorUtils.isSubclass(receiverClass, collection) -> "size"
receiverClass != null && DescriptorUtils.isSubclass(receiverClass, charSequence) -> "length"
else -> "count()"
}
val lambdaExpression = callExpression.lambdaArguments.singleOrNull()?.getArgumentExpression() ?: return
val replacement =
KtPsiFactory(project).createExpressionByPattern("repeat($0.$sizeText, $1)", receiverExpression, lambdaExpression)
val result = qualifiedExpression.replaced(replacement) as KtCallExpression
result.moveFunctionLiteralOutsideParentheses()
}
}
private fun KtBlockExpression?.usesDescriptor(descriptor: VariableDescriptor, context: BindingContext): Boolean {
if (this == null) return false
var used = false
acceptChildren(object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
if (!used) {
if (element.children.isNotEmpty()) {
element.acceptChildren(this)
} else {
val resolvedCall = element.getResolvedCall(context) ?: return
used = descriptor == when (resolvedCall) {
is VariableAsFunctionResolvedCall -> resolvedCall.variableCall.candidateDescriptor
else -> resolvedCall.candidateDescriptor
}
}
}
}
})
return used
}
}
|
apache-2.0
|
5b3cdbc101f803db322501edf755ab2b
| 53.643411 | 158 | 0.678065 | 6.034247 | false | false | false | false |
JetBrains/ideavim
|
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/mark/VimMarkConstants.kt
|
1
|
2035
|
/*
* 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.mark
object VimMarkConstants {
const val MARK_VISUAL_START = '<'
const val MARK_VISUAL_END = '>'
const val MARK_CHANGE_START = '['
const val MARK_CHANGE_END = ']'
const val MARK_CHANGE_POS = '.'
const val WR_GLOBAL_MARKS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const val WR_REGULAR_FILE_MARKS = "abcdefghijklmnopqrstuvwxyz"
/** Marks: abcdefghijklmnopqrstuvwxyz' */
const val WR_FILE_MARKS = "$WR_REGULAR_FILE_MARKS'"
const val RO_GLOBAL_MARKS = "0123456789"
const val RO_FILE_MARKS = ".[]<>^{}()"
const val DEL_CONTEXT_FILE_MARKS = ".^[]\""
/** Marks: .^[]"abcdefghijklmnopqrstuvwxyz */
const val DEL_FILE_MARKS = DEL_CONTEXT_FILE_MARKS + WR_REGULAR_FILE_MARKS
/** Marks: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ */
const val DEL_GLOBAL_MARKS = RO_GLOBAL_MARKS + WR_GLOBAL_MARKS
/** Marks: .^[]"abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ */
const val DEL_MARKS = DEL_FILE_MARKS + DEL_GLOBAL_MARKS
/** Marks: abcdefghijklmnopqrstuvwxyz'.^[]" */
const val SAVE_FILE_MARKS = WR_FILE_MARKS + DEL_CONTEXT_FILE_MARKS
/** Marks: ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 */
const val GLOBAL_MARKS = WR_GLOBAL_MARKS + RO_GLOBAL_MARKS
/** Marks: abcdefghijklmnopqrstuvwxyz'[]<>^{}() */
const val FILE_MARKS = WR_FILE_MARKS + RO_FILE_MARKS
/** Marks: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' */
const val WRITE_MARKS = WR_GLOBAL_MARKS + WR_FILE_MARKS
/** Marks: 0123456789.[]<>^{}() */
const val READONLY_MARKS = RO_GLOBAL_MARKS + RO_FILE_MARKS
/** Marks: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' */
const val VALID_SET_MARKS = WRITE_MARKS
/** Marks: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'0123456789.[]<>^{}() */
const val VALID_GET_MARKS = WRITE_MARKS + READONLY_MARKS
}
|
mit
|
ce1222e2376891c036213272442bb358
| 34.086207 | 90 | 0.70516 | 3.825188 | false | false | false | false |
peterholak/graphql-ws-kotlin
|
src/main/kotlin/net/holak/graphql/ws/DefaultSubscriptions.kt
|
1
|
5963
|
package net.holak.graphql.ws
import graphql.ErrorType
import graphql.GraphQLError
import graphql.execution.ValuesResolver
import graphql.language.Document
import graphql.language.Field
import graphql.language.OperationDefinition
import graphql.parser.Parser
import graphql.schema.GraphQLSchema
import graphql.validation.Validator
import mu.KLogging
import org.antlr.v4.runtime.misc.ParseCancellationException
import java.lang.IllegalArgumentException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentLinkedQueue
typealias Identifier<T> = Subscriptions.Identifier<T>
/**
* TODO: this is not currently thread safe
*
* Places the data directly into context when running the subscription "queries",
* which should probably be configurable.
*/
@Suppress("unused")
class DefaultSubscriptions<Client>(val schema: GraphQLSchema) : Subscriptions<Client> {
companion object: KLogging()
override val subscriptions = ConcurrentHashMap<String, ConcurrentLinkedQueue<Identifier<Client>>>()
override val subscriptionsByClient = ConcurrentHashMap<Client, ConcurrentHashMap<String, Subscription<Client>>>()
val listeners = mutableMapOf<String, MutableList<(start: Start) -> Unit>>()
override fun subscribe(client: Client, start: Start): List<GraphQLError>? {
try {
logger.debug { "Subscribe: id=${start.id} query=${start.payload.query}" }
val document = Parser().parseDocument(start.payload.query)
val errors = Validator().validateDocument(schema, document)
if (errors.isNotEmpty()) {
return errors
}
val id = Identifier(client, start.id)
val toNotify = subscriptionToNotify(document, schema, start.payload.operationName, start.payload.variables)
subscriptions
.getOrPut(toNotify.name, { ConcurrentLinkedQueue() })
.add(id)
subscriptionsByClient
.getOrPut(client, { ConcurrentHashMap() })
.put(start.id, Subscription(client, start, toNotify.name, toNotify.arguments))
listeners[toNotify.name]?.forEach { it(start) }
return null
}catch(e: ParseCancellationException) {
logger.error { "Error during subscription: $e" }
return listOf(SubscriptionDocumentError(e.message ?: e.javaClass.simpleName))
}catch(e: IllegalArgumentException) {
logger.error { "Error during subscription: $e" }
return listOf(SubscriptionDocumentError(e.message ?: e.javaClass.simpleName))
}catch(e: NotImplementedError) {
logger.error { "Error during subscription: $e" }
return listOf(SubscriptionDocumentError(e.message ?: e.javaClass.simpleName))
}
}
override fun unsubscribe(client: Client, subscriptionId: String) {
logger.debug { "Unsubscribe: id=$subscriptionId" }
val id = Identifier(client, subscriptionId)
val subscription = subscriptionsByClient[client]?.remove(subscriptionId) ?: throw NoSuchSubscriptionException("No such subscription.")
subscriptions[subscription.subscriptionName]?.remove(id)
}
override fun disconnected(client: Client) {
logger.debug { "Client with ${subscriptionsByClient[client]?.size ?: 0} subscriptions disconnected." }
val ids = subscriptionsByClient.remove(client) ?: return
ids.forEach { (subscriptionId, subscription) ->
subscriptions[subscription.subscriptionName]?.remove(Identifier(client, subscriptionId))
}
}
fun onSubscribed(name: String, function: (start: Start) -> Unit) {
listeners
.getOrPut(name, { mutableListOf() })
.add(function)
}
class ToNotify(val name: String, val arguments: JsonMap)
}
// TODO: a better way to obtain this information?
fun subscriptionToNotify(document: Document, schema: GraphQLSchema, operationName: String? = null, variables: JsonMap? = null): DefaultSubscriptions.ToNotify {
val definitions = document.definitions
val definition = when {
definitions.isEmpty() ->
throw IllegalArgumentException("Empty request.")
definitions.size > 1 && operationName == null ->
throw IllegalArgumentException("Must specify operation name.")
definitions.size == 1 && operationName == null ->
definitions[0]
else ->
definitions.find { (it as? OperationDefinition)?.name == operationName } ?:
throw IllegalArgumentException("Unable to find operation '$operationName'.")
} as? OperationDefinition ?: throw IllegalArgumentException("Not an operation.")
if (definition.operation != OperationDefinition.Operation.SUBSCRIPTION)
throw IllegalArgumentException("The operation is not a subscription.")
val subscription = definition.selectionSet.selections
.filterIsInstance<Field>()
.apply { if (size > 1) throw IllegalArgumentException("Subscriptions can only have a single root field") }
.first()
val subscriptionSchema = schema.subscriptionType.fieldDefinitions.find { it.name == subscription.name }
?: throw IllegalArgumentException("Subscription ${subscription.name} not found in schema.")
val resolver = ValuesResolver()
val variableValues: JsonMap = resolver.getVariableValues(schema, definition.variableDefinitions, variables)
val values: JsonMap = resolver.getArgumentValues(
subscriptionSchema.arguments,
subscription.arguments,
variableValues
)
return DefaultSubscriptions.ToNotify(subscription.name, values)
}
class SubscriptionDocumentError(private val description: String) : GraphQLError {
override fun getMessage() = description
override fun getErrorType() = ErrorType.ValidationError
override fun getLocations() = null
}
|
mit
|
7e80ce527604ba15e30e7366dac60015
| 42.210145 | 159 | 0.693443 | 5.114065 | false | false | false | false |
Hexworks/zircon
|
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/api/shape/FilledRectangleFactoryTest.kt
|
1
|
892
|
package org.hexworks.zircon.api.shape
import org.assertj.core.api.Assertions.assertThat
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.junit.Test
class FilledRectangleFactoryTest {
@Test
fun shouldProperlyFillRectangle() {
val result = FilledRectangleFactory.buildFilledRectangle(
topLeft = Position.offset1x1(),
size = Size.create(3, 3)
)
assertThat(result).containsExactly(
Position.create(x = 1, y = 1),
Position.create(x = 2, y = 1),
Position.create(x = 3, y = 1),
Position.create(x = 1, y = 2),
Position.create(x = 2, y = 2),
Position.create(x = 3, y = 2),
Position.create(x = 1, y = 3),
Position.create(x = 2, y = 3),
Position.create(x = 3, y = 3)
)
}
}
|
apache-2.0
|
78d09d735e1593c0a0c4fd6aade8f6f7
| 27.774194 | 65 | 0.576233 | 3.701245 | false | true | false | false |
JetBrains/ideavim
|
src/test/java/ui/pages/IdeaFrame.kt
|
1
|
1928
|
/*
* 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 ui.pages
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.data.RemoteComponent
import com.intellij.remoterobot.fixtures.CommonContainerFixture
import com.intellij.remoterobot.fixtures.DefaultXpath
import com.intellij.remoterobot.fixtures.FixtureName
import com.intellij.remoterobot.fixtures.JTreeFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.stepsProcessing.step
import com.intellij.remoterobot.utils.waitFor
import java.time.Duration
fun RemoteRobot.idea(function: IdeaFrame.() -> Unit) {
find<IdeaFrame>().apply(function)
}
@FixtureName("Idea frame")
@DefaultXpath("IdeFrameImpl type", "//div[@class='IdeFrameImpl']")
class IdeaFrame(
remoteRobot: RemoteRobot,
remoteComponent: RemoteComponent,
) : CommonContainerFixture(remoteRobot, remoteComponent) {
val projectViewTree
get() = find<JTreeFixture>(byXpath("ProjectViewTree", "//div[@class='ProjectViewTree']"), Duration.ofSeconds(10))
val projectName
get() = step("Get project name") { return@step callJs<String>("component.getProject().getName()") }
@JvmOverloads
fun dumbAware(timeout: Duration = Duration.ofMinutes(5), function: () -> Unit) {
step("Wait for smart mode") {
waitFor(duration = timeout, interval = Duration.ofSeconds(5)) {
runCatching { isDumbMode().not() }.getOrDefault(false)
}
function()
step("..wait for smart mode again") {
waitFor(duration = timeout, interval = Duration.ofSeconds(5)) {
isDumbMode().not()
}
}
}
}
private fun isDumbMode(): Boolean {
return callJs("com.intellij.openapi. project.DumbService.isDumb(component.project);", true)
}
}
|
mit
|
95349f1f8161053a7951f9814d7bfe10
| 32.824561 | 117 | 0.731846 | 4.07611 | false | false | false | false |
NCBSinfo/NCBSinfo
|
app/src/main/java/com/rohitsuratekar/NCBSinfo/adapters/InformationAdapter.kt
|
2
|
1783
|
package com.rohitsuratekar.NCBSinfo.adapters
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.rohitsuratekar.NCBSinfo.R
import com.rohitsuratekar.NCBSinfo.common.inflate
import com.rohitsuratekar.NCBSinfo.fragments.InformationFragment
class InformationAdapter(
private val infoList: List<InformationFragment.Information>,
private val listener: OnInfoClick
) : RecyclerView.Adapter<InformationAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(parent.inflate(R.layout.fragment_information_item))
}
override fun getItemCount(): Int {
return infoList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val info = infoList[position]
val context = holder.itemView.context
holder.apply {
title.text = context.getString(info.title)
details.text = context.getString(info.details)
image.setImageResource(info.image)
card.setOnClickListener { listener.sectionClicked(info.action) }
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var card: CardView = itemView.findViewById(R.id.info_card)
var image: ImageView = itemView.findViewById(R.id.info_card_image)
var title: TextView = itemView.findViewById(R.id.info_card_title)
var details: TextView = itemView.findViewById(R.id.info_card_details)
}
interface OnInfoClick {
fun sectionClicked(action: Int)
}
}
|
mit
|
67866b5b5bba0b9081a9f559c08eba98
| 33.7 | 83 | 0.710039 | 4.560102 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinFunctionDeclarationBodyFixer.kt
|
4
|
1732
|
// 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.editor.fixers
import com.intellij.lang.SmartEnterProcessorWithFixers
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class KotlinFunctionDeclarationBodyFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, psiElement: PsiElement) {
if (psiElement !is KtNamedFunction) return
if (psiElement.bodyExpression != null || psiElement.equalsToken != null) return
val parentDeclaration = psiElement.getStrictParentOfType<KtDeclaration>()
if (parentDeclaration is KtClassOrObject) {
if (KtPsiUtil.isTrait(parentDeclaration) || psiElement.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
return
}
}
val doc = editor.document
var endOffset = psiElement.range.end
if (psiElement.text?.last() == ';') {
doc.deleteString(endOffset - 1, endOffset)
endOffset--
}
// Insert '\n' to force a multiline body, otherwise there will be an empty body on one line and a caret on the next one.
doc.insertString(endOffset, "{\n}")
}
}
|
apache-2.0
|
111e20699bbd690bdefd45454dbfd78f
| 42.325 | 158 | 0.734988 | 4.851541 | false | false | false | false |
Abdel-RhmanAli/Inventory-App
|
app/src/main/java/com/example/android/inventory/presenter/ItemsActivityPresenter.kt
|
1
|
2460
|
package com.example.android.inventory.presenter
import android.support.design.widget.Snackbar
import android.support.v7.widget.helper.ItemTouchHelper
import com.example.android.inventory.R
import com.example.android.inventory.repository.ItemsViewModel
import com.example.android.inventory.ui.ItemsRecyclerViewAdapter
import com.example.android.inventory.ui.SwipeToDeleteCallBack
class ItemsActivityPresenter(
private val mRecyclerViewAdapter: ItemsRecyclerViewAdapter,
private val mViewModel: ItemsViewModel,
private val mView: View) {
fun confirmDeletion() {
mView.showAlertDialogue(mView.getString(R.string.delete_all_items), false) {
mRecyclerViewAdapter.removeAll()
this.showSnakeBar()
}
}
private fun showSnakeBar() {
mView.showSnakeBar(
text = mView.getString(R.string.all_items_deleted),
length = Snackbar.LENGTH_LONG,
callbackOnDismissed = { mViewModel.deleteAllItems() },
actionText = mView.getString(R.string.undo),
actionClickListener = { mRecyclerViewAdapter.setItems(mViewModel.getAllItems()?.value) }
)
}
fun createSwipeToDeleteCallback(): SwipeToDeleteCallBack {
return SwipeToDeleteCallBack(0, ItemTouchHelper.LEFT) { position ->
val item = mRecyclerViewAdapter.getItem(position)
item?.let {
mRecyclerViewAdapter.removeItem(position)
mView.showSnakeBar(
text = mView.getString(R.string.item_deleted),
length = Snackbar.LENGTH_LONG,
callbackOnDismissed = { mViewModel.deleteItem(it) },
actionText = mView.getString(R.string.undo),
actionClickListener = { mRecyclerViewAdapter.addItem(it, position) }
)
}
}
}
interface View {
fun showAlertDialogue(
message: String,
isCancellable: Boolean,
positiveButtonClickListener: () -> Unit)
fun showSnakeBar(
text: String,
length: Int,
callbackOnDismissed: () -> Unit,
actionText: String,
actionClickListener: () -> Unit
)
fun getString(id: Int): String
}
}
|
apache-2.0
|
168134f2e53d6971e19d7282c87b9d93
| 34.746269 | 104 | 0.595122 | 5.200846 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/AbstractSmartStepIntoTest.kt
|
2
|
3111
|
// 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.debugger.test
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import org.jetbrains.kotlin.idea.base.psi.getStartLineOffset
import org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto.KotlinSmartStepIntoHandler
import org.jetbrains.kotlin.idea.debugger.test.mock.MockSourcePosition
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
abstract class AbstractSmartStepIntoTest : KotlinLightCodeInsightFixtureTestCase() {
private val fixture: JavaCodeInsightTestFixture
get() = myFixture
protected open fun doTest(path: String) {
fixture.configureByFile(fileName())
val offset = fixture.caretOffset
val line = fixture.getDocument(fixture.file!!)!!.getLineNumber(offset)
val lineStart = getStartLineOffset(file, line)!!
val elementAtOffset = file.findElementAt(lineStart)
val position = MockSourcePosition(
myFile = fixture.file,
myLine = line,
myOffset = offset,
myEditor = fixture.editor,
myElementAt = elementAtOffset
)
val actual = KotlinSmartStepIntoHandler().findSmartStepTargets(position).map { it.presentation }
val expected = InTextDirectivesUtils.findListWithPrefixes(fixture.file?.text!!.replace("\\,", "+++"), "// EXISTS: ")
.map { it.replace("+++", ",") }
for (actualTargetName in actual) {
assert(actualTargetName in expected) {
"Unexpected step into target was found: $actualTargetName\n${renderTableWithResults(expected, actual)}" +
"\n // EXISTS: ${actual.joinToString()}"
}
}
for (expectedTargetName in expected) {
assert(expectedTargetName in actual) {
"Missed step into target: $expectedTargetName\n${renderTableWithResults(expected, actual)}" +
"\n // EXISTS: ${actual.joinToString()}"
}
}
}
private fun renderTableWithResults(expected: List<String>, actual: List<String>): String {
val sb = StringBuilder()
val maxExtStrSize = (expected.maxOfOrNull { it.length } ?: 0) + 5
val longerList = (if (expected.size < actual.size) actual else expected).sorted()
val shorterList = (if (expected.size < actual.size) expected else actual).sorted()
for ((i, element) in longerList.withIndex()) {
sb.append(element)
sb.append(" ".repeat(maxExtStrSize - element.length))
if (i < shorterList.size) sb.append(shorterList[i])
sb.append("\n")
}
return sb.toString()
}
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance()
}
|
apache-2.0
|
5fefa9a72d29440ddfa9cb21709baf5b
| 42.816901 | 158 | 0.67406 | 4.961722 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/AssignmentExpressionUnfoldingConversion.kt
|
2
|
7498
|
// 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.nj2k.conversions
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase
import org.jetbrains.kotlin.nj2k.blockStatement
import org.jetbrains.kotlin.nj2k.parenthesizeIfCompoundExpression
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AssignmentExpressionUnfoldingConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
val unfolded = when (element) {
is JKBlock -> element.convertAssignments()
is JKExpressionStatement -> element.convertAssignments()
is JKJavaAssignmentExpression -> element.convertAssignments()
else -> null
} ?: return recurse(element)
return recurse(unfolded)
}
private fun JKBlock.convertAssignments(): JKBlock? {
val hasAssignments = statements.any { it.containsAssignment() }
if (!hasAssignments) return null
val newStatements = mutableListOf<JKStatement>()
for (statement in statements) {
when {
statement is JKExpressionStatement && statement.expression is JKJavaAssignmentExpression -> {
val assignment = statement.expression as JKJavaAssignmentExpression
newStatements += assignment
.unfoldToStatementsList(assignmentTarget = null)
.withFormattingFrom(statement)
}
statement is JKDeclarationStatement && statement.containsAssignment() -> {
val variable = statement.declaredStatements.single() as JKVariable
val assignment = variable.initializer as JKJavaAssignmentExpression
newStatements += assignment
.unfoldToStatementsList(variable.detached(statement))
.withFormattingFrom(statement)
}
else -> {
newStatements += statement
}
}
}
statements = newStatements
return this
}
private fun JKExpressionStatement.convertAssignments(): JKStatement? {
val assignment = expression as? JKJavaAssignmentExpression ?: return null
return when {
canBeConvertedToBlock() && assignment.expression is JKJavaAssignmentExpression ->
blockStatement(assignment.unfoldToStatementsList(assignmentTarget = null))
else -> createKtAssignmentStatement(
assignment::field.detached(),
assignment::expression.detached(),
assignment.operator
)
}.withFormattingFrom(this)
}
private fun JKExpressionStatement.canBeConvertedToBlock() = when (val parent = parent) {
is JKLoopStatement -> parent.body == this
is JKIfElseStatement -> parent.thenBranch == this || parent.elseBranch == this
is JKJavaSwitchCase -> true
else -> false
}
private fun JKJavaAssignmentExpression.convertAssignments() =
unfoldToExpressionsChain().withFormattingFrom(this)
private fun JKDeclarationStatement.containsAssignment() =
declaredStatements.singleOrNull()?.safeAs<JKVariable>()?.initializer is JKJavaAssignmentExpression
private fun JKStatement.containsAssignment() = when (this) {
is JKExpressionStatement -> expression is JKJavaAssignmentExpression
is JKDeclarationStatement -> containsAssignment()
else -> false
}
private fun JKJavaAssignmentExpression.unfold() = generateSequence(this) { assignment ->
assignment.expression as? JKJavaAssignmentExpression
}.toList().asReversed()
private fun JKJavaAssignmentExpression.unfoldToExpressionsChain(): JKExpression {
val links = unfold()
val first = links.first()
return links.subList(1, links.size)
.fold(first.toExpressionChainLink(first::expression.detached())) { state, assignment ->
assignment.toExpressionChainLink(state)
}
}
private fun JKJavaAssignmentExpression.unfoldToStatementsList(assignmentTarget: JKVariable?): List<JKStatement> {
val links = unfold()
val first = links.first()
val statements = links.subList(1, links.size)
.foldIndexed(listOf(first.toDeclarationChainLink(first::expression.detached()))) { index, list, assignment ->
list + assignment.toDeclarationChainLink(links[index].field.copyTreeAndDetach())
}
return when (assignmentTarget) {
null -> statements
else -> {
assignmentTarget.initializer = statements.last().field.copyTreeAndDetach()
statements + JKDeclarationStatement(listOf(assignmentTarget))
}
}
}
private fun JKJavaAssignmentExpression.toExpressionChainLink(receiver: JKExpression): JKExpression {
val assignment = createKtAssignmentStatement(
this::field.detached(),
JKKtItExpression(operator.returnType),
operator
).withFormattingFrom(this)
return when {
operator.isSimpleToken() ->
JKAssignmentChainAlsoLink(receiver, assignment, field.copyTreeAndDetach())
else ->
JKAssignmentChainLetLink(receiver, assignment, field.copyTreeAndDetach())
}
}
private fun JKJavaAssignmentExpression.toDeclarationChainLink(expression: JKExpression) =
createKtAssignmentStatement(this::field.detached(), expression, this.operator)
.withFormattingFrom(this)
private fun createKtAssignmentStatement(
field: JKExpression,
expression: JKExpression,
operator: JKOperator
) = when {
operator.isOnlyJavaToken() ->
JKKtAssignmentStatement(
field,
JKBinaryExpression(
field.copyTreeAndDetach(),
expression.parenthesizeIfCompoundExpression(),
JKKtOperatorImpl(
onlyJavaAssignTokensToKotlinOnes[operator.token]!!,
operator.returnType
)
),
JKOperatorToken.EQ
)
else -> JKKtAssignmentStatement(field, expression, operator.token)
}
private fun JKOperator.isSimpleToken() = when {
isOnlyJavaToken() -> false
token == JKOperatorToken.PLUSEQ
|| token == JKOperatorToken.MINUSEQ
|| token == JKOperatorToken.MULTEQ
|| token == JKOperatorToken.DIVEQ -> false
else -> true
}
private fun JKOperator.isOnlyJavaToken() = token in onlyJavaAssignTokensToKotlinOnes
companion object {
private val onlyJavaAssignTokensToKotlinOnes = mapOf(
JKOperatorToken.ANDEQ to JKOperatorToken.AND,
JKOperatorToken.OREQ to JKOperatorToken.OR,
JKOperatorToken.XOREQ to JKOperatorToken.XOR,
JKOperatorToken.LTLTEQ to JKOperatorToken.SHL,
JKOperatorToken.GTGTEQ to JKOperatorToken.SHR,
JKOperatorToken.GTGTGTEQ to JKOperatorToken.USHR
)
}
}
|
apache-2.0
|
a19026c7c0d18c9a63906e0a4fe17e8b
| 40.430939 | 125 | 0.647506 | 6.155993 | false | false | false | false |
GunoH/intellij-community
|
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/MutableEntityCollectionTest.kt
|
2
|
12259
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage
import com.intellij.testFramework.ApplicationRule
import com.intellij.workspaceModel.storage.entities.test.api.*
import com.intellij.workspaceModel.storage.impl.MutableEntityStorageImpl
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceSet
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
class MutableEntityCollectionTest {
private lateinit var virtualFileManager: VirtualFileUrlManager
@Rule
@JvmField
var application = ApplicationRule()
@Before
fun setUp() {
virtualFileManager = VirtualFileUrlManagerImpl()
}
@Test
fun `check vfu list basic operations`() {
val fileUrlList = listOf("/user/a.txt", "/user/opt/app/a.txt", "/user/opt/app/b.txt")
val builder = createEmptyBuilder()
builder.addListVFUEntity("hello", fileUrlList, virtualFileManager)
makeOperationOnListAndCheck(builder, "/user/b.txt") { entity, vfu ->
entity.fileProperty.add(vfu.single())
}
makeOperationOnListAndCheck(builder, "/user/c.txt") { entity, vfu ->
entity.fileProperty.add(3, vfu.single())
}
makeOperationOnListAndCheck(builder, "/user/d.txt", "/user/e.txt") { entity, vfu ->
entity.fileProperty.addAll(vfu)
}
makeOperationOnListAndCheck(builder, "/user/f.txt", "/user/g.txt") { entity, vfu ->
entity.fileProperty.addAll(2, vfu)
}
makeOperationOnListAndCheck(builder, "/user/b.txt", removeOperation = true) { entity, vfu ->
entity.fileProperty.remove(vfu.single())
}
makeOperationOnListAndCheck(builder, "/user/d.txt", "/user/e.txt", removeOperation = true) { entity, vfu ->
entity.fileProperty.removeAll(vfu)
}
val entity = builder.entities(ListVFUEntity::class.java).single()
makeOperationOnListAndCheck(builder, entity.fileProperty[3].url, removeOperation = true) { entity, vfu ->
entity.fileProperty.removeAt(3)
}
makeOperationOnListAndCheck(builder, "/user/foo.txt") { entity, vfu ->
entity.fileProperty[3] = vfu.single()
}
makeOperationOnListAndCheck(builder, "/user/foo.txt", removeOperation = true) { entity, vfu ->
entity.fileProperty.removeIf{ it == vfu.single() }
}
makeOperationOnListAndCheck(builder, "/user/opt/app/a.txt", removeOperation = true) { entity, vfu ->
entity.fileProperty.removeAll { vfu.contains(it) }
}
makeReplaceOnListOperationAndCheck(builder, listOf("/user/a.txt", "/user/f.txt"), listOf("/user/c.txt")) { entity, vfu ->
entity.fileProperty.retainAll(listOf(virtualFileManager.fromUrl ("/user/c.txt")))
}
makeReplaceOnListOperationAndCheck(builder, listOf("/user/c.txt"), listOf("/user/e.txt")) { entity, vfu ->
entity.fileProperty.replaceAll {
if (it == vfu.single()) virtualFileManager.fromUrl("/user/e.txt") else it
}
}
makeOperationOnListAndCheck(builder, "/user/d.txt", "/user/f.txt", "/user/g.txt") { entity, vfu ->
val listIterator = entity.fileProperty.listIterator()
vfu.forEach { listIterator.add(it) }
}
makeReplaceOnListOperationAndCheck(builder, listOf("/user/d.txt"), listOf("/user/k.txt")) { entity, vfu ->
val listIterator = entity.fileProperty.listIterator()
while (listIterator.hasNext()) {
val element = listIterator.next()
if (element == vfu.single()) listIterator.set(virtualFileManager.fromUrl("/user/k.txt"))
}
}
makeOperationOnListAndCheck(builder, "/user/k.txt", removeOperation = true) { entity, vfu ->
val listIterator = entity.fileProperty.listIterator()
while (listIterator.hasNext()) {
val element = listIterator.next()
if (element == vfu.single()) listIterator.remove()
}
}
makeOperationOnListAndCheck(builder, "/user/g.txt", removeOperation = true) { entity, vfu ->
val listIterator = entity.fileProperty.iterator()
while (listIterator.hasNext()) {
val element = listIterator.next()
if (element == vfu.single()) listIterator.remove()
}
}
makeOperationOnListAndCheck(builder, "/user/e.txt", "/user/f.txt", removeOperation = true) { entity, vfu ->
entity.fileProperty.clear()
}
}
@Test
fun `check vfu set basic operations`() {
val vfuSet = listOf("/user/a.txt", "/user/b.txt", "/user/c.txt", "/user/opt/app/a.txt").map { virtualFileManager.fromUrl(it) }.toSet()
val builder = createEmptyBuilder()
builder.addEntity(SetVFUEntity("hello", vfuSet, SampleEntitySource("test")))
makeOperationOnSetAndCheck(builder, "/user/d.txt") { entity, vfu ->
entity.fileProperty.add(vfu.single())
}
makeOperationOnSetAndCheck(builder, "/user/f.txt", "/user/e.txt") { entity, vfu ->
entity.fileProperty.addAll(vfu)
}
makeOperationOnSetAndCheck(builder, "/user/d.txt", removeOperation = true) { entity, vfu ->
entity.fileProperty.remove(vfu.single())
}
makeOperationOnSetAndCheck(builder, "/user/f.txt", "/user/e.txt", removeOperation = true) { entity, vfu ->
entity.fileProperty.removeAll(vfu)
}
makeOperationOnSetAndCheck(builder, "/user/a.txt", removeOperation = true) { entity, vfu ->
entity.fileProperty.removeIf { it == vfu.single() }
}
// TODO:: Not supported
//makeOperationOnSetAndCheck(builder, "/user/opt/app/a.txt", removeOperation = true) { entity, vfu ->
// entity.fileProperty.removeAll { vfu.contains(it) }
//}
makeReplaceOnSetOperationAndCheck(builder, listOf("/user/b.txt", "/user/opt/app/a.txt"), listOf("/user/c.txt")) { entity, vfu ->
entity.fileProperty.retainAll(listOf(virtualFileManager.fromUrl ("/user/c.txt")))
}
// TODO:: Not supported
//makeOperationOnSetAndCheck(builder, "/user/c.txt", removeOperation = true) { entity, vfu ->
// val listIterator = entity.fileProperty.iterator()
// while (listIterator.hasNext()) {
// val element = listIterator.next()
// if (element == vfu.single()) listIterator.remove()
// }
//}
makeOperationOnSetAndCheck(builder, "/user/f.txt", "/user/e.txt") { entity, vfu ->
entity.fileProperty.addAll(vfu)
}
makeOperationOnSetAndCheck(builder, "/user/e.txt", "/user/f.txt", "/user/c.txt", removeOperation = true) { entity, vfu ->
entity.fileProperty.clear()
}
}
private fun makeOperationOnSetAndCheck(builder: MutableEntityStorageImpl, vararg urls: String, removeOperation: Boolean = false,
operation: (SetVFUEntity.Builder, Set<VirtualFileUrl>) -> Unit) {
val entity = builder.entities(SetVFUEntity::class.java).single()
val vfuForAction = urls.map { virtualFileManager.fromUrl(it) }.toSet()
var virtualFiles = builder.indexes.virtualFileIndex.getVirtualFiles((entity as WorkspaceEntityBase).id)
if (removeOperation) vfuForAction.forEach { assertTrue(virtualFiles.contains(it)) }
builder.modifyEntity(entity) {
operation(this, vfuForAction)
}
virtualFiles = builder.indexes.virtualFileIndex.getVirtualFiles((entity as WorkspaceEntityBase).id)
vfuForAction.forEach {
if (removeOperation) {
assertFalse(virtualFiles.contains(it))
} else {
assertTrue(virtualFiles.contains(it))
}
}
}
@Test(expected = IllegalStateException::class)
fun `collection modification allowed only in modifyEntity block`() {
val vfuSet = listOf("/user/a.txt", "/user/b.txt", "/user/c.txt", "/user/opt/app/a.txt").map { virtualFileManager.fromUrl(it) }.toSet()
val builder = createEmptyBuilder()
builder.addEntity(SetVFUEntity("hello", vfuSet, SampleEntitySource("test")))
val entity = builder.entities(SetVFUEntity::class.java).first()
entity as SetVFUEntityImpl.Builder
entity.fileProperty.remove(entity.fileProperty.first())
}
@Test
fun `check lambda is available only in certain places`() {
val vfuSet = listOf("/user/a.txt", "/user/b.txt", "/user/c.txt", "/user/opt/app/a.txt").map { virtualFileManager.fromUrl(it) }.toSet()
val builder = createEmptyBuilder()
val entity = SetVFUEntity("hello", vfuSet, SampleEntitySource("test"))
assertNotNull((entity.fileProperty as MutableWorkspaceSet).getModificationUpdateAction())
(entity.fileProperty as MutableWorkspaceSet).remove(entity.fileProperty.first())
builder.addEntity(entity)
var existingEntity = builder.entities(SetVFUEntity::class.java).first()
assertNull((existingEntity.fileProperty as MutableWorkspaceSet).getModificationUpdateAction())
builder.modifyEntity(existingEntity) {
assertNotNull((this.fileProperty as MutableWorkspaceSet).getModificationUpdateAction())
}
assertNull((existingEntity.fileProperty as MutableWorkspaceSet).getModificationUpdateAction())
existingEntity = builder.entities(SetVFUEntity::class.java).first()
assertNull((existingEntity.fileProperty as MutableWorkspaceSet).getModificationUpdateAction())
}
private fun makeReplaceOnSetOperationAndCheck(builder: MutableEntityStorageImpl, oldUrls: List<String>, newUrls: List<String>,
operation: (SetVFUEntity.Builder, Set<VirtualFileUrl>) -> Unit) {
val entity = builder.entities(SetVFUEntity::class.java).single()
val vfuForAction = oldUrls.map { virtualFileManager.fromUrl(it) }.toSet()
var virtualFiles = builder.indexes.virtualFileIndex.getVirtualFiles((entity as WorkspaceEntityBase).id)
vfuForAction.forEach { assertTrue(virtualFiles.contains(it)) }
builder.modifyEntity(entity) {
operation(this, vfuForAction)
}
virtualFiles = builder.indexes.virtualFileIndex.getVirtualFiles((entity as WorkspaceEntityBase).id)
vfuForAction.forEach { assertFalse(virtualFiles.contains(it)) }
newUrls.map { virtualFileManager.fromUrl(it) }.forEach { assertTrue(virtualFiles.contains(it)) }
}
private fun makeOperationOnListAndCheck(builder: MutableEntityStorageImpl, vararg urls: String, removeOperation: Boolean = false,
operation: (ListVFUEntity.Builder, List<VirtualFileUrl>) -> Unit) {
val entity = builder.entities(ListVFUEntity::class.java).single()
val vfuForAction = urls.map { virtualFileManager.fromUrl(it) }
var virtualFiles = builder.indexes.virtualFileIndex.getVirtualFiles((entity as WorkspaceEntityBase).id)
if (removeOperation) vfuForAction.forEach { assertTrue(virtualFiles.contains(it)) }
builder.modifyEntity(entity) {
operation(this, vfuForAction)
}
virtualFiles = builder.indexes.virtualFileIndex.getVirtualFiles((entity as WorkspaceEntityBase).id)
vfuForAction.forEach {
if (removeOperation) {
assertFalse(virtualFiles.contains(it))
} else {
assertTrue(virtualFiles.contains(it))
}
}
}
private fun makeReplaceOnListOperationAndCheck(builder: MutableEntityStorageImpl, oldUrls: List<String>, newUrls: List<String>,
operation: (ListVFUEntity.Builder, List<VirtualFileUrl>) -> Unit) {
val entity = builder.entities(ListVFUEntity::class.java).single()
val vfuForAction = oldUrls.map { virtualFileManager.fromUrl(it) }
var virtualFiles = builder.indexes.virtualFileIndex.getVirtualFiles((entity as WorkspaceEntityBase).id)
vfuForAction.forEach { assertTrue(virtualFiles.contains(it)) }
builder.modifyEntity(entity) {
operation(this, vfuForAction)
}
virtualFiles = builder.indexes.virtualFileIndex.getVirtualFiles((entity as WorkspaceEntityBase).id)
vfuForAction.forEach { assertFalse(virtualFiles.contains(it)) }
newUrls.map { virtualFileManager.fromUrl(it) }.forEach { assertTrue(virtualFiles.contains(it)) }
}
}
|
apache-2.0
|
543b8d5a57f9d2ed2d89324a2c4adb66
| 42.629893 | 138 | 0.705359 | 4.311994 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/top-mpp/src/jsJvm18iOSMain/kotlin/transitiveStory/bottomActual/mppBeginning/BottomActualDeclarations.kt
|
8
|
737
|
package transitiveStory.bottomActual.mppBeginning
actual open class <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'"), LINE_MARKER("descr='Has subclasses'")!>BottomActualDeclarations<!> {
actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>simpleVal<!>: Int = commonInt
actual companion object <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>Compainon<!> {
actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>inTheCompanionOfBottomActualDeclarations<!>: String =
"I'm a string from the companion object of `$this` in `$sourceSetName` module `$moduleName`"
}
}
|
apache-2.0
|
0822ca40e4173b72c26df15bd8d6a205
| 72.7 | 167 | 0.7327 | 4.211429 | false | false | false | false |
GunoH/intellij-community
|
plugins/git4idea/src/git4idea/GitRefreshUsageCollector.kt
|
8
|
1654
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.project.Project
class GitRefreshUsageCollector : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
private val GROUP: EventLogGroup = EventLogGroup("git.status.refresh", 1)
private val IS_FULL_REFRESH_FIELD = EventFields.Boolean("is_full_refresh")
private val STATUS_REFRESH = GROUP.registerIdeActivity(activityName = "status.refresh",
startEventAdditionalFields = arrayOf(IS_FULL_REFRESH_FIELD))
private val UNTRACKED_REFRESH = GROUP.registerIdeActivity(activityName = "untracked.refresh",
startEventAdditionalFields = arrayOf(IS_FULL_REFRESH_FIELD))
@JvmStatic
fun logStatusRefresh(project: Project, everythingDirty: Boolean): StructuredIdeActivity {
return STATUS_REFRESH.started(project) {
listOf(IS_FULL_REFRESH_FIELD.with(everythingDirty))
}
}
@JvmStatic
fun logUntrackedRefresh(project: Project, everythingDirty: Boolean): StructuredIdeActivity {
return UNTRACKED_REFRESH.started(project) {
listOf(IS_FULL_REFRESH_FIELD.with(everythingDirty))
}
}
}
}
|
apache-2.0
|
f68ff9f91529bccf5a0e0af6048e7d8c
| 44.972222 | 122 | 0.720073 | 4.966967 | false | false | false | false |
ktorio/ktor
|
ktor-client/ktor-client-darwin-legacy/darwin/src/io/ktor/client/engine/darwin/certificates/LegacyPinnedCertificate.kt
|
1
|
3965
|
/*
* 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.client.engine.darwin.certificates
import io.ktor.client.engine.darwin.certificates.LegacyCertificatePinner.*
import io.ktor.client.engine.darwin.certificates.LegacyCertificatesInfo.HASH_ALGORITHM_SHA_1
import io.ktor.client.engine.darwin.certificates.LegacyCertificatesInfo.HASH_ALGORITHM_SHA_256
/**
* Represents a pinned certificate. Recommended using [Builder.add] to construct
* [LegacyCertificatePinner]
*/
public data class LegacyPinnedCertificate(
/**
* A hostname like `example.com` or a pattern like `*.example.com` (canonical form).
*/
private val pattern: String,
/**
* Either `sha1/` or `sha256/`.
*/
val hashAlgorithm: String,
/**
* The hash of the pinned certificate using [hashAlgorithm].
*/
val hash: String
) {
/**
* Checks whether the given [hostname] matches the [pattern] of this [LegacyPinnedCertificate]
* @param hostname The hostname to check
* @return Boolean TRUE if it matches
*/
internal fun matches(hostname: String): Boolean = when {
pattern.startsWith("**.") -> {
// With ** empty prefixes match so exclude the dot from regionMatches().
val suffixLength = pattern.length - 3
val prefixLength = hostname.length - suffixLength
hostname.regionMatches(
thisOffset = hostname.length - suffixLength,
other = pattern,
otherOffset = 3,
length = suffixLength
) && (prefixLength == 0 || hostname[prefixLength - 1] == '.')
}
pattern.startsWith("*.") -> {
// With * there must be a prefix so include the dot in regionMatches().
val suffixLength = pattern.length - 1
val prefixLength = hostname.length - suffixLength
hostname.regionMatches(
thisOffset = hostname.length - suffixLength,
other = pattern,
otherOffset = 1,
length = suffixLength
) && hostname.lastIndexOf('.', prefixLength - 1) == -1
}
else -> hostname == pattern
}
override fun toString(): String = hashAlgorithm + hash
public companion object {
/**
* Create a new Pin
* @param pattern The hostname pattern
* @param pin The hash to pin
* @return [LegacyPinnedCertificate] The new pin
*/
public fun new(pattern: String, pin: String): LegacyPinnedCertificate {
require(
pattern.startsWith("*.") && pattern.indexOf("*", 1) == -1 ||
pattern.startsWith("**.") && pattern.indexOf("*", 2) == -1 ||
pattern.indexOf("*") == -1
) {
"Unexpected pattern: $pattern"
}
val canonicalPattern = pattern.lowercase()
return when {
pin.startsWith(HASH_ALGORITHM_SHA_1) -> {
val hash = pin.substring(HASH_ALGORITHM_SHA_1.length)
LegacyPinnedCertificate(
pattern = canonicalPattern,
hashAlgorithm = HASH_ALGORITHM_SHA_1,
hash = hash
)
}
pin.startsWith(HASH_ALGORITHM_SHA_256) -> {
val hash = pin.substring(HASH_ALGORITHM_SHA_256.length)
LegacyPinnedCertificate(
pattern = canonicalPattern,
hashAlgorithm = HASH_ALGORITHM_SHA_256,
hash = hash
)
}
else -> throw IllegalArgumentException(
"Pins must start with '$HASH_ALGORITHM_SHA_256' or '$HASH_ALGORITHM_SHA_1': $pin"
)
}
}
}
}
|
apache-2.0
|
70afaefe3b3e48fa334a49f91246edab
| 38.257426 | 118 | 0.555359 | 5.083333 | false | false | false | false |
abertschi/ad-free
|
app/src/main/java/ch/abertschi/adfree/detector/SpLiteTextDetector.kt
|
1
|
979
|
package ch.abertschi.adfree.detector
import org.jetbrains.anko.AnkoLogger
open class SpLiteTextDetector : AdDetectable, AnkoLogger, AbstractNotificationBundleAndroidTextDetector() {
override fun getPackageName() = "com.spotify.lite"
override fun detectAsAdvertisement(
payload: AdPayload,
title: Pair<String?, Boolean>,
text: Pair<String?, Boolean>,
subtext: Pair<String?, Boolean>
): Boolean {
if (listOf(title.second, text.second, subtext.second).contains(false)) {
return false
}
// title first is advertisement in english version
return title.first != null && title.first!!.isNotEmpty()
&& text.first == null && subtext.first != null
}
override fun getMeta(): AdDetectorMeta = AdDetectorMeta(
"Generic Text detector", "detector for presence of text for spotify lite",
true,
category = "Spotify Lite",
debugOnly = false
)
}
|
apache-2.0
|
5f658e23d10333dbb1587f0382f52390
| 32.793103 | 107 | 0.649642 | 4.574766 | false | false | false | false |
ktorio/ktor
|
ktor-server/ktor-server-plugins/ktor-server-freemarker/jvm/src/io/ktor/server/freemarker/FreeMarker.kt
|
1
|
1828
|
/*
* 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.freemarker
import freemarker.template.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import java.io.*
/**
* A response content handled by the [FreeMarker] plugin.
*
* @param template name that is resolved by FreeMarker
* @param model to be passed during template rendering
* @param etag value for the `E-Tag` header (optional)
* @param contentType of response (optional, `text/html` with the UTF-8 character encoding by default)
*/
public class FreeMarkerContent(
public val template: String,
public val model: Any?,
public val etag: String? = null,
public val contentType: ContentType = ContentType.Text.Html.withCharset(Charsets.UTF_8)
)
/**
* A plugin that allows you to use FreeMarker templates as views within your application.
* Provides the ability to respond with [FreeMarkerContent].
* You can learn more from [FreeMarker](https://ktor.io/docs/freemarker.html).
*/
public val FreeMarker: ApplicationPlugin<Configuration> = createApplicationPlugin(
"FreeMarker",
{ Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS) }
) {
fun process(content: FreeMarkerContent): OutgoingContent = with(content) {
val writer = StringWriter()
pluginConfig.getTemplate(content.template).process(model, writer)
val result = TextContent(text = writer.toString(), contentType)
if (etag != null) {
result.versions += EntityTagVersion(etag)
}
return result
}
onCallRespond { _, message ->
if (message is FreeMarkerContent) {
transformBody {
process(message)
}
}
}
}
|
apache-2.0
|
2a4a434f9f2036b08adafba05081e2b6
| 32.236364 | 119 | 0.695295 | 4.192661 | false | true | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryController.kt
|
1
|
20931
|
package eu.kanade.tachiyomi.ui.library
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.appcompat.view.ActionMode
import androidx.core.view.doOnAttach
import androidx.core.view.isVisible
import com.bluelinelabs.conductor.ControllerChangeHandler
import com.bluelinelabs.conductor.ControllerChangeType
import com.fredporciuncula.flow.preferences.Preference
import com.google.android.material.tabs.TabLayout
import com.jakewharton.rxrelay.BehaviorRelay
import com.jakewharton.rxrelay.PublishRelay
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.library.LibraryUpdateService
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.databinding.LibraryControllerBinding
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.ui.base.controller.RootController
import eu.kanade.tachiyomi.ui.base.controller.SearchableNucleusController
import eu.kanade.tachiyomi.ui.base.controller.TabbedController
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.browse.source.globalsearch.GlobalSearchController
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.util.preference.asImmediateFlow
import eu.kanade.tachiyomi.util.system.getResourceColor
import eu.kanade.tachiyomi.util.system.openInBrowser
import eu.kanade.tachiyomi.util.system.toast
import eu.kanade.tachiyomi.widget.ActionModeWithToolbar
import eu.kanade.tachiyomi.widget.EmptyView
import eu.kanade.tachiyomi.widget.materialdialogs.QuadStateTextView
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import reactivecircus.flowbinding.android.view.clicks
import reactivecircus.flowbinding.viewpager.pageSelections
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.concurrent.TimeUnit
class LibraryController(
bundle: Bundle? = null,
private val preferences: PreferencesHelper = Injekt.get()
) : SearchableNucleusController<LibraryControllerBinding, LibraryPresenter>(bundle),
RootController,
TabbedController,
ActionModeWithToolbar.Callback,
ChangeMangaCategoriesDialog.Listener,
DeleteLibraryMangasDialog.Listener {
/**
* Position of the active category.
*/
private var activeCategory: Int = preferences.lastUsedCategory().get()
/**
* Action mode for selections.
*/
private var actionMode: ActionModeWithToolbar? = null
/**
* Currently selected mangas.
*/
val selectedMangas = mutableSetOf<Manga>()
/**
* Relay to notify the UI of selection updates.
*/
val selectionRelay: PublishRelay<LibrarySelectionEvent> = PublishRelay.create()
/**
* Relay to notify search query changes.
*/
val searchRelay: BehaviorRelay<String> = BehaviorRelay.create()
/**
* Relay to notify the library's viewpager for updates.
*/
val libraryMangaRelay: BehaviorRelay<LibraryMangaEvent> = BehaviorRelay.create()
/**
* Relay to notify the library's viewpager to select all manga
*/
val selectAllRelay: PublishRelay<Int> = PublishRelay.create()
/**
* Relay to notify the library's viewpager to select the inverse
*/
val selectInverseRelay: PublishRelay<Int> = PublishRelay.create()
/**
* Number of manga per row in grid mode.
*/
var mangaPerRow = 0
private set
/**
* Adapter of the view pager.
*/
private var adapter: LibraryAdapter? = null
/**
* Sheet containing filter/sort/display items.
*/
private var settingsSheet: LibrarySettingsSheet? = null
private var tabsVisibilityRelay: BehaviorRelay<Boolean> = BehaviorRelay.create(false)
private var mangaCountVisibilityRelay: BehaviorRelay<Boolean> = BehaviorRelay.create(false)
private var tabsVisibilitySubscription: Subscription? = null
private var mangaCountVisibilitySubscription: Subscription? = null
init {
setHasOptionsMenu(true)
retainViewMode = RetainViewMode.RETAIN_DETACH
}
private var currentTitle: String? = null
set(value) {
if (field != value) {
field = value
setTitle()
}
}
override fun getTitle(): String? {
return currentTitle ?: resources?.getString(R.string.label_library)
}
private fun updateTitle() {
val showCategoryTabs = preferences.categoryTabs().get()
val currentCategory = adapter?.categories?.getOrNull(binding.libraryPager.currentItem)
var title = if (showCategoryTabs) {
resources?.getString(R.string.label_library)
} else {
currentCategory?.name
}
if (preferences.categoryNumberOfItems().get() && libraryMangaRelay.hasValue()) {
libraryMangaRelay.value.mangas.let { mangaMap ->
if (!showCategoryTabs || adapter?.categories?.size == 1) {
title += " (${mangaMap[currentCategory?.id]?.size ?: 0})"
}
}
}
currentTitle = title
}
override fun createPresenter(): LibraryPresenter {
return LibraryPresenter()
}
override fun createBinding(inflater: LayoutInflater) = LibraryControllerBinding.inflate(inflater)
override fun onViewCreated(view: View) {
super.onViewCreated(view)
adapter = LibraryAdapter(this)
binding.libraryPager.adapter = adapter
binding.libraryPager.pageSelections()
.drop(1)
.onEach {
preferences.lastUsedCategory().set(it)
activeCategory = it
updateTitle()
}
.launchIn(viewScope)
getColumnsPreferenceForCurrentOrientation().asImmediateFlow { mangaPerRow = it }
.drop(1)
// Set again the adapter to recalculate the covers height
.onEach { reattachAdapter() }
.launchIn(viewScope)
if (selectedMangas.isNotEmpty()) {
createActionModeIfNeeded()
}
settingsSheet = LibrarySettingsSheet(router) { group ->
when (group) {
is LibrarySettingsSheet.Filter.FilterGroup -> onFilterChanged()
is LibrarySettingsSheet.Sort.SortGroup -> onSortChanged()
is LibrarySettingsSheet.Display.DisplayGroup -> {
val delay = if (preferences.categorizedDisplaySettings().get()) 125L else 0L
Observable.timer(delay, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribe {
reattachAdapter()
}
}
is LibrarySettingsSheet.Display.BadgeGroup -> onBadgeSettingChanged()
is LibrarySettingsSheet.Display.TabsGroup -> onTabsSettingsChanged()
}
}
binding.btnGlobalSearch.clicks()
.onEach {
router.pushController(
GlobalSearchController(presenter.query).withFadeTransaction()
)
}
.launchIn(viewScope)
}
override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) {
super.onChangeStarted(handler, type)
if (type.isEnter) {
(activity as? MainActivity)?.binding?.tabs?.setupWithViewPager(binding.libraryPager)
presenter.subscribeLibrary()
}
}
override fun onDestroyView(view: View) {
destroyActionModeIfNeeded()
adapter?.onDestroy()
adapter = null
settingsSheet = null
tabsVisibilitySubscription?.unsubscribe()
tabsVisibilitySubscription = null
super.onDestroyView(view)
}
override fun configureTabs(tabs: TabLayout): Boolean {
with(tabs) {
isVisible = false
tabGravity = TabLayout.GRAVITY_START
tabMode = TabLayout.MODE_SCROLLABLE
}
tabsVisibilitySubscription?.unsubscribe()
tabsVisibilitySubscription = tabsVisibilityRelay.subscribe { visible ->
tabs.isVisible = visible
}
mangaCountVisibilitySubscription?.unsubscribe()
mangaCountVisibilitySubscription = mangaCountVisibilityRelay.subscribe {
adapter?.notifyDataSetChanged()
}
return false
}
override fun cleanupTabs(tabs: TabLayout) {
tabsVisibilitySubscription?.unsubscribe()
tabsVisibilitySubscription = null
}
fun showSettingsSheet() {
if (adapter?.categories?.isNotEmpty() == true) {
adapter?.categories?.get(binding.libraryPager.currentItem)?.let { category ->
settingsSheet?.show(category)
}
} else {
settingsSheet?.show()
}
}
fun onNextLibraryUpdate(categories: List<Category>, mangaMap: Map<Int, List<LibraryItem>>) {
val view = view ?: return
val adapter = adapter ?: return
// Show empty view if needed
if (mangaMap.isNotEmpty()) {
binding.emptyView.hide()
} else {
binding.emptyView.show(
R.string.information_empty_library,
listOf(
EmptyView.Action(R.string.getting_started_guide, R.drawable.ic_help_24dp) {
activity?.openInBrowser("https://tachiyomi.org/help/guides/getting-started")
}
),
)
(activity as? MainActivity)?.ready = true
}
// Get the current active category.
val activeCat = if (adapter.categories.isNotEmpty()) {
binding.libraryPager.currentItem
} else {
activeCategory
}
// Set the categories
adapter.updateCategories(categories.map { it to (mangaMap[it.id]?.size ?: 0) })
// Restore active category.
binding.libraryPager.setCurrentItem(activeCat, false)
// Trigger display of tabs
onTabsSettingsChanged(firstLaunch = true)
// Delay the scroll position to allow the view to be properly measured.
view.doOnAttach {
(activity as? MainActivity)?.binding?.tabs?.setScrollPosition(binding.libraryPager.currentItem, 0f, true)
}
// Send the manga map to child fragments after the adapter is updated.
libraryMangaRelay.call(LibraryMangaEvent(mangaMap))
// Finally update the title
updateTitle()
}
/**
* Returns a preference for the number of manga per row based on the current orientation.
*
* @return the preference.
*/
private fun getColumnsPreferenceForCurrentOrientation(): Preference<Int> {
return if (resources?.configuration?.orientation == Configuration.ORIENTATION_PORTRAIT) {
preferences.portraitColumns()
} else {
preferences.landscapeColumns()
}
}
private fun onFilterChanged() {
presenter.requestFilterUpdate()
activity?.invalidateOptionsMenu()
}
private fun onBadgeSettingChanged() {
presenter.requestBadgesUpdate()
}
private fun onTabsSettingsChanged(firstLaunch: Boolean = false) {
if (!firstLaunch) {
mangaCountVisibilityRelay.call(preferences.categoryNumberOfItems().get())
}
tabsVisibilityRelay.call(preferences.categoryTabs().get() && adapter?.categories?.size ?: 0 > 1)
updateTitle()
}
/**
* Called when the sorting mode is changed.
*/
private fun onSortChanged() {
presenter.requestSortUpdate()
}
/**
* Reattaches the adapter to the view pager to recreate fragments
*/
private fun reattachAdapter() {
val adapter = adapter ?: return
val position = binding.libraryPager.currentItem
adapter.recycle = false
binding.libraryPager.adapter = adapter
binding.libraryPager.currentItem = position
adapter.recycle = true
}
/**
* Creates the action mode if it's not created already.
*/
fun createActionModeIfNeeded() {
val activity = activity
if (actionMode == null && activity is MainActivity) {
actionMode = activity.startActionModeAndToolbar(this)
activity.showBottomNav(false)
}
}
/**
* Destroys the action mode.
*/
private fun destroyActionModeIfNeeded() {
actionMode?.finish()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
createOptionsMenu(menu, inflater, R.menu.library, R.id.action_search)
// Mutate the filter icon because it needs to be tinted and the resource is shared.
menu.findItem(R.id.action_filter).icon.mutate()
}
fun search(query: String) {
presenter.query = query
}
private fun performSearch() {
searchRelay.call(presenter.query)
if (presenter.query.isNotEmpty()) {
binding.btnGlobalSearch.isVisible = true
binding.btnGlobalSearch.text =
resources?.getString(R.string.action_global_search_query, presenter.query)
} else {
binding.btnGlobalSearch.isVisible = false
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
val settingsSheet = settingsSheet ?: return
val filterItem = menu.findItem(R.id.action_filter)
// Tint icon if there's a filter active
if (settingsSheet.filters.hasActiveFilters()) {
val filterColor = activity!!.getResourceColor(R.attr.colorFilterActive)
filterItem.icon.setTint(filterColor)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_search -> expandActionViewFromInteraction = true
R.id.action_filter -> showSettingsSheet()
R.id.action_update_library -> {
activity?.let {
if (LibraryUpdateService.start(it)) {
it.toast(R.string.updating_library)
}
}
}
}
return super.onOptionsItemSelected(item)
}
/**
* Invalidates the action mode, forcing it to refresh its content.
*/
fun invalidateActionMode() {
actionMode?.invalidate()
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.generic_selection, menu)
return true
}
override fun onCreateActionToolbar(menuInflater: MenuInflater, menu: Menu) {
menuInflater.inflate(R.menu.library_selection, menu)
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
val count = selectedMangas.size
if (count == 0) {
// Destroy action mode if there are no items selected.
destroyActionModeIfNeeded()
} else {
mode.title = count.toString()
}
return true
}
override fun onPrepareActionToolbar(toolbar: ActionModeWithToolbar, menu: Menu) {
if (selectedMangas.isEmpty()) return
toolbar.findToolbarItem(R.id.action_download_unread)?.isVisible =
selectedMangas.any { it.source != LocalSource.ID }
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_move_to_category -> showChangeMangaCategoriesDialog()
R.id.action_download_unread -> downloadUnreadChapters()
R.id.action_mark_as_read -> markReadStatus(true)
R.id.action_mark_as_unread -> markReadStatus(false)
R.id.action_delete -> showDeleteMangaDialog()
R.id.action_select_all -> selectAllCategoryManga()
R.id.action_select_inverse -> selectInverseCategoryManga()
else -> return false
}
return true
}
override fun onDestroyActionMode(mode: ActionMode) {
// Clear all the manga selections and notify child views.
selectedMangas.clear()
selectionRelay.call(LibrarySelectionEvent.Cleared())
(activity as? MainActivity)?.showBottomNav(true)
actionMode = null
}
fun openManga(manga: Manga) {
// Notify the presenter a manga is being opened.
presenter.onOpenManga()
router.pushController(MangaController(manga).withFadeTransaction())
}
/**
* Sets the selection for a given manga.
*
* @param manga the manga whose selection has changed.
* @param selected whether it's now selected or not.
*/
fun setSelection(manga: Manga, selected: Boolean) {
if (selected) {
if (selectedMangas.add(manga)) {
selectionRelay.call(LibrarySelectionEvent.Selected(manga))
}
} else {
if (selectedMangas.remove(manga)) {
selectionRelay.call(LibrarySelectionEvent.Unselected(manga))
}
}
}
/**
* Toggles the current selection state for a given manga.
*
* @param manga the manga whose selection to change.
*/
fun toggleSelection(manga: Manga) {
if (selectedMangas.add(manga)) {
selectionRelay.call(LibrarySelectionEvent.Selected(manga))
} else if (selectedMangas.remove(manga)) {
selectionRelay.call(LibrarySelectionEvent.Unselected(manga))
}
}
/**
* Clear all of the manga currently selected, and
* invalidate the action mode to revert the top toolbar
*/
fun clearSelection() {
selectedMangas.clear()
selectionRelay.call(LibrarySelectionEvent.Cleared())
invalidateActionMode()
}
/**
* Move the selected manga to a list of categories.
*/
private fun showChangeMangaCategoriesDialog() {
// Create a copy of selected manga
val mangas = selectedMangas.toList()
// Hide the default category because it has a different behavior than the ones from db.
val categories = presenter.categories.filter { it.id != 0 }
// Get indexes of the common categories to preselect.
val common = presenter.getCommonCategories(mangas)
// Get indexes of the mix categories to preselect.
val mix = presenter.getMixCategories(mangas)
var preselected = categories.map {
when (it) {
in common -> QuadStateTextView.State.CHECKED.ordinal
in mix -> QuadStateTextView.State.INDETERMINATE.ordinal
else -> QuadStateTextView.State.UNCHECKED.ordinal
}
}.toTypedArray()
ChangeMangaCategoriesDialog(this, mangas, categories, preselected)
.showDialog(router)
}
private fun downloadUnreadChapters() {
val mangas = selectedMangas.toList()
presenter.downloadUnreadChapters(mangas)
destroyActionModeIfNeeded()
}
private fun markReadStatus(read: Boolean) {
val mangas = selectedMangas.toList()
presenter.markReadStatus(mangas, read)
destroyActionModeIfNeeded()
}
private fun showDeleteMangaDialog() {
DeleteLibraryMangasDialog(this, selectedMangas.toList()).showDialog(router)
}
override fun updateCategoriesForMangas(mangas: List<Manga>, addCategories: List<Category>, removeCategories: List<Category>) {
presenter.updateMangasToCategories(mangas, addCategories, removeCategories)
destroyActionModeIfNeeded()
}
override fun deleteMangas(mangas: List<Manga>, deleteFromLibrary: Boolean, deleteChapters: Boolean) {
presenter.removeMangas(mangas, deleteFromLibrary, deleteChapters)
destroyActionModeIfNeeded()
}
private fun selectAllCategoryManga() {
adapter?.categories?.getOrNull(binding.libraryPager.currentItem)?.id?.let {
selectAllRelay.call(it)
}
}
private fun selectInverseCategoryManga() {
adapter?.categories?.getOrNull(binding.libraryPager.currentItem)?.id?.let {
selectInverseRelay.call(it)
}
}
override fun onSearchViewQueryTextChange(newText: String?) {
// Ignore events if this controller isn't at the top to avoid query being reset
if (router.backstack.lastOrNull()?.controller == this) {
presenter.query = newText ?: ""
performSearch()
}
}
}
|
apache-2.0
|
3321b8f04202166932a1abe167506212
| 33.256956 | 130 | 0.651235 | 4.965836 | false | false | false | false |
dhis2/dhis2-android-sdk
|
core/src/test/java/org/hisp/dhis/android/core/imports/internal/conflicts/InvalidDataValueConflictShould.kt
|
1
|
4071
|
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.imports.internal.conflicts
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.whenever
import org.hisp.dhis.android.core.imports.internal.ImportConflict
import org.junit.Test
internal class InvalidDataValueConflictShould : BaseConflictShould() {
@Test
fun `Should match error messages`() {
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotNumeric(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotUnitInterval(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotPercentage(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotInteger(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotPositiveInteger(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotNegativeInteger(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotZeroOrPositiveInteger(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotBoolean(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotTrueOnly(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotValidDate(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotValidDatetime(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotCoordinate(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotUrl(dataElementUid))
checkMatchAndDataElement(TrackedImportConflictSamples.valueNotFileResourceUid(dataElementUid))
}
@Test
fun `Should create display description`() {
whenever(dataElement.displayFormName()) doReturn "Data Element form name"
val conflict = TrackedImportConflictSamples.valueNotNumeric(dataElementUid)
val displayDescription = InvalidDataValueConflict.getDisplayDescription(conflict, context)
assertThat(displayDescription == "Invalid value type for dataElement: Data Element form name").isTrue()
}
private fun checkMatchAndDataElement(conflict: ImportConflict) {
assertThat(InvalidDataValueConflict.matches(conflict)).isTrue()
assertThat(InvalidDataValueConflict.getDataElement(conflict) == dataElementUid).isTrue()
}
}
|
bsd-3-clause
|
f053d5933d14b10d95eb3d510f020ad1
| 58 | 111 | 0.800049 | 5.013547 | false | false | false | false |
mdanielwork/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/inference.kt
|
1
|
3749
|
// 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.processors.inference
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil.extractIterableTypeParameter
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.SpreadState
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.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil.getQualifierType
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.api.JustTypeArgument
import org.jetbrains.plugins.groovy.lang.resolve.impl.getArguments
import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint
fun getTopLevelType(expression: GrExpression): PsiType? {
if (expression is GrMethodCall) {
val resolved = expression.advancedResolve()
(resolved as? GroovyMethodResult)?.candidate?.let {
val session = GroovyInferenceSessionBuilder(expression.invokedExpression as GrReferenceExpression, it)
.resolveMode(false)
.build()
return session.inferSubst().substitute(PsiUtil.getSmartReturnType(it.method))
}
}
if (expression is GrClosableBlock) {
return TypesUtil.createTypeByFQClassName(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, expression)
}
return expression.type
}
fun getTopLevelTypeCached(expression: GrExpression): PsiType? {
return GroovyPsiManager.getInstance(expression.project).getTopLevelType(expression)
}
fun buildQualifier(ref: GrReferenceExpression, state: ResolveState): Argument {
val qualifierExpression = ref.qualifierExpression
val spreadState = state[SpreadState.SPREAD_STATE]
if (qualifierExpression != null && spreadState == null) {
return ExpressionArgument(qualifierExpression)
}
val resolvedThis = state[ClassHint.THIS_TYPE]
if (resolvedThis != null) {
return JustTypeArgument(resolvedThis)
}
val type = getQualifierType(ref)
when {
spreadState == null -> return JustTypeArgument(type)
type == null -> return JustTypeArgument(null)
else -> return JustTypeArgument(extractIterableTypeParameter(type, false))
}
}
fun GrCall.buildTopLevelArgumentTypes(): Array<PsiType?>? {
return getArguments()?.map { argument ->
if (argument is ExpressionArgument) {
getTopLevelTypeCached(argument.expression)
}
else {
val type = argument.type
if (type is GrMapType) {
TypesUtil.createTypeByFQClassName(CommonClassNames.JAVA_UTIL_MAP, this)
}
else {
type
}
}
}?.toTypedArray()
}
fun PsiSubstitutor.putAll(parameters: Array<out PsiTypeParameter>, arguments: Array<out PsiType>): PsiSubstitutor {
if (arguments.size != parameters.size) return this
return parameters.zip(arguments).fold(this) { acc, (param, arg) ->
acc.put(param, arg)
}
}
|
apache-2.0
|
f031b874f85d0e5ea92c9492c7aec43c
| 41.123596 | 140 | 0.782875 | 4.260227 | false | false | false | false |
google/android-auto-companion-app
|
android/app/src/main/kotlin/com/google/automotive/companion/CalendarSyncConstants.kt
|
1
|
1736
|
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.automotive.companion
/**
* Constants for mapping calendar sync methods across the flutter `MethodChannel`.
*
* This file is auto-generated.
*/
object CalendarSyncConstants {
const val CHANNEL = "google.gas.connecteddevice.feature/calendarsync"
const val METHOD_HAS_PERMISSIONS = "hasPermissions"
const val METHOD_REQUEST_PERMISSIONS = "requestPermissions"
const val METHOD_RETRIEVE_CALENDARS = "retrieveCalendars"
const val METHOD_IS_ENABLED = "isEnabled"
const val METHOD_SET_ENABLED = "setEnabled"
const val METHOD_GET_SELECTED_IDS = "getSelectedIds"
const val METHOD_SET_SELECTED_IDS = "setSelectedIds"
const val METHOD_IS_CAR_ENABLED = "isCarEnabled"
const val METHOD_ENABLE_CAR = "enableCar"
const val METHOD_DISABLE_CAR = "disableCar"
const val METHOD_FETCH_CALENDAR_IDS_TO_SYNC = "fetchCalendarIdsToSync"
const val METHOD_STORE_CALENDAR_IDS_TO_SYNC = "storeCalendarIdsToSync"
const val ARGUMENT_CAR_ID = "carId"
const val ARGUMENT_CALENDARS = "calendars"
const val PREF_CALENDAR_IDS = "kCompanionCalSyncCalendarIds"
const val PREF_ENABLED_STATE = "kCompanionCalSyncEnabled"
}
|
apache-2.0
|
a7382e2d0bed84acbfc7a1e16881534b
| 41.341463 | 82 | 0.758641 | 4.027842 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/platform-impl/src/com/intellij/ide/browsers/LaunchBrowserBeforeRunTaskProvider.kt
|
7
|
4968
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.browsers
import com.intellij.execution.BeforeRunTask
import com.intellij.execution.BeforeRunTaskProvider
import com.intellij.execution.ExecutionListener
import com.intellij.execution.ExecutionManager
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.xmlb.annotations.Attribute
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.resolvedPromise
import javax.swing.Icon
internal class LaunchBrowserBeforeRunTaskProvider : BeforeRunTaskProvider<LaunchBrowserBeforeRunTask>(), DumbAware {
companion object {
val ID = Key.create<LaunchBrowserBeforeRunTask>("LaunchBrowser.Before.Run")
}
override fun getName() = IdeBundle.message("task.browser.launch")
override fun getId() = ID
override fun getIcon(): Icon = AllIcons.Nodes.PpWeb
override fun isConfigurable() = true
override fun createTask(runConfiguration: RunConfiguration) = LaunchBrowserBeforeRunTask()
override fun configureTask(context: DataContext, runConfiguration: RunConfiguration, task: LaunchBrowserBeforeRunTask): Promise<Boolean> {
val state = task.state
val modificationCount = state.modificationCount
val browserSelector = BrowserSelector()
val browserComboBox = browserSelector.mainComponent
state.browser?.let {
browserSelector.selected = it
}
val url = TextFieldWithBrowseButton()
state.url?.let {
url.text = it
}
StartBrowserPanel.setupUrlField(url, runConfiguration.project)
val startJavaScriptDebuggerCheckBox = if (JavaScriptDebuggerStarter.Util.hasStarters()) CheckBox(IdeBundle.message("start.browser.with.js.debugger"), state.withDebugger) else null
val panel = panel {
row(IdeBundle.message("task.browser.label")) {
browserComboBox()
startJavaScriptDebuggerCheckBox?.invoke()
}
row(IdeBundle.message("task.browser.url")) {
url(growPolicy = GrowPolicy.MEDIUM_TEXT)
}
}
dialog(IdeBundle.message("task.browser.launch"), panel = panel, resizable = true, focusedComponent = url)
.show()
state.browser = browserSelector.selected
state.url = url.text
if (startJavaScriptDebuggerCheckBox != null) {
state.withDebugger = startJavaScriptDebuggerCheckBox.isSelected
}
return resolvedPromise(modificationCount != state.modificationCount)
}
override fun executeTask(context: DataContext, configuration: RunConfiguration, env: ExecutionEnvironment, task: LaunchBrowserBeforeRunTask): Boolean {
val disposable = Disposer.newDisposable()
Disposer.register(env.project, disposable)
val executionId = env.executionId
env.project.messageBus.connect(disposable).subscribe(ExecutionManager.EXECUTION_TOPIC, object: ExecutionListener {
override fun processNotStarted(executorId: String, env: ExecutionEnvironment) {
Disposer.dispose(disposable)
}
override fun processStarted(executorId: String, env: ExecutionEnvironment, handler: ProcessHandler) {
if (env.executionId != executionId) {
return
}
Disposer.dispose(disposable)
val settings = StartBrowserSettings()
settings.browser = task.state.browser
settings.isStartJavaScriptDebugger = task.state.withDebugger
settings.url = task.state.url
settings.isSelected = true
BrowserStarter(configuration, settings, handler).start()
}
})
return true
}
}
internal class LaunchBrowserBeforeRunTaskState : BaseState() {
@get:Attribute(value = "browser", converter = WebBrowserReferenceConverter::class)
var browser by property<WebBrowser?>(null) { it == null }
@get:Attribute()
var url by string()
@get:Attribute()
var withDebugger by property(false)
}
internal class LaunchBrowserBeforeRunTask : BeforeRunTask<LaunchBrowserBeforeRunTask>(LaunchBrowserBeforeRunTaskProvider.ID), PersistentStateComponent<LaunchBrowserBeforeRunTaskState> {
private var state = LaunchBrowserBeforeRunTaskState()
override fun loadState(state: LaunchBrowserBeforeRunTaskState) {
state.resetModificationCount()
this.state = state
}
override fun getState() = state
}
|
apache-2.0
|
14f9cf8b9c075297f1830edea35e6264
| 37.820313 | 185 | 0.768921 | 5.053917 | false | true | false | false |
dahlstrom-g/intellij-community
|
platform/credential-store/src/PasswordSafeSettings.kt
|
7
|
3329
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore
import com.intellij.ide.passwordSafe.impl.getDefaultKeePassDbFile
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.messages.Topic
import com.intellij.util.text.nullize
import com.intellij.util.xmlb.annotations.OptionTag
@Service
@State(name = "PasswordSafe", storages = [Storage(value = "security.xml", roamingType = RoamingType.DISABLED)], reportStatistic = false)
class PasswordSafeSettings : PersistentStateComponentWithModificationTracker<PasswordSafeSettings.PasswordSafeOptions> {
companion object {
private val LOG = logger<PasswordSafeSettings>()
@JvmField
val TOPIC = Topic.create("PasswordSafeSettingsListener", PasswordSafeSettingsListener::class.java)
private val defaultProviderType: ProviderType
get() = CredentialStoreManager.getInstance().defaultProvider()
}
private var state = PasswordSafeOptions()
var keepassDb: String?
get() {
val result = state.keepassDb
return when {
result == null && providerType === ProviderType.KEEPASS -> getDefaultKeePassDbFile().toString()
else -> result
}
}
set(value) {
var v = value.nullize(nullizeSpaces = true)
if (v != null && v == getDefaultKeePassDbFile().toString()) {
v = null
}
state.keepassDb = v
}
var providerType: ProviderType
get() = if (SystemInfo.isWindows && state.provider === ProviderType.KEYCHAIN) ProviderType.KEEPASS else state.provider
set(value) {
var newValue = value
@Suppress("DEPRECATION")
if (newValue === ProviderType.DO_NOT_STORE) {
newValue = ProviderType.MEMORY_ONLY
}
val oldValue = state.provider
if (newValue !== oldValue && CredentialStoreManager.getInstance().isSupported(newValue)) {
state.provider = newValue
ApplicationManager.getApplication()?.messageBus?.syncPublisher(TOPIC)?.typeChanged(oldValue, newValue)
}
}
override fun getState() = state
override fun loadState(state: PasswordSafeOptions) {
val credentialStoreManager = CredentialStoreManager.getInstance()
@Suppress("DEPRECATION")
if (state.provider === ProviderType.DO_NOT_STORE && !credentialStoreManager.isSupported(ProviderType.MEMORY_ONLY)
|| state.provider !== ProviderType.DO_NOT_STORE && !credentialStoreManager.isSupported(state.provider)) {
LOG.error("Provider ${state.provider} from loaded credential store config is not supported in this environment")
}
this.state = state
providerType = state.provider
state.keepassDb = state.keepassDb.nullize(nullizeSpaces = true)
}
override fun getStateModificationCount() = state.modificationCount
class PasswordSafeOptions : BaseState() {
// do not use it directly
@get:OptionTag("PROVIDER")
var provider by enum(defaultProviderType)
// do not use it directly
var keepassDb by string()
var isRememberPasswordByDefault by property(true)
// do not use it directly
var pgpKeyId by string()
}
}
|
apache-2.0
|
314949cb9ffefc8ec6f6301f840cadbc
| 36.404494 | 140 | 0.725443 | 4.535422 | false | false | false | false |
intellij-solidity/intellij-solidity
|
src/test/kotlin/me/serce/solidity/utils/SolTestBase.kt
|
1
|
2909
|
package me.serce.solidity.utils
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import org.intellij.lang.annotations.Language
abstract class SolTestBase : SolLightPlatformCodeInsightFixtureTestCase() {
inner class InlineFile(@Language("Solidity") private val code: String, val name: String = "ctr.sol") {
val psiFile: PsiFile
private val hasCaretMarker = "/*caret*/" in code
init {
psiFile = myFixture.configureByText(name, replaceCaretMarker(code))
}
fun withCaret() {
check(hasCaretMarker) {
"Please, add `/*caret*/` marker to\n$code"
}
}
}
protected val fileName: String
get() = "${getTestName(true)}.sol"
val fixture: CodeInsightTestFixture
get() = super.myFixture
protected fun replaceCaretMarker(text: String) = text.replace("/*caret*/", "<caret>")
inline fun <reified T : PsiElement> findElementAndDataInEditor(marker: String = "^"): Pair<T, String> {
val caretMarker = "//$marker"
val (elementAtMarker, data) = run {
val text = fixture.file.text
val markerOffset = text.indexOf(caretMarker)
check(markerOffset != -1) { "No `$marker` marker:\n$text" }
check(text.indexOf(caretMarker, startIndex = markerOffset + 1) == -1) {
"More than one `$marker` marker:\n$text"
}
val data = text.drop(markerOffset).removePrefix(caretMarker).takeWhile { it != '\n' }.trim()
val markerPosition = fixture.editor.offsetToLogicalPosition(markerOffset + caretMarker.length - 1)
val previousLine = LogicalPosition(markerPosition.line - 1, markerPosition.column)
val elementOffset = fixture.editor.logicalPositionToOffset(previousLine)
fixture.file.findElementAt(elementOffset)!! to data
}
val element = elementAtMarker.parentOfType<T>(strict = false)
?: error("No ${T::class.java.simpleName} at ${elementAtMarker.text}")
return element to data
}
inline fun <reified T : PsiElement> PsiElement.parentOfType(strict: Boolean = true, minStartOffset: Int = -1): T? =
PsiTreeUtil.getParentOfType(this, T::class.java, strict, minStartOffset)
inline fun <reified T : PsiElement> findElementInEditor(marker: String = "^"): T {
val (element, data) = findElementAndDataInEditor<T>(marker)
check(data.isEmpty()) { "Did not expect marker data" }
return element
}
protected fun checkByFile(ignoreTrailingWhitespace: Boolean = true, action: () -> Unit) {
val (before, after) = (fileName to fileName.replace(".sol", "After.sol"))
myFixture.configureByFile(before)
action()
myFixture.checkResultByFile(after, ignoreTrailingWhitespace)
}
protected fun checkResult(@Language("Solidity") text: String) {
myFixture.checkResult(text)
}
}
|
mit
|
db3b34d5982bcd1a0359b8fe0ecd1252
| 38.310811 | 117 | 0.706085 | 4.234352 | false | true | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/util/HTMLDecoder.kt
|
1
|
54195
|
package jp.juggler.subwaytooter.util
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.*
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.entity.*
import jp.juggler.subwaytooter.mfm.MisskeyMarkdownDecoder
import jp.juggler.subwaytooter.pref.PrefB
import jp.juggler.subwaytooter.span.*
import jp.juggler.subwaytooter.table.AcctColor
import jp.juggler.subwaytooter.table.HighlightWord
import jp.juggler.util.*
import java.util.*
import java.util.regex.Pattern
import kotlin.math.min
object HTMLDecoder {
private val log = LogCategory("HTMLDecoder")
private const val DEBUG_HTML_PARSER = false
private enum class OpenType {
Open,
Close,
OpenClose,
}
private const val TAG_TEXT = "<>text"
private const val TAG_END = "<>end"
private val reTag = "<(/?)(\\w+)".asciiPattern()
private val reTagEnd = "(/?)>$".asciiPattern()
private val reHref = "\\bhref=\"([^\"]*)\"".asciiPattern()
private val reAttribute = "\\s+([A-Za-z0-9:_-]+)\\s*=([\"'])([^>]*?)\\2".asciiPattern()
private val reShortcode = ":[A-Za-z0-9_-]+:".asciiPattern()
private val reNotestockEmojiAlt = """\A:[^:]+:\z""".toRegex()
private val reUrlStart = """\Ahttps?://""".toRegex()
// Block-level Elements
// https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
// https://www.w3schools.com/html/html_blocks.asp
private val blockLevelElements = arrayOf(
"address",
"article",
"aside",
"blockquote",
"body",
"canvas",
"caption",
"col",
"colgroup",
"dd",
"div",
"dl",
"dt",
"embed",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hgroup",
"hr",
"li",
"main",
"map",
"nav",
"noscript",
"object",
"ol",
"p",
"pre",
"progress",
"section",
"textarea",
"table",
"tbody",
"tfoot",
"thead",
"tr",
"ul",
"video"
).toHashSet()
// Empty element
// https://developer.mozilla.org/en-US/docs/Glossary/Empty_element
// elements that cannot have any child nodes (i.e., nested elements or text nodes).
// In HTML, using a closing tag on an empty element is usually invalid.
private val emptyElements = arrayOf(
"area",
"base",
"br",
"col",
"embed",
"hr",
"img",
"input",
"keygen", //(HTML 5.2 Draft removed)
"link",
"meta",
"param",
"source",
"track",
"wbr"
).toHashSet()
private val reEntity = "&(#?)(\\w+);".asciiPattern()
private val entity_map = HashMap<String, Char>()
private fun defineEntity(s: String, c: Char) {
entity_map[s] = c
}
private fun chr(num: Int): Char {
return num.toChar()
}
fun decodeEntity(src: String?): String {
src ?: return ""
var sb: StringBuilder? = null
val m = reEntity.matcher(src)
var last_end = 0
while (m.find()) {
if (sb == null) sb = StringBuilder()
val start = m.start()
val end = m.end()
try {
if (start > last_end) {
sb.append(src.substring(last_end, start))
}
val is_numeric = m.groupEx(1)!!.isNotEmpty()
val part = m.groupEx(2)!!
if (!is_numeric) {
val c = entity_map[part]
if (c != null) {
sb.append(c)
continue
}
} else {
try {
val cp = when {
part[0] == 'x' -> part.substring(1).toInt(16)
else -> part.toInt(10)
}
when {
Character.isBmpCodePoint(cp) -> sb.append(cp.toChar())
Character.isValidCodePoint(cp) -> {
sb.append(Character.highSurrogate(cp))
sb.append(Character.lowSurrogate(cp))
}
else -> sb.append('?')
}
continue
} catch (ex: Throwable) {
log.trace(ex)
}
}
sb.append(src.substring(start, end))
} finally {
last_end = end
}
}
// 全くマッチしなかった
sb ?: return src
val end = src.length
if (end > last_end) {
sb.append(src.substring(last_end, end))
}
return sb.toString()
}
fun encodeEntity(src: String): String {
val size = src.length
val sb = StringBuilder()
sb.ensureCapacity(size)
for (i in 0 until size) {
when (val c = src[i]) {
'<' -> sb.append("<")
'>' -> sb.append(">")
'"' -> sb.append(""")
'\'' -> sb.append("'")
'&' -> sb.append("&")
else -> sb.append(c)
}
}
return sb.toString()
}
//////////////////////////////////////////////////////////////////////////////////////
private val reDoctype = """\A\s*<!doctype[^>]*>""".asciiPattern(Pattern.CASE_INSENSITIVE)
private val reComment = """<!--.*?-->""".asciiPattern(Pattern.DOTALL)
private fun String.quoteMeta() = Pattern.quote(this)
private class TokenParser(srcArg: String) {
val src: String
var next: Int = 0
var open_type = OpenType.OpenClose
var tag = ""
var text = ""
init {
this.src = srcArg
.replaceFirst(reDoctype, "")
.replaceAll(reComment, " ")
eat()
}
fun eat() {
// end?
if (next >= src.length) {
tag = TAG_END
open_type = OpenType.OpenClose
return
}
// text ?
var end = src.indexOf('<', next)
if (end == -1) end = src.length
if (end > next) {
this.text = src.substring(next, end)
this.tag = TAG_TEXT
this.open_type = OpenType.OpenClose
next = end
return
}
// tag ?
end = src.indexOf('>', next)
if (end == -1) {
end = src.length
} else {
++end
}
text = src.substring(next, end)
next = end
val m = reTag.matcher(text)
if (m.find()) {
val is_close = m.groupEx(1)!!.isNotEmpty()
tag = m.groupEx(2)!!.lowercase()
val m2 = reTagEnd.matcher(text)
val is_openclose = when {
m2.find() -> m2.groupEx(1)!!.isNotEmpty()
else -> false
}
open_type = when {
is_close -> OpenType.Close
is_openclose || emptyElements.contains(tag) -> OpenType.OpenClose
else -> OpenType.Open
}
} else {
tag = TAG_TEXT
this.open_type = OpenType.OpenClose
}
}
}
// 末尾の改行を数える
private fun SpannableStringBuilder.lastBrCount(): Int {
var count = 0
var pos = length - 1
while (pos > 0) {
val c = this[pos--]
when {
c == '\n' -> {
++count
continue
}
Character.isWhitespace(c) -> continue
else -> break
}
}
return count
}
private val listMarkers = arrayOf("●", "-", "*", "・")
private enum class ListType {
None,
Ordered,
Unordered,
Definition,
Quote
}
private class ListContext(
val type: ListType,
val nestLevelOrdered: Int,
val nestLevelUnordered: Int,
val nestLevelDefinition: Int,
val nestLevelQuote: Int,
var order: Int = 0,
) {
fun subOrdered() = ListContext(
type = ListType.Ordered,
nestLevelOrdered + 1,
nestLevelUnordered,
nestLevelDefinition,
nestLevelQuote
)
fun subUnordered() = ListContext(
type = ListType.Unordered,
nestLevelOrdered,
nestLevelUnordered + 1,
nestLevelDefinition,
nestLevelQuote
)
fun subDefinition() = ListContext(
type = ListType.Definition,
nestLevelOrdered,
nestLevelUnordered,
nestLevelDefinition + 1,
nestLevelQuote
)
fun subQuote() = ListContext(
type = ListType.Quote,
nestLevelOrdered,
nestLevelUnordered,
nestLevelDefinition,
nestLevelQuote + 1
)
fun increment() = when (type) {
ListType.Ordered -> "${++order}. "
ListType.Unordered -> "${listMarkers[nestLevelUnordered % listMarkers.size]} "
ListType.Definition -> ""
else -> ""
}
fun inList() = nestLevelOrdered + nestLevelUnordered + nestLevelDefinition > 0
fun quoteColor(): Int {
val quoteNestColors = MisskeyMarkdownDecoder.quoteNestColors
return quoteNestColors[nestLevelQuote % quoteNestColors.size]
}
}
// SpannableStringBuilderを行ごとに分解する
// 行末の改行文字は各行の末尾に残る
// 最終行の長さが0(改行文字もなし)だった場合は出力されない
fun SpannableStringBuilder.splitLines() =
ArrayList<SpannableStringBuilder>().also { dst ->
// 入力の末尾のtrim
var end = this.length
while (end > 0 && CharacterGroup.isWhitespace(this[end - 1].code)) --end
// 入力の最初の非空白文字の位置を調べておく
var firstNonSpace = 0
while (firstNonSpace < end && CharacterGroup.isWhitespace(this[firstNonSpace].code)) ++firstNonSpace
var i = 0
while (i < end) {
val lineStart = i
while (i < end && this[i] != '\n') ++i
val lineEnd = if (i >= end) end else i + 1
++i
// 行頭の空白を削る
// while (lineStart < lineEnd &&
// this[lineStart] != '\n' &&
// CharacterGroup.isWhitespace(this[lineStart].toInt())
// ) ++lineStart
// 最初の非空白文字以降の行を出力する
if (lineEnd > firstNonSpace) {
dst.add(this.subSequence(lineStart, lineEnd) as SpannableStringBuilder)
}
}
if (dst.isEmpty()) {
// ブロック要素は最低1行は存在するので、1行だけの要素を作る
dst.add(SpannableStringBuilder())
}
}
private val reLastLine = """(?:\A|\n)([^\n]*)\z""".toRegex()
private class Node {
val child_nodes = ArrayList<Node>()
val tag: String
val text: String
private val href: String?
get() {
val m = reHref.matcher(text)
if (m.find()) {
val href = decodeEntity(m.groupEx(1))
if (href.isNotEmpty()) {
return href
}
}
return null
}
constructor() {
tag = "<>root"
text = ""
}
constructor(t: TokenParser) {
this.tag = t.tag
this.text = t.text
}
fun addChild(t: TokenParser, indent: String) {
if (DEBUG_HTML_PARSER) log.d("addChild: $indent($tag")
while (t.tag != TAG_END) {
// 閉じるタグ
if (t.open_type == OpenType.Close) {
if (t.tag != this.tag) {
// 閉じるタグが現在の階層とマッチしないなら無視する
log.w("unexpected close tag! ${t.tag}")
t.eat()
continue
}
// この階層の終端
t.eat()
break
}
val open_type = t.open_type
val child = Node(t)
child_nodes.add(child)
t.eat()
if (DEBUG_HTML_PARSER) {
log.d("addChild: $indent|${child.tag} $open_type [${child.text.quoteMeta()}]")
}
if (open_type == OpenType.Open) {
child.addChild(t, "$indent--")
}
}
if (DEBUG_HTML_PARSER) log.d("addChild: $indent)$tag")
}
fun String.tagsCanRemoveNearSpaces() = when (this) {
"li", "ol", "ul", "dl", "dt", "dd", "blockquote", "h1", "h2", "h3", "h4", "h5", "h6",
"table", "tbody", "thead", "tfoot", "tr", "td", "th",
-> true
else -> false
}
fun canSkipEncode(
isBlockParent: Boolean,
curr: Node,
parent: Node,
prev: Node?,
next: Node?
) = when {
!isBlockParent -> false
curr.tag != TAG_TEXT -> false
curr.text.isNotBlank() -> false
else -> when {
prev?.tag?.tagsCanRemoveNearSpaces() == true -> true
next?.tag?.tagsCanRemoveNearSpaces() == true -> true
parent.tag.tagsCanRemoveNearSpaces() && (prev == null || next == null) -> true
else -> false
}
}
fun encodeText(options: DecodeOptions, sb: SpannableStringBuilder) {
if (options.context != null && options.decodeEmoji) {
sb.append(options.decodeEmoji(decodeEntity(text)))
} else {
sb.append(decodeEntity(text))
}
}
fun encodeImage(options: DecodeOptions, sb: SpannableStringBuilder) {
val attrs = parseAttributes(text)
if (options.unwrapEmojiImageTag) {
val cssClass = attrs["class"]
val title = attrs["title"]
val url = attrs["src"]
val alt = attrs["alt"]
if (cssClass != null &&
title != null &&
cssClass.contains("emojione") &&
reShortcode.matcher(title).find()
) {
sb.append(options.decodeEmoji(title))
return
} else if (cssClass == "emoji" && url != null && alt != null && reNotestockEmojiAlt.matches(
alt
)
) {
// notestock custom emoji
sb.run {
val start = length
append(alt)
val end = length
setSpan(
NetworkEmojiSpan(url, scale = options.enlargeCustomEmoji),
start,
end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
return
}
}
sb.append("<img ")
val url = attrs["src"] ?: ""
val caption = attrs["alt"] ?: ""
if (caption.isNotEmpty() || url.isNotEmpty()) {
val start = sb.length
sb.append(caption.notEmpty() ?: url)
if (reUrlStart.find(url) != null) {
val span =
MyClickableSpan(
LinkInfo(
url = url,
ac = null,
tag = null,
caption = caption,
mention = null
)
)
sb.setSpan(span, start, sb.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
sb.append(" ")
}
sb.append("/>")
}
class EncodeSpanEnv(
val options: DecodeOptions,
val listContext: ListContext,
val tag: String,
val sb: SpannableStringBuilder,
val sbTmp: SpannableStringBuilder,
val spanStart: Int,
)
val originalFlusher: EncodeSpanEnv.() -> Unit = {
when (tag) {
"s", "strike", "del" -> {
sb.setSpan(
StrikethroughSpan(),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"em" -> {
sb.setSpan(
fontSpan(Typeface.defaultFromStyle(Typeface.ITALIC)),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"strong" -> {
sb.setSpan(
StyleSpan(Typeface.BOLD),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"tr" -> {
sb.append("|")
}
"style", "script" -> {
// sb_tmpにレンダリングした分は読み捨てる
}
"h1" -> {
sb.setSpan(
StyleSpan(Typeface.BOLD),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.setSpan(
RelativeSizeSpan(1.8f),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"h2" -> {
sb.setSpan(
StyleSpan(Typeface.BOLD),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.setSpan(
RelativeSizeSpan(1.6f),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"h3" -> {
sb.setSpan(
StyleSpan(Typeface.BOLD),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.setSpan(
RelativeSizeSpan(1.4f),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"h4" -> {
sb.setSpan(
StyleSpan(Typeface.BOLD),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.setSpan(
RelativeSizeSpan(1.2f),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"h5" -> {
sb.setSpan(
StyleSpan(Typeface.BOLD),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.setSpan(
RelativeSizeSpan(1.0f),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"h6" -> {
sb.setSpan(
StyleSpan(Typeface.BOLD),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.setSpan(
RelativeSizeSpan(0.8f),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"pre" -> {
sb.setSpan(
BackgroundColorSpan(0x40808080),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.setSpan(
RelativeSizeSpan(0.7f),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.setSpan(
fontSpan(Typeface.MONOSPACE),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"code" -> {
sb.setSpan(
BackgroundColorSpan(0x40808080),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.setSpan(
fontSpan(Typeface.MONOSPACE),
spanStart,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
"hr" -> sb.append("----------")
}
}
val tmpFlusher = HashMap<String, EncodeSpanEnv.() -> Unit>().apply {
fun add(vararg tags: String, block: EncodeSpanEnv.() -> Unit) {
for (tag in tags) this[tag] = block
}
add("a") {
val linkInfo = formatLinkCaption(options, sbTmp, href ?: "")
val caption = linkInfo.caption
if (caption.isNotEmpty()) {
val start = sb.length
sb.append(linkInfo.caption)
val end = sb.length
if (linkInfo.url.isNotEmpty()) {
val span = MyClickableSpan(linkInfo)
sb.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
// リンクスパンを設定した後に色をつける
val list = options.highlightTrie?.matchList(sb, start, end)
if (list != null) {
for (range in list) {
val word = HighlightWord.load(range.word) ?: continue
sb.setSpan(
HighlightSpan(word.color_fg, word.color_bg),
range.start,
range.end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
if (word.sound_type != HighlightWord.SOUND_TYPE_NONE) {
if (options.highlightSound == null) options.highlightSound = word
}
if (word.speech != 0) {
if (options.highlightSpeech == null) options.highlightSpeech = word
}
if (options.highlightAny == null) options.highlightAny = word
}
}
}
}
add("style", "script") {
// 読み捨てる
// 最適化によりtmpFlusherOriginalとこのラムダが同一オブジェクトにならないようにする
}
add("blockquote") {
val bg_color = listContext.quoteColor()
// TextView の文字装飾では「ブロック要素の入れ子」を表現できない
// 内容の各行の始端に何か追加するというのがまずキツい
// しかし各行の頭に引用マークをつけないと引用のネストで意味が通じなくなってしまう
val startItalic = sb.length
sbTmp.splitLines().forEach { line ->
val lineStart = sb.length
sb.append("> ")
sb.setSpan(
BackgroundColorSpan(bg_color),
lineStart,
lineStart + 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.append(line)
}
sb.setSpan(
fontSpan(Typeface.defaultFromStyle(Typeface.ITALIC)),
startItalic,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
add("li") {
val lineHeader1 = listContext.increment()
val lineHeader2 = " ".repeat(lineHeader1.length)
sbTmp.splitLines().forEachIndexed { i, line ->
sb.append(if (i == 0) lineHeader1 else lineHeader2)
sb.append(line)
}
}
add("dt") {
val prefix = listContext.increment()
val startBold = sb.length
sbTmp.splitLines().forEach { line ->
sb.append(prefix)
sb.append(line)
}
sb.setSpan(
fontSpan(Typeface.defaultFromStyle(Typeface.BOLD)),
startBold,
sb.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
add("dd") {
val prefix = listContext.increment() + " "
sbTmp.splitLines().forEach { line ->
sb.append(prefix)
sb.append(line)
}
}
}
fun childListContext(tag: String, outerContext: ListContext) = when (tag) {
"ol" -> outerContext.subOrdered()
"ul" -> outerContext.subUnordered()
"dl" -> outerContext.subDefinition()
"blockquote" -> outerContext.subQuote()
else -> outerContext
}
fun encodeSpan(
options: DecodeOptions,
sb: SpannableStringBuilder,
listContext: ListContext,
) {
val isBlock = blockLevelElements.contains(tag)
when (tag) {
TAG_TEXT -> {
encodeText(options, sb)
return
}
"img" -> {
encodeImage(options, sb)
return
}
"script", "style" -> return
"th", "td" -> sb.append("|")
else -> if (isBlock && tag != "script" && tag != "style") {
val lastLine = reLastLine.find(sb)?.groupValues?.firstOrNull() ?: ""
if (CharacterGroup.reNotWhitespace.matcher(lastLine).find()) {
sb.append("\n")
}
}
}
var flusher = this.tmpFlusher[tag]
val encodeSpanEnv = if (flusher != null) {
// 一時的なバッファに子要素を出力して、後で何か処理する
EncodeSpanEnv(
options = options,
listContext = listContext,
tag = tag,
sb = sb,
sbTmp = SpannableStringBuilder(),
spanStart = 0,
)
} else {
// 現在のバッファに出力する
flusher = originalFlusher
EncodeSpanEnv(
options = options,
listContext = listContext,
tag = tag,
sb = sb,
sbTmp = sb,
spanStart = sb.length
)
}
val childListContext = childListContext(tag, listContext)
child_nodes.forEachIndexed { i, child ->
if (!canSkipEncode(
isBlock,
curr = child,
parent = this,
prev = child_nodes.elementAtOrNull(i - 1),
next = child_nodes.elementAtOrNull(i + 1)
)
) {
child.encodeSpan(options, encodeSpanEnv.sbTmp, childListContext)
}
}
flusher(encodeSpanEnv)
if (isBlock) {
// ブロック要素
// 末尾の改行が2文字未満なら改行を追加する
var appendCount = 2 - sb.lastBrCount()
if (listContext.inList()) appendCount = min(1, appendCount)
when (tag) {
"tr" -> appendCount = min(1, appendCount)
"thead", "tfoot", "tbody" -> appendCount = 0
}
repeat(appendCount) { sb.append("\n") }
} else {
// インライン要素で改行タグでテキストがカラでないなら、改行を追加する
if ("br" == tag && sb.isNotEmpty()) sb.append('\n')
}
}
}
// split attributes
private fun parseAttributes(text: String): HashMap<String, String> {
val dst = HashMap<String, String>()
val m = reAttribute.matcher(text)
while (m.find()) {
val name = m.groupEx(1)!!.lowercase()
val value = decodeEntity(m.groupEx(3))
dst[name] = value
}
return dst
}
fun decodeHTML(options: DecodeOptions, src: String?): SpannableStringBuilder {
if (options.linkHelper?.isMisskey == true && !options.forceHtml) {
return MisskeyMarkdownDecoder.decodeMarkdown(options, src)
}
val sb = SpannableStringBuilder()
try {
if (src != null) {
// parse HTML node tree
val tracker = TokenParser(src)
val rootNode = Node()
while (TAG_END != tracker.tag) {
rootNode.addChild(tracker, "")
}
// encode to SpannableStringBuilder
rootNode.encodeSpan(options, sb, ListContext(type = ListType.None, 0, 0, 0, 0))
// 末尾の空白を取り除く
sb.removeEndWhitespaces()
}
} catch (ex: Throwable) {
log.trace(ex)
}
return sb
}
fun decodeMentions(
linkHelper: LinkHelper,
status: TootStatus,
): Spannable? {
val mentionList: List<TootMention>? = status.mentions
val link_tag: Any = status
if (mentionList == null || mentionList.isEmpty()) return null
val sb = SpannableStringBuilder()
for (item in mentionList) {
if (sb.isNotEmpty()) sb.append(" ")
val fullAcct = getFullAcctOrNull(
item.acct,
item.url,
linkHelper,
status.account
)
val linkInfo = if (fullAcct != null) {
LinkInfo(
url = item.url,
caption = "@${(if (PrefB.bpMentionFullAcct()) fullAcct else item.acct).pretty}",
ac = AcctColor.load(fullAcct),
mention = item,
tag = link_tag
)
} else {
LinkInfo(
url = item.url,
caption = "@${item.acct.pretty}",
ac = null,
mention = item,
tag = link_tag
)
}
val start = sb.length
sb.append(linkInfo.caption)
val end = sb.length
if (end > start) sb.setSpan(
MyClickableSpan(linkInfo),
start,
end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
return sb
}
private val reNormalLink = """\A(\w+://)[^/]*""".asciiPattern()
// URLの表記を短くする
// Punycode のデコードはサーバ側で行われる?ので、ここでは元リンクの表示テキストを元にURL短縮を試みる
fun shortenUrl(originalUrl: CharSequence): CharSequence {
try {
val m = reNormalLink.matcher(originalUrl)
if (m.find()) return SpannableStringBuilder().apply {
// 文字装飾をそのまま残したいのでsubSequenceを返す
// WebUIでは非表示スパンに隠れているが、
// 通常のリンクなら スキーマ名 + :// が必ず出現する
val schema = m.groupEx(1)
val start = if (schema?.startsWith("http") == true) {
// http,https の場合はスキーマ表記を省略する
schema.length
} else {
// その他のスキーマもMastodonでは許容される
// この場合はスキーマ名を省略しない
// https://github.com/tootsuite/mastodon/pull/7810
0
}
val length = originalUrl.length
val limit = m.end() + 10 // 10 characters for ( path + query + fragment )
if (length > limit) {
append(originalUrl.subSequence(start, limit))
append('…')
} else {
append(originalUrl.subSequence(start, length))
}
}
} catch (ex: Throwable) {
log.trace(ex)
}
return originalUrl
}
private val reNicodic = """\Ahttps?://dic.nicovideo.jp/a/([^?#/]+)""".asciiPattern()
private fun formatLinkCaption(
options: DecodeOptions,
originalCaption: CharSequence,
href: String,
) = LinkInfo(
caption = originalCaption,
url = href,
tag = options.linkTag
).also { linkInfo ->
when (originalCaption.firstOrNull()) {
// #hashtag は変更しない
'#' -> {
}
// @mention
'@' -> {
fun afterFullAcctResolved(fullAcct: Acct) {
linkInfo.ac = AcctColor.load(fullAcct)
if (options.mentionFullAcct || PrefB.bpMentionFullAcct()) {
linkInfo.caption = "@${fullAcct.pretty}"
}
}
// https://github.com/tateisu/SubwayTooter/issues/108
// check mentions to skip getAcctFromUrl
val mention = options.mentions?.find { it.url == href }
if (mention != null) {
getFullAcctOrNull(
mention.acct,
href,
options.authorDomain,
options.linkHelper,
)?.let { afterFullAcctResolved(it) }
} else {
// case A
// Account.note does not have mentions metadata.
// fallback to resolve acct by mention URL.
// case B
// https://mastodon.juggler.jp/@tateisu/104897039191509317
// リモートのMisskeyからMastodonに流れてきた投稿をSTで見ると
// (元タンスでの)ローカルメンションに対して間違って閲覧者のドメインが補われる
// STのバグかと思ったけど、データみたらmentionsメタデータに一つ目のメンションのURLが含まれてない。
// 閲覧サーバがメンションに含まれるアカウントを解決できなかった際に発生するらしい。
// メンション情報がない場合がありうる。
// acctのドメイン部分を補う際、閲覧者のドメインや投稿者のドメインへの変換を試みる
val rawAcct = Acct.parse(originalCaption.toString().substring(1))
getFullAcctOrNull(
rawAcct,
href,
options.authorDomain,
options.linkHelper,
)?.let { fullAcct ->
// mentionメタデータを捏造する
linkInfo.mention = TootMention(
id = EntityId.DEFAULT,
url = href,
acct = fullAcct,
username = rawAcct.username
)
afterFullAcctResolved(fullAcct)
}
}
}
else -> {
val context = options.context
when {
context == null || !options.short || href.isEmpty() -> {
}
options.isMediaAttachment(href) -> {
// 添付メディアのURLなら絵文字に変換する
linkInfo.caption = SpannableString(href).apply {
setSpan(
SvgEmojiSpan(context, "emj_1f5bc.svg", scale = 1f),
0,
length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
return@also
}
else -> {
// ニコニコ大百科のURLを変える
val m = reNicodic.matcher(href)
when {
m.find() -> {
linkInfo.caption =
SpannableString(
"${
m.groupEx(1)!!.decodePercent()
}:nicodic:"
).apply {
setSpan(
EmojiImageSpan(context, R.drawable.nicodic),
length - 9,
length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
return@also
}
else -> linkInfo.caption = shortenUrl(originalCaption)
}
}
}
}
}
}
private fun init1() {
defineEntity("amp", '&') // ampersand
defineEntity("gt", '>') // greater than
defineEntity("lt", '<') // less than
defineEntity("quot", '"') // double quote
defineEntity("apos", '\'') // single quote
defineEntity("AElig", chr(198)) // capital AE diphthong (ligature)
defineEntity("Aacute", chr(193)) // capital A, acute accent
defineEntity("Acirc", chr(194)) // capital A, circumflex accent
defineEntity("Agrave", chr(192)) // capital A, grave accent
defineEntity("Aring", chr(197)) // capital A, ring
defineEntity("Atilde", chr(195)) // capital A, tilde
defineEntity("Auml", chr(196)) // capital A, dieresis or umlaut mark
defineEntity("Ccedil", chr(199)) // capital C, cedilla
defineEntity("ETH", chr(208)) // capital Eth, Icelandic
defineEntity("Eacute", chr(201)) // capital E, acute accent
defineEntity("Ecirc", chr(202)) // capital E, circumflex accent
defineEntity("Egrave", chr(200)) // capital E, grave accent
defineEntity("Euml", chr(203)) // capital E, dieresis or umlaut mark
defineEntity("Iacute", chr(205)) // capital I, acute accent
defineEntity("Icirc", chr(206)) // capital I, circumflex accent
defineEntity("Igrave", chr(204)) // capital I, grave accent
defineEntity("Iuml", chr(207)) // capital I, dieresis or umlaut mark
defineEntity("Ntilde", chr(209)) // capital N, tilde
defineEntity("Oacute", chr(211)) // capital O, acute accent
defineEntity("Ocirc", chr(212)) // capital O, circumflex accent
defineEntity("Ograve", chr(210)) // capital O, grave accent
defineEntity("Oslash", chr(216)) // capital O, slash
defineEntity("Otilde", chr(213)) // capital O, tilde
defineEntity("Ouml", chr(214)) // capital O, dieresis or umlaut mark
defineEntity("THORN", chr(222)) // capital THORN, Icelandic
defineEntity("Uacute", chr(218)) // capital U, acute accent
defineEntity("Ucirc", chr(219)) // capital U, circumflex accent
defineEntity("Ugrave", chr(217)) // capital U, grave accent
defineEntity("Uuml", chr(220)) // capital U, dieresis or umlaut mark
defineEntity("Yacute", chr(221)) // capital Y, acute accent
defineEntity("aacute", chr(225)) // small a, acute accent
defineEntity("acirc", chr(226)) // small a, circumflex accent
defineEntity("aelig", chr(230)) // small ae diphthong (ligature)
defineEntity("agrave", chr(224)) // small a, grave accent
defineEntity("aring", chr(229)) // small a, ring
defineEntity("atilde", chr(227)) // small a, tilde
defineEntity("auml", chr(228)) // small a, dieresis or umlaut mark
defineEntity("ccedil", chr(231)) // small c, cedilla
defineEntity("eacute", chr(233)) // small e, acute accent
defineEntity("ecirc", chr(234)) // small e, circumflex accent
defineEntity("egrave", chr(232)) // small e, grave accent
defineEntity("eth", chr(240)) // small eth, Icelandic
defineEntity("euml", chr(235)) // small e, dieresis or umlaut mark
defineEntity("iacute", chr(237)) // small i, acute accent
defineEntity("icirc", chr(238)) // small i, circumflex accent
defineEntity("igrave", chr(236)) // small i, grave accent
defineEntity("iuml", chr(239)) // small i, dieresis or umlaut mark
defineEntity("ntilde", chr(241)) // small n, tilde
defineEntity("oacute", chr(243)) // small o, acute accent
defineEntity("ocirc", chr(244)) // small o, circumflex accent
defineEntity("ograve", chr(242)) // small o, grave accent
defineEntity("oslash", chr(248)) // small o, slash
defineEntity("otilde", chr(245)) // small o, tilde
defineEntity("ouml", chr(246)) // small o, dieresis or umlaut mark
defineEntity("szlig", chr(223)) // small sharp s, German (sz ligature)
defineEntity("thorn", chr(254)) // small thorn, Icelandic
defineEntity("uacute", chr(250)) // small u, acute accent
defineEntity("ucirc", chr(251)) // small u, circumflex accent
defineEntity("ugrave", chr(249)) // small u, grave accent
defineEntity("uuml", chr(252)) // small u, dieresis or umlaut mark
defineEntity("yacute", chr(253)) // small y, acute accent
defineEntity("yuml", chr(255)) // small y, dieresis or umlaut mark
defineEntity("copy", chr(169)) // copyright sign
defineEntity("reg", chr(174)) // registered sign
defineEntity("nbsp", chr(160)) // non breaking space
defineEntity("iexcl", chr(161))
defineEntity("cent", chr(162))
defineEntity("pound", chr(163))
defineEntity("curren", chr(164))
defineEntity("yen", chr(165))
defineEntity("brvbar", chr(166))
defineEntity("sect", chr(167))
defineEntity("uml", chr(168))
defineEntity("ordf", chr(170))
defineEntity("laquo", chr(171))
defineEntity("not", chr(172))
defineEntity("shy", chr(173))
defineEntity("macr", chr(175))
defineEntity("deg", chr(176))
defineEntity("plusmn", chr(177))
defineEntity("sup1", chr(185))
defineEntity("sup2", chr(178))
defineEntity("sup3", chr(179))
defineEntity("acute", chr(180))
defineEntity("micro", chr(181))
defineEntity("para", chr(182))
defineEntity("middot", chr(183))
defineEntity("cedil", chr(184))
defineEntity("ordm", chr(186))
defineEntity("raquo", chr(187))
defineEntity("frac14", chr(188))
defineEntity("frac12", chr(189))
defineEntity("frac34", chr(190))
defineEntity("iquest", chr(191))
defineEntity("times", chr(215))
}
private fun init2() {
defineEntity("divide", chr(247))
defineEntity("OElig", chr(338))
defineEntity("oelig", chr(339))
defineEntity("Scaron", chr(352))
defineEntity("scaron", chr(353))
defineEntity("Yuml", chr(376))
defineEntity("fnof", chr(402))
defineEntity("circ", chr(710))
defineEntity("tilde", chr(732))
defineEntity("Alpha", chr(913))
defineEntity("Beta", chr(914))
defineEntity("Gamma", chr(915))
defineEntity("Delta", chr(916))
defineEntity("Epsilon", chr(917))
defineEntity("Zeta", chr(918))
defineEntity("Eta", chr(919))
defineEntity("Theta", chr(920))
defineEntity("Iota", chr(921))
defineEntity("Kappa", chr(922))
defineEntity("Lambda", chr(923))
defineEntity("Mu", chr(924))
defineEntity("Nu", chr(925))
defineEntity("Xi", chr(926))
defineEntity("Omicron", chr(927))
defineEntity("Pi", chr(928))
defineEntity("Rho", chr(929))
defineEntity("Sigma", chr(931))
defineEntity("Tau", chr(932))
defineEntity("Upsilon", chr(933))
defineEntity("Phi", chr(934))
defineEntity("Chi", chr(935))
defineEntity("Psi", chr(936))
defineEntity("Omega", chr(937))
defineEntity("alpha", chr(945))
defineEntity("beta", chr(946))
defineEntity("gamma", chr(947))
defineEntity("delta", chr(948))
defineEntity("epsilon", chr(949))
defineEntity("zeta", chr(950))
defineEntity("eta", chr(951))
defineEntity("theta", chr(952))
defineEntity("iota", chr(953))
defineEntity("kappa", chr(954))
defineEntity("lambda", chr(955))
defineEntity("mu", chr(956))
defineEntity("nu", chr(957))
defineEntity("xi", chr(958))
defineEntity("omicron", chr(959))
defineEntity("pi", chr(960))
defineEntity("rho", chr(961))
defineEntity("sigmaf", chr(962))
defineEntity("sigma", chr(963))
defineEntity("tau", chr(964))
defineEntity("upsilon", chr(965))
defineEntity("phi", chr(966))
defineEntity("chi", chr(967))
defineEntity("psi", chr(968))
defineEntity("omega", chr(969))
defineEntity("thetasym", chr(977))
defineEntity("upsih", chr(978))
defineEntity("piv", chr(982))
defineEntity("ensp", chr(8194))
defineEntity("emsp", chr(8195))
defineEntity("thinsp", chr(8201))
defineEntity("zwnj", chr(8204))
defineEntity("zwj", chr(8205))
defineEntity("lrm", chr(8206))
defineEntity("rlm", chr(8207))
defineEntity("ndash", chr(8211))
defineEntity("mdash", chr(8212))
defineEntity("lsquo", chr(8216))
defineEntity("rsquo", chr(8217))
defineEntity("sbquo", chr(8218))
defineEntity("ldquo", chr(8220))
defineEntity("rdquo", chr(8221))
defineEntity("bdquo", chr(8222))
defineEntity("dagger", chr(8224))
defineEntity("Dagger", chr(8225))
defineEntity("bull", chr(8226))
defineEntity("hellip", chr(8230))
defineEntity("permil", chr(8240))
defineEntity("prime", chr(8242))
defineEntity("Prime", chr(8243))
defineEntity("lsaquo", chr(8249))
defineEntity("rsaquo", chr(8250))
defineEntity("oline", chr(8254))
defineEntity("frasl", chr(8260))
defineEntity("euro", chr(8364))
defineEntity("image", chr(8465))
defineEntity("weierp", chr(8472))
defineEntity("real", chr(8476))
defineEntity("trade", chr(8482))
defineEntity("alefsym", chr(8501))
defineEntity("larr", chr(8592))
defineEntity("uarr", chr(8593))
defineEntity("rarr", chr(8594))
defineEntity("darr", chr(8595))
defineEntity("harr", chr(8596))
defineEntity("crarr", chr(8629))
defineEntity("lArr", chr(8656))
}
private fun init3() {
defineEntity("uArr", chr(8657))
defineEntity("rArr", chr(8658))
defineEntity("dArr", chr(8659))
defineEntity("hArr", chr(8660))
defineEntity("forall", chr(8704))
defineEntity("part", chr(8706))
defineEntity("exist", chr(8707))
defineEntity("empty", chr(8709))
defineEntity("nabla", chr(8711))
defineEntity("isin", chr(8712))
defineEntity("notin", chr(8713))
defineEntity("ni", chr(8715))
defineEntity("prod", chr(8719))
defineEntity("sum", chr(8721))
defineEntity("minus", chr(8722))
defineEntity("lowast", chr(8727))
defineEntity("radic", chr(8730))
defineEntity("prop", chr(8733))
defineEntity("infin", chr(8734))
defineEntity("ang", chr(8736))
defineEntity("and", chr(8743))
defineEntity("or", chr(8744))
defineEntity("cap", chr(8745))
defineEntity("cup", chr(8746))
defineEntity("int", chr(8747))
defineEntity("there4", chr(8756))
defineEntity("sim", chr(8764))
defineEntity("cong", chr(8773))
defineEntity("asymp", chr(8776))
defineEntity("ne", chr(8800))
defineEntity("equiv", chr(8801))
defineEntity("le", chr(8804))
defineEntity("ge", chr(8805))
defineEntity("sub", chr(8834))
defineEntity("sup", chr(8835))
defineEntity("nsub", chr(8836))
defineEntity("sube", chr(8838))
defineEntity("supe", chr(8839))
defineEntity("oplus", chr(8853))
defineEntity("otimes", chr(8855))
defineEntity("perp", chr(8869))
defineEntity("sdot", chr(8901))
defineEntity("lceil", chr(8968))
defineEntity("rceil", chr(8969))
defineEntity("lfloor", chr(8970))
defineEntity("rfloor", chr(8971))
defineEntity("lang", chr(9001))
defineEntity("rang", chr(9002))
defineEntity("loz", chr(9674))
defineEntity("spades", chr(9824))
defineEntity("clubs", chr(9827))
defineEntity("hearts", chr(9829))
defineEntity("diams", chr(9830))
}
init {
init1()
init2()
init3()
}
}
|
apache-2.0
|
3415b72d7942d16807d3ddedabb36f6b
| 34.26174 | 112 | 0.443027 | 4.688125 | false | false | false | false |
TechzoneMC/SonarPet
|
api/src/main/kotlin/net/techcable/sonarpet/utils/UniqueCollection.kt
|
1
|
1260
|
package net.techcable.sonarpet.utils
/**
* A [Collection] that contains no duplicates,
* and can be used as a [Set].
*/
class UniqueCollection<out T>(
private val handle: Collection<T>
): Set<T> {
override fun iterator(): Iterator<T> {
return DuplicateCheckingIterator(
delegate = handle.iterator(),
expectedSize = handle.size
)
}
private class DuplicateCheckingIterator<out T>(
private val delegate: Iterator<T>,
expectedSize: Int
): Iterator<T> {
private val seenElements: MutableSet<T> = HashSet(((expectedSize / 0.75) + 1).toInt())
override fun hasNext() = delegate.hasNext()
override fun next(): T {
val element = delegate.next()
if (!seenElements.add(element)) {
throw IllegalStateException("Duplicate elements: $element")
}
return element
}
}
// Plain delegates
override fun isEmpty() = handle.isEmpty()
override val size: Int
get() = handle.size
override fun contains(element: @UnsafeVariance T) = handle.contains(element)
override fun containsAll(elements: Collection<@UnsafeVariance T>) = handle.containsAll(elements)
}
|
gpl-3.0
|
92dd3b76d077e08d16dd8fc8a31a7145
| 32.157895 | 100 | 0.613492 | 4.666667 | false | false | false | false |
xmartlabs/Android-Base-Project
|
ui/src/main/java/com/xmartlabs/bigbang/ui/common/recyclerview/RecyclerViewEmptySupport.kt
|
1
|
5159
|
package com.xmartlabs.bigbang.ui.common.recyclerview
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.annotation.IdRes
import androidx.recyclerview.widget.RecyclerView
import com.xmartlabs.bigbang.ui.R
/**
* [RecyclerView] subclass that automatically handles empty state.
*
* A [RecyclerView] is in an empty state when its adapter holds zero items,
* or if the callback function [.isInEmptyState] is set and returns true.
*
* In the empty state, the [] will be hidden and a view will be shown.
* The empty state view to be shown can be defined in two ways:
*
* 1. By means of [.setEmptyView] method
* 2. By setting the attribute `app:emptyViewId` in the recycler view and point to a view in the hierarchy
*/
class RecyclerViewEmptySupport @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : RecyclerView(context, attrs, defStyle) {
private var emptyView: View? = null
@IdRes
private var emptyViewId: Int = 0
private var isInEmptyState: ((RecyclerView) -> Boolean)? = null
private val emptyObserver = object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
super.onChanged()
showCorrectView()
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
super.onItemRangeInserted(positionStart, itemCount)
showCorrectView()
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
super.onItemRangeRemoved(positionStart, itemCount)
showCorrectView()
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
super.onItemRangeChanged(positionStart, itemCount)
showCorrectView()
}
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
super.onItemRangeMoved(fromPosition, toPosition, itemCount)
showCorrectView()
}
}
init {
bindAttributes(context, attrs)
initializeEmptyView()
}
/**
* Extracts the resource id from the [RecyclerView] attributes, if present.
*
* @param context The Context the view is running in, through which it can
* * access the current theme, resources, etc.
* *
* @param attrs The attributes of the XML tag that is inflating the view.
*/
private fun bindAttributes(context: Context, attrs: AttributeSet?) {
val attributes = context.obtainStyledAttributes(attrs, R.styleable.RecyclerViewEmptySupport, 0, 0)
emptyViewId = attributes.getResourceId(R.styleable.RecyclerViewEmptySupport_emptyView, -1)
attributes.recycle()
}
/** Initializes the empty view using the resource identifier [.emptyViewId], if it exists. */
private fun initializeEmptyView() {
if (emptyViewId > 0) {
post {
rootView.findViewById<View>(emptyViewId)?.let { view ->
emptyView = view
showCorrectView()
}
}
}
}
/**
* Decides which view should be visible (recycler view or empty view) and shows it
* To do that, it checks for the presence of [.isInEmptyState] callback and uses it to determine whether or not
* the empty view should be shown.
* If the callback was not set, then it uses the adapter item count information, where zero elements means the empty
* state should be shown.
*/
private fun showCorrectView() {
val adapter = adapter
emptyView?.let {
val hasItems = isInEmptyState?.let { it(this) } ?: (adapter == null || adapter.itemCount > 0)
it.visibility = if (hasItems) View.GONE else View.VISIBLE
visibility = if (hasItems) View.VISIBLE else View.GONE
}
}
override fun setAdapter(adapter: RecyclerView.Adapter<*>?) {
super.setAdapter(adapter)
adapter?.let {
try {
adapter.registerAdapterDataObserver(emptyObserver)
} catch (ignored: IllegalStateException) { // the observer is already registered
}
}
emptyObserver.onChanged()
}
/**
* Sets the empty view.
* If null, the [.showCorrectView] method will yield no further effect, unless the [.emptyViewId] was
* set and the [.resetState] is called.
*
* @param emptyView the empty view to show on empty state
*/
fun setEmptyView(emptyView: View?) {
this.emptyView = emptyView
}
/**
* Sets the empty state callback check.
* The callback will be called each time a decision is to be made to whether show or hide the empty view.
*
* @param isInEmptyState the callback function to determine if the recycler view is in an empty state
*/
fun setIsInEmptyState(isInEmptyState: ((RecyclerView) -> Boolean)?) {
this.isInEmptyState = isInEmptyState
showCorrectView()
}
/**
* Resets the state of the recycler view.
* If no empty view is present, an attempt to retrieve it from the resource id will be made.
* If it's already present, then the recycler view will check whether or not is in an empty state and act
* accordingly (show/hide the empty view/itself).
*/
fun resetState() {
if (emptyView == null) {
initializeEmptyView()
} else {
showCorrectView()
}
}
}
|
apache-2.0
|
78be826dc0fd7dff0f93e3730da87508
| 32.940789 | 118 | 0.697228 | 4.413174 | false | false | false | false |
vkurdin/idea-php-lambda-folding
|
src/ru/vkurdin/idea/php/lambdafolding/LambdaFoldingBuilder.kt
|
1
|
5094
|
package ru.vkurdin.idea.php.lambdafolding
import com.intellij.lang.ASTNode
import com.intellij.lang.folding.FoldingBuilderEx
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.FoldingGroup
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.PsiTreeUtil as IdeaUtils
import com.jetbrains.php.lang.psi.elements.*
import com.jetbrains.php.lang.psi.elements.Function
class LambdaFoldingBuilder : FoldingBuilderEx(), DumbAware {
class ClosureParts(
val closure: Function, // closure body
val params: ParameterList, // parameters
val use: PhpUseList?, // "use" construct
val returnType: ClassReference?, // function return type(if any)
val expression: PhpExpression // returned expression
)
override fun buildFoldRegions(root: PsiElement, document: Document, quick: Boolean): Array<out FoldingDescriptor> =
IdeaUtils
.findChildrenOfType(root, Function::class.java)
.asSequence()
.filter {
// match one-liner closures w/o errors
it.isClosure &&
(document.getLineNumber(it.textRange.startOffset) == document.getLineNumber(it.textRange.endOffset)) &&
!IdeaUtils.hasErrorElements(it)
}
.map { closure ->
var params: ParameterList? = null
var bodyStmts: GroupStatement? = null
var use: PhpUseList? = null
var type: ClassReference? = null
closure.children.forEach {
when (it) {
is ParameterList -> params = it
is GroupStatement -> bodyStmts = it
is PhpUseList -> use = it
is ClassReference -> type = it
}
}
params
?. let { bodyStmts } // params and bodyStmts must be found
?. statements
?. asSequence()
?. filterIsInstance<Statement>()
?. take(2) // take at most two statements
?. toList() ?.letIf { it.size == 1 } // closure body must contain exactly one ...
?. first() ?.let { it as? PhpReturn } // ... return statement which result is ...
?. argument ?.let { it as? PhpExpression } // ...an arbitrary expression
?. let { expression -> ClosureParts(closure, params!!, use, type, expression) }
}
.filterNotNull()
.flatMap { parts ->
val foldGroup = FoldingGroup.newGroup("lambda_fold")
var useVars = emptyList<Variable>()
parts.use ?.let {
useVars = it.children.filterIsInstance<Variable>()
}
// hide "function", "return" keywords, semicolon
sequenceOf(
getFold(
parts.closure.node,
TextRange(
parts.closure.textRange.startOffset,
parts.params
.prevSiblings()
.filter { it is LeafPsiElement && it.text == "(" } // locate left parenthesis
.first()
.textRange.startOffset
),
"{ ",
foldGroup
),
getFold(
parts.closure.node,
TextRange(
if (parts.returnType == null) {
// no return type info
(if (useVars.isEmpty()) parts.params else useVars.last()) // search start point depends on "use" presense
.nextSiblings()
.filter { it is LeafPsiElement && it.text == ")" } // locate right parenthesis
.first()
.textRange.endOffset
} else {
parts.returnType.textRange.endOffset
},
parts.expression.textRange.startOffset
),
" => ",
foldGroup
),
getFold(
parts.closure.node,
TextRange(
parts.expression.textRange.endOffset,
parts.closure.textRange.endOffset
),
" }",
foldGroup
)
)
}
.toList()
.toTypedArray()
private fun getFold(node: ASTNode, range: TextRange, placeholder: String, group: FoldingGroup) =
object : FoldingDescriptor(node, range, group) {
override fun getPlaceholderText() = placeholder
}
override fun getPlaceholderText(node: ASTNode) = "..."
override fun isCollapsedByDefault(node: ASTNode) = true
}
|
mit
|
546fe45b3b7f4e4be4084e3261ae4631
| 39.436508 | 133 | 0.522772 | 5.430704 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/AbstractFileRankingTest.kt
|
1
|
5712
|
// 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.debugger.test
import com.intellij.openapi.application.runReadAction
import com.sun.jdi.ThreadReference
import org.jetbrains.kotlin.codegen.OriginCollectingClassBuilderFactory
import org.jetbrains.kotlin.codegen.getClassFiles
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.idea.debugger.FileRankingCalculator
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.org.objectweb.asm.tree.ClassNode
import org.junit.Assert
abstract class AbstractFileRankingTest : LowLevelDebuggerTestBase() {
override fun doTest(
options: Set<String>,
mainThread: ThreadReference,
factory: OriginCollectingClassBuilderFactory,
state: GenerationState
) {
val doNotCheckClassFqName = "DO_NOT_CHECK_CLASS_FQNAME" in options
val strictMode = "DISABLE_STRICT_MODE" !in options
val classNameToKtFile = factory.collectClassNamesToKtFiles()
val files = classNameToKtFile.values.distinct()
val expectedRanks: Map<Pair<KtFile, Int>, Int> = files.asSequence().flatMap { ktFile ->
ktFile.text.lines()
.asSequence()
.withIndex()
.map {
val matchResult = "^.*// (R: (-?\\d+)( L: (\\d+))?)\\s*$".toRegex().matchEntire(it.value) ?: return@map null
val rank = matchResult.groupValues[2].toInt()
val line = matchResult.groupValues.getOrNull(4)?.takeIf { !it.isEmpty() }?.toInt()
if (line != null && line != it.index + 1) {
throw IllegalArgumentException("Bad line in directive at ${ktFile.name}:${it.index + 1}\n${it.value}")
}
(ktFile to it.index + 1) to rank
}
.filterNotNull()
}.toMap()
val calculator = object : FileRankingCalculator(checkClassFqName = !doNotCheckClassFqName) {
override fun analyze(element: KtElement) = state.bindingContext
}
val problems = mutableListOf<String>()
val skipClasses = skipLoadingClasses(options)
val classFileFactory = state.factory
for (outputFile in classFileFactory.getClassFiles()) {
val className = outputFile.internalName.replace('/', '.')
if (className in skipClasses) {
continue
}
val expectedFile = classNameToKtFile[className] ?: throw IllegalStateException("Can't find source for $className")
val jdiClass = mainThread.virtualMachine().classesByName(className).singleOrNull()
?: error("Class '$className' was not found in the debuggee process class loader")
val locations = jdiClass.allLineLocations()
assert(locations.isNotEmpty()) { "There are no locations for class $className" }
val allFilesWithSameName = files.filter { it.name == expectedFile.name }
for (location in locations) {
if (location.method().isBridge || location.method().isSynthetic) continue
val fileWithRankings: Map<KtFile, Int> = runReadAction {
calculator.rankFiles(allFilesWithSameName, location)
}
for ((ktFile, rank) in fileWithRankings) {
val expectedRank = expectedRanks[ktFile to (location.lineNumber())]
if (expectedRank != null) {
Assert.assertEquals("Invalid expected rank at $location", expectedRank, rank)
}
}
val fileWithMaxScore = fileWithRankings.maxByOrNull { it.value }!!
val actualFile = fileWithMaxScore.key
if (strictMode) {
require(fileWithMaxScore.value >= 0) { "Max score is negative at $location" }
// Allow only one element with max ranking
require(fileWithRankings.filter { it.value == fileWithMaxScore.value }.count() == 1) {
"Score is the same for several files at $location"
}
}
if (actualFile != expectedFile) {
problems += "Location ${location.sourceName()}:${location.lineNumber() - 1} is associated with a wrong KtFile:\n" +
" - expected: ${expectedFile.virtualFilePath}\n" +
" - actual: ${actualFile.virtualFilePath}"
}
}
}
if (problems.isNotEmpty()) {
throw AssertionError(buildString {
appendLine("There were association errors:").appendLine()
problems.joinTo(this, "\n\n")
})
}
}
override fun skipLoadingClasses(options: Set<String>): Set<String> {
val skipClasses = options.mapTo(mutableSetOf()) { it.substringAfter("DO_NOT_LOAD:", "").trim() }
skipClasses.remove("")
return skipClasses
}
}
private fun OriginCollectingClassBuilderFactory.collectClassNamesToKtFiles(): Map<String, KtFile> =
runReadAction {
origins.asSequence()
.filter { it.key is ClassNode }
.map {
val ktFile = (it.value.element?.containingFile as? KtFile) ?: return@map null
val name = (it.key as ClassNode).name.replace('/', '.')
name to ktFile
}
.filterNotNull()
.toMap()
}
|
apache-2.0
|
8c97f8234b995ab7c8f0d081b6b75c52
| 42.603053 | 158 | 0.595763 | 5.045936 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinUnresolvedReferenceQuickFixProvider.kt
|
1
|
2074
|
// 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.codeInsight
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.PsiReference
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.highlighter.Fe10QuickFixProvider
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class KotlinUnresolvedReferenceQuickFixProvider: UnresolvedReferenceQuickFixProvider<PsiReference>() {
override fun registerFixes(reference: PsiReference, registrar: QuickFixActionRegistrar) {
val element = reference.element as? KtElement ?: return
val file = runReadAction { element.containingFile }
val project = element.project
val bindingContext = runReadAction { element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) }
val diagnostics = bindingContext.diagnostics.filter {
it.severity == Severity.ERROR && runReadAction { it.psiElement.containingFile == file }
}.ifEmpty { return }
val quickFixProvider = Fe10QuickFixProvider.getInstance(project)
diagnostics.groupBy { it.psiElement }.forEach { (psiElement, sameElementDiagnostics) ->
val textRange = psiElement.textRange
if (textRange in element.textRange) {
sameElementDiagnostics.groupBy { it.factory }.forEach { (_, sameTypeDiagnostic) ->
val quickFixes = quickFixProvider.createUnresolvedReferenceQuickFixes(sameTypeDiagnostic)
quickFixes.values().forEach {
registrar.register(textRange, it, null)
}
}
}
}
}
override fun getReferenceClass(): Class<PsiReference> = PsiReference::class.java
}
|
apache-2.0
|
72dc53b6fc9908a130b94ebb036d3665
| 52.205128 | 120 | 0.729026 | 5.317949 | false | false | false | false |
StepicOrg/stepik-android
|
app/src/main/java/org/stepic/droid/storage/operations/DatabaseFacade.kt
|
1
|
13676
|
package org.stepic.droid.storage.operations
import android.content.ContentValues
import org.stepic.droid.adaptive.model.LocalExpItem
import org.stepic.droid.di.storage.StorageSingleton
import org.stepic.droid.features.stories.model.ViewedStoryTemplate
import org.stepic.droid.model.BlockPersistentWrapper
import org.stepic.droid.model.SearchQuery
import org.stepic.droid.model.ViewedNotification
import org.stepic.droid.notifications.model.Notification
import org.stepic.droid.storage.dao.AdaptiveExpDao
import org.stepic.droid.storage.dao.IDao
import org.stepic.droid.storage.dao.SearchQueryDao
import org.stepic.droid.storage.structure.DbStructureCourse
import org.stepic.droid.storage.structure.DbStructureLastStep
import org.stepic.droid.storage.structure.DbStructureNotification
import org.stepic.droid.storage.structure.DbStructureProgress
import org.stepic.droid.storage.structure.DbStructureVideoTimestamp
import org.stepic.droid.storage.structure.DbStructureViewQueue
import org.stepic.droid.storage.structure.DbStructureViewedNotificationsQueue
import org.stepic.droid.util.AppConstants
import org.stepic.droid.util.DbParseHelper
import org.stepik.android.cache.assignment.structure.DbStructureAssignment
import org.stepik.android.cache.base.database.AppDatabase
import org.stepik.android.cache.course_calendar.structure.DbStructureSectionDateEvent
import org.stepik.android.cache.lesson.structure.DbStructureLesson
import org.stepik.android.cache.personal_deadlines.dao.DeadlinesBannerDao
import org.stepik.android.cache.personal_deadlines.dao.PersonalDeadlinesDao
import org.stepik.android.cache.purchase_notification.dao.PurchaseNotificationDao
import org.stepik.android.cache.section.structure.DbStructureSection
import org.stepik.android.cache.step.structure.DbStructureStep
import org.stepik.android.cache.unit.structure.DbStructureUnit
import org.stepik.android.cache.user_courses.dao.UserCourseDao
import org.stepik.android.cache.video_player.model.VideoTimestamp
import org.stepik.android.data.course_list.model.CourseListQueryData
import org.stepik.android.domain.course_calendar.model.SectionDateEvent
import org.stepik.android.domain.course_payments.model.CoursePayment
import org.stepik.android.domain.last_step.model.LastStep
import org.stepik.android.model.Assignment
import org.stepik.android.model.Certificate
import org.stepik.android.model.Course
import org.stepik.android.model.CourseCollection
import org.stepik.android.model.Lesson
import org.stepik.android.model.Progress
import org.stepik.android.model.Section
import org.stepik.android.model.SocialProfile
import org.stepik.android.model.Step
import org.stepik.android.model.Submission
import org.stepik.android.model.Unit
import org.stepik.android.model.ViewAssignment
import org.stepik.android.model.attempts.Attempt
import org.stepik.android.model.comments.DiscussionThread
import javax.inject.Inject
@StorageSingleton
class DatabaseFacade
@Inject
constructor(
private val searchQueryDao: SearchQueryDao,
private val adaptiveExpDao: AdaptiveExpDao,
private val viewedNotificationsQueueDao: IDao<ViewedNotification>,
private val sectionDao: IDao<Section>,
private val unitDao: IDao<Unit>,
private val progressDao: IDao<Progress>,
private val assignmentDao: IDao<Assignment>,
private val lessonDao: IDao<Lesson>,
private val viewAssignmentDao: IDao<ViewAssignment>,
private val stepDao: IDao<Step>,
private val courseDao: IDao<Course>,
private val notificationDao: IDao<Notification>,
private val videoTimestampDao: IDao<VideoTimestamp>,
private val lastStepDao: IDao<LastStep>,
private val blockDao: IDao<BlockPersistentWrapper>,
private val personalDeadlinesDao: PersonalDeadlinesDao,
private val deadlinesBannerDao: DeadlinesBannerDao,
private val viewedStoryTemplatesDao: IDao<ViewedStoryTemplate>,
private val sectionDateEventDao: IDao<SectionDateEvent>,
private val submissionDao: IDao<Submission>,
private val certificateDao: IDao<Certificate>,
private val discussionThreadDao: IDao<DiscussionThread>,
private val attemptDao: IDao<Attempt>,
private val socialProfileDao: IDao<SocialProfile>,
private val userCourseDao: UserCourseDao,
private val courseCollectionDao: IDao<CourseCollection>,
private val courseListQueryDataDao: IDao<CourseListQueryData>,
private val purchaseNotificationDao: PurchaseNotificationDao,
private val coursePaymentDao: IDao<CoursePayment>,
private val appDatabase: AppDatabase
) {
fun dropDatabase() {
sectionDao.removeAll()
unitDao.removeAll()
progressDao.removeAll()
lessonDao.removeAll()
viewAssignmentDao.removeAll()
viewedNotificationsQueueDao.removeAll()
stepDao.removeAll()
courseDao.removeAll()
notificationDao.removeAll()
lastStepDao.removeAll()
blockDao.removeAll()
videoTimestampDao.removeAll()
assignmentDao.removeAll()
searchQueryDao.removeAll()
adaptiveExpDao.removeAll()
personalDeadlinesDao.removeAll()
deadlinesBannerDao.removeAll()
viewedStoryTemplatesDao.removeAll()
sectionDateEventDao.removeAll()
submissionDao.removeAll()
certificateDao.removeAll()
discussionThreadDao.removeAll()
attemptDao.removeAll()
socialProfileDao.removeAll()
userCourseDao.removeAll()
courseCollectionDao.removeAll()
courseListQueryDataDao.removeAll()
purchaseNotificationDao.removeAll()
coursePaymentDao.removeAll()
appDatabase.clearAllTables()
}
fun addAssignments(assignments: List<Assignment>) {
assignmentDao.insertOrReplaceAll(assignments)
}
fun getAssignments(assignmentsIds: List<Long>): List<Assignment> {
val stringIds = DbParseHelper.parseLongListToString(assignmentsIds, AppConstants.COMMA)
return if (stringIds != null) {
assignmentDao.getAllInRange(DbStructureAssignment.Columns.ID, stringIds)
} else {
emptyList()
}
}
fun getAssignmentByUnitAndStep(unitId: Long, stepId: Long): Assignment? =
assignmentDao
.get(mapOf(
DbStructureAssignment.Columns.UNIT to unitId.toString(),
DbStructureAssignment.Columns.STEP to stepId.toString()
))
fun getStepsById(stepIds: LongArray): List<Step> {
val stringIds = DbParseHelper.parseLongArrayToString(stepIds, AppConstants.COMMA)
return if (stringIds != null) {
stepDao.getAllInRange(DbStructureStep.Column.ID, stringIds)
} else {
emptyList()
}
}
fun getLessonById(lessonId: Long) = lessonDao.get(DbStructureLesson.Columns.ID, lessonId.toString())
fun getSectionById(sectionId: Long) = sectionDao.get(DbStructureSection.Columns.ID, sectionId.toString())
fun getCourseById(courseId: Long) = courseDao.get(DbStructureCourse.Columns.ID, courseId.toString())
fun getProgresses(progressIds: List<String>): List<Progress> {
//todo change implementation of getAllInRange and escape internally
val escapedIds = progressIds
.map {
"\"$it\""
}
.toTypedArray()
val range = DbParseHelper.parseStringArrayToString(escapedIds, AppConstants.COMMA)
return if (range == null) {
emptyList()
} else {
progressDao.getAllInRange(DbStructureProgress.Columns.ID, range)
}
}
fun getUnitsByLessonId(lessonId: Long): List<Unit> =
unitDao.getAll(DbStructureUnit.Columns.LESSON, lessonId.toString())
fun getUnitById(unitId: Long) =
unitDao.get(DbStructureUnit.Columns.ID, unitId.toString())
fun addCourses(courses: List<Course>) {
courseDao.insertOrReplaceAll(courses)
}
fun deleteCourse(courseId: Long) =
courseDao.remove(DbStructureCourse.Columns.ID, courseId.toString())
fun deleteCourses() {
courseDao.removeAll()
}
fun updateCourseIsInWishlist(courseId: Long, isInWishlist: Boolean) {
val contentValues = ContentValues()
contentValues.put(DbStructureCourse.Columns.IS_IN_WISHLIST, isInWishlist)
courseDao.update(DbStructureCourse.Columns.ID, courseId.toString(), contentValues)
}
fun addSections(sections: List<Section>) =
sectionDao.insertOrReplaceAll(sections)
fun addSteps(steps: List<Step>) {
stepDao.insertOrReplaceAll(steps)
}
fun addUnits(units: List<Unit>) =
unitDao.insertOrReplaceAll(units)
fun addLessons(lessons: List<Lesson>) =
lessonDao.insertOrReplaceAll(lessons)
fun removeLessons(courseId: Long) {
lessonDao.removeLike(DbStructureLesson.Columns.COURSES, "%${DbParseHelper.escapeId(courseId.toString())}%")
}
fun addToQueueViewedState(viewState: ViewAssignment) = viewAssignmentDao.insertOrUpdate(viewState)
fun getAllInQueue() = viewAssignmentDao.getAll()
fun addNotification(notification: Notification) {
notificationDao.insertOrUpdate(notification)
}
fun removeAllNotificationsWithCourseId(courseId: Long) {
notificationDao.remove(DbStructureNotification.Column.COURSE_ID, courseId.toString())
}
fun removeFromQueue(viewAssignmentWrapper: ViewAssignment?) {
val assignmentId = viewAssignmentWrapper?.assignment ?: return
viewAssignmentDao.remove(DbStructureViewQueue.Column.ASSIGNMENT_ID, assignmentId.toString())
}
fun addProgresses(progresses: List<Progress>) =
progressDao.insertOrReplaceAll(progresses)
fun getAllNotificationsOfCourse(courseId: Long): List<Notification> =
notificationDao
.getAll(DbStructureNotification.Column.COURSE_ID, courseId.toString())
fun dropOnlyCourseTable() {
courseDao.removeAll()
}
fun getLessonsByIds(lessonIds: LongArray): List<Lesson> {
val stringIds = DbParseHelper.parseLongArrayToString(lessonIds, AppConstants.COMMA)
return if (stringIds != null) {
lessonDao
.getAllInRange(DbStructureLesson.Columns.ID, stringIds)
} else {
emptyList()
}
}
fun addTimestamp(videoTimestamp: VideoTimestamp) {
videoTimestampDao.insertOrUpdate(videoTimestamp)
}
fun getVideoTimestamp(videoId: Long): VideoTimestamp? =
videoTimestampDao.get(DbStructureVideoTimestamp.Column.VIDEO_ID, videoId.toString())
fun updateLastStep(lastStep: LastStep) {
lastStepDao.insertOrUpdate(lastStep)
}
fun getLocalLastStepById(lastStepId: String?): LastStep? =
lastStepId?.let { lastStepDao.get(DbStructureLastStep.Columns.ID, it) }
fun getUnitsByIds(keys: List<Long>): List<Unit> {
DbParseHelper.parseLongListToString(keys, AppConstants.COMMA)?.let {
return unitDao.getAllInRange(DbStructureUnit.Columns.ID, it)
}
return emptyList()
}
fun getSectionsByIds(keys: List<Long>): List<Section> {
DbParseHelper.parseLongListToString(keys, AppConstants.COMMA)?.let {
return sectionDao.getAllInRange(DbStructureSection.Columns.ID, it)
}
return emptyList()
}
fun getSearchQueries(courseId: Long, constraint: String, count: Int) =
searchQueryDao.getSearchQueries(courseId, constraint, count)
fun addSearchQuery(searchQuery: SearchQuery) {
searchQueryDao.insertOrReplace(searchQuery)
}
fun addToViewedNotificationsQueue(viewedNotification: ViewedNotification) {
viewedNotificationsQueueDao.insertOrReplace(viewedNotification)
}
fun getViewedNotificationsQueue() = viewedNotificationsQueueDao.getAll()
fun removeViewedNotification(viewedNotification: ViewedNotification) {
viewedNotificationsQueueDao.remove(
DbStructureViewedNotificationsQueue.Column.NOTIFICATION_ID,
viewedNotification.notificationId.toString())
}
fun syncExp(courseId: Long, apiExp: Long): Long {
val localExp = getExpForCourse(courseId)
val diff = apiExp - localExp
if (diff > 0) {
val syncRecord = adaptiveExpDao.getExpItem(courseId, 0)?.exp ?: 0
adaptiveExpDao.insertOrReplace(LocalExpItem(syncRecord + diff, 0, courseId))
return getExpForCourse(courseId)
}
return localExp
}
fun getExpForCourse(courseId: Long) = adaptiveExpDao.getExpForCourse(courseId)
fun getStreakForCourse(courseId: Long) = adaptiveExpDao.getExpItem(courseId)?.exp ?: 0
fun addLocalExpItem(exp: Long, submissionId: Long, courseId: Long) {
adaptiveExpDao.insertOrReplace(LocalExpItem(exp, submissionId, courseId))
}
fun getExpForLast7Days(courseId: Long) = adaptiveExpDao.getExpForLast7Days(courseId)
fun getExpForWeeks(courseId: Long) = adaptiveExpDao.getExpForWeeks(courseId)
fun getSectionDateEvents(vararg sectionIds: Long): List<SectionDateEvent> =
DbParseHelper.parseLongArrayToString(sectionIds, AppConstants.COMMA)?.let {
sectionDateEventDao.getAllInRange(DbStructureSectionDateEvent.Columns.SECTION_ID, it)
} ?: emptyList()
fun removeSectionDateEvents(vararg sectionIds: Long) =
DbParseHelper.parseLongArrayToString(sectionIds, AppConstants.COMMA)?.let {
sectionDateEventDao.removeAllInRange(DbStructureSectionDateEvent.Columns.SECTION_ID, it)
}
fun addSectionDateEvents(events: List<SectionDateEvent>) {
sectionDateEventDao.insertOrReplaceAll(events)
}
}
|
apache-2.0
|
0dfe901b6b02b64e33e9c07165ac2ea1
| 39.108504 | 115 | 0.738739 | 4.578507 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2
|
core/src/main/kotlin/io/github/chrislo27/rhre3/VersionHistory.kt
|
2
|
391
|
package io.github.chrislo27.rhre3
import io.github.chrislo27.toolboks.version.Version
object VersionHistory {
val TIME_SIGNATURES_REFACTOR = Version(3, 6, 0)
val ANALYTICS = Version(3, 8, 0)
val RHRE_EXPANSION = Version(3, 12, 0)
val RE_ADD_STRETCHABLE_TEMPO = Version(3, 14, 0)
val PLAYALONG_UPDATE = Version(3, 17, 0)
val LAMPSHADE_UPDATE = Version(3, 19, 0)
}
|
gpl-3.0
|
eb78b880f63a71d853530ad8e9027ae8
| 25.133333 | 52 | 0.693095 | 3.031008 | false | false | false | false |
Homes-MinecraftServerMod/Homes
|
src/test/java/com/masahirosaito/spigot/homes/testutils/MockPlayerFactory.kt
|
1
|
4545
|
package com.masahirosaito.spigot.homes.testutils
import com.masahirosaito.spigot.homes.Homes
import com.masahirosaito.spigot.homes.testutils.SpyLogger
import com.masahirosaito.spigot.homes.testutils.MockWorldFactory.makeRandomLocation
import org.bukkit.Location
import org.bukkit.OfflinePlayer
import org.bukkit.Server
import org.bukkit.entity.Player
import org.bukkit.metadata.MetadataValue
import org.bukkit.plugin.java.JavaPlugin
import org.mockito.Matchers.any
import org.mockito.Matchers.anyString
import org.powermock.api.mockito.PowerMockito
import java.util.*
import java.util.logging.Logger
object MockPlayerFactory {
val players: MutableMap<UUID, Player> = mutableMapOf()
val locations: MutableMap<UUID, Location> = mutableMapOf()
val permissions: MutableMap<UUID, MutableList<String>> = mutableMapOf()
val offlinePlayers: MutableMap<UUID, OfflinePlayer> = mutableMapOf()
val ops: MutableMap<UUID, Boolean> = mutableMapOf()
val metadatas: MutableMap<UUID, MutableMap<String, MutableList<MetadataValue>>> = mutableMapOf()
val loggers: MutableMap<UUID, SpyLogger> = mutableMapOf()
fun makeNewMockPlayer(playerName: String, mockServer: Server): Player {
return PowerMockito.mock(Player::class.java).apply {
val uuid = UUID.randomUUID()
PowerMockito.`when`(server).thenReturn(mockServer)
PowerMockito.`when`(name).thenReturn(playerName)
PowerMockito.`when`(uniqueId).thenReturn(uuid)
PowerMockito.`when`(location).then { locations[uniqueId] }
/* TODO: hasPermission(permission: String): Boolean */
PowerMockito.`when`(hasPermission(anyString())).thenAnswer { invocation ->
if (ops[uniqueId]!!) true else permissions[uniqueId]!!.contains(invocation.getArgumentAt(0, String::class.java))
}
/* TODO: getMetadata(metadataKey: String): List<MetadataValue> */
PowerMockito.`when`(getMetadata(anyString())).thenAnswer { invocation ->
metadatas[uniqueId]?.get(invocation.getArgumentAt(0, String::class.java))
}
/* TODO: setMetadata(metadataKey: String, newMetadataValue: MetadataValue): Unit */
PowerMockito.`when`(setMetadata(anyString(), any(MetadataValue::class.java))).thenAnswer { invocation ->
metadatas[uniqueId]?.put(
invocation.getArgumentAt(0, String::class.java),
mutableListOf(invocation.getArgumentAt(1, MetadataValue::class.java)))
}
/* TODO: hasMetadata(metadataKey: String): Boolean */
PowerMockito.`when`(hasMetadata(anyString())).thenAnswer { invocation ->
metadatas[uniqueId]?.contains(invocation.getArgumentAt(0, String::class.java)) ?: false
}
/* TODO: removeMetadata(metadataKey: String, plugin: JavaPlugin): Unit */
PowerMockito.`when`(removeMetadata(anyString(), any(JavaPlugin::class.java))).thenAnswer { invocation ->
metadatas[uniqueId]?.remove(invocation.getArgumentAt(0, String::class.java))
}
/* TODO: teleport(location: Location): Boolean */
PowerMockito.`when`(teleport(any(Location::class.java))).thenAnswer { invocation ->
locations.put(uniqueId, invocation.getArgumentAt(0, Location::class.java)); true
}
/* TODO: sendMessage(msg: String): Unit */
PowerMockito.`when`(sendMessage(anyString())).thenAnswer { invocation ->
loggers[uniqueId]?.info(invocation.getArgumentAt(0, String::class.java))
}
register(this)
}
}
fun makeNewMockPlayer(playerName: String, homes: Homes): Player {
return makeNewMockPlayer(playerName, homes.server).apply {
homes.econ?.createPlayerAccount(this)
}
}
private fun register(player: Player) {
players.put(player.uniqueId, player)
locations.put(player.uniqueId, makeRandomLocation())
permissions.put(player.uniqueId, mutableListOf())
offlinePlayers.put(player.uniqueId, player)
ops.put(player.uniqueId, false)
metadatas.put(player.uniqueId, mutableMapOf())
loggers.put(player.uniqueId, SpyLogger(Logger.getLogger(player.name)))
}
fun clear() {
players.clear()
locations.clear()
permissions.clear()
offlinePlayers.clear()
ops.clear()
metadatas.clear()
loggers.clear()
}
}
|
apache-2.0
|
7df0790e96f2d6d50f623842d6065950
| 44 | 128 | 0.665127 | 4.685567 | false | false | false | false |
jiro-aqua/vertical-text-viewer
|
vtextview/src/main/java/jp/gr/aqua/vtextviewer/Flags.kt
|
1
|
725
|
package jp.gr.aqua.vtextviewer
import android.content.Context
import android.content.SharedPreferences
class Flags(context: Context){
companion object {
const val PREF_FILE="flags"
const val KEY_IS_NEWS_READ="is_news_read_202206"
const val KEY_USAGE_COUNTER="usage_counter"
}
private val sp : SharedPreferences = context.getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE)
var isNewsRead : Boolean
get() = sp.getBoolean(KEY_IS_NEWS_READ,false)
set(value) = sp.edit().putBoolean(KEY_IS_NEWS_READ,value).apply()
var usageCounter : Long
get() = sp.getLong(KEY_USAGE_COUNTER,0L)
set(value) = sp.edit().putLong(KEY_USAGE_COUNTER,value).apply()
}
|
apache-2.0
|
93fe8373f34f4f287fd0ee6a0ed059d3
| 28.04 | 101 | 0.686897 | 3.625 | false | false | false | false |
allotria/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserStartupActivity.kt
|
1
|
2674
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.advertiser.KnownExtensions
import com.intellij.ide.plugins.advertiser.KnownExtensionsService
import com.intellij.ide.plugins.advertiser.PluginData
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileTypes.FileTypeFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.updateSettings.impl.UpdateSettings
import com.intellij.ui.EditorNotifications
internal class PluginsAdvertiserStartupActivity : StartupActivity.Background {
override fun runActivity(project: Project) {
val application = ApplicationManager.getApplication()
if (application.isUnitTestMode ||
application.isHeadlessEnvironment ||
!UpdateSettings.getInstance().isPluginsCheckNeeded) {
return
}
val customPlugins = loadPluginsFromCustomRepositories()
if (project.isDisposed) {
return
}
val extensionsService = KnownExtensionsService.instance
val extensions = extensionsService.extensions
val unknownFeatures = UnknownFeaturesCollector.getInstance(project).unknownFeatures
if (extensions != null && unknownFeatures.isEmpty()) {
return
}
try {
if (extensions == null) {
val extensionsMap = getExtensionsFromMarketPlace(customPlugins)
extensionsService.extensions = KnownExtensions(extensionsMap)
if (project.isDisposed) {
return
}
EditorNotifications.getInstance(project).updateAllNotifications()
}
PluginAdvertiserService.instance.run(
project,
customPlugins,
unknownFeatures,
)
}
catch (e: Exception) {
LOG.info(e)
}
}
companion object {
private fun getExtensionsFromMarketPlace(customPlugins: List<IdeaPluginDescriptor>): Map<String, Set<PluginData>> {
val customPluginIds = customPlugins.map { it.pluginId.idString }.toSet()
@Suppress("DEPRECATION") val params = mapOf("featureType" to FileTypeFactory.FILE_TYPE_FACTORY_EP.name)
return MarketplaceRequests.Instance
.getFeatures(params)
.groupBy(
{ it.implementationName!! },
{ feature -> feature.toPluginData { customPluginIds.contains(it) } }
).mapValues { it.value.filterNotNull().toSet() }
}
}
}
|
apache-2.0
|
b51a4872541fab54774c6379092588ae
| 36.152778 | 140 | 0.739342 | 4.97026 | false | false | false | false |
JetBrains/teamcity-dnx-plugin
|
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/DotnetCommandSet.kt
|
1
|
2946
|
package jetbrains.buildServer.dotnet
import jetbrains.buildServer.agent.CommandLineArgument
import jetbrains.buildServer.agent.CommandLineArgumentType
import jetbrains.buildServer.agent.CommandResultEvent
import jetbrains.buildServer.agent.runner.ParameterType
import jetbrains.buildServer.agent.runner.ParametersService
import jetbrains.buildServer.rx.Observer
class DotnetCommandSet(
private val _parametersService: ParametersService,
commands: List<DotnetCommand>)
: CommandSet {
private val _knownCommands: Map<String, DotnetCommand> = commands.associateBy({ it.commandType.id }, { it })
override val commands: Sequence<DotnetCommand>
get() = _parametersService.tryGetParameter(ParameterType.Runner, DotnetConstants.PARAM_COMMAND)?.let {
_knownCommands[it]?.let { command ->
getTargetArguments(command).asSequence().map {
val targetArguments = TargetArguments(it.arguments.toList().asSequence())
CompositeCommand(command, targetArguments)
}
}
} ?: emptySequence()
private fun getTargetArguments(command: DotnetCommand) = sequence {
var hasTargets = false
for (targetArguments in command.targetArguments) {
yield(targetArguments)
hasTargets = true
}
if (!hasTargets) {
yield(TargetArguments(emptySequence()))
}
}
class CompositeCommand(
private val _command: DotnetCommand,
private val _targetArguments: TargetArguments)
: DotnetCommand {
override val commandType: DotnetCommandType
get() = _command.commandType
override val toolResolver: ToolResolver
get() = _command.toolResolver
override fun getArguments(context: DotnetBuildContext): Sequence<CommandLineArgument> =
sequence {
if (_command.toolResolver.isCommandRequired) {
// command
yieldAll(_command.commandType.id.split('-')
.filter { it.isNotEmpty() }
.map { CommandLineArgument(it, CommandLineArgumentType.Mandatory) })
}
// projects
yieldAll(_targetArguments.arguments)
// command specific arguments
yieldAll(_command.getArguments(context))
}
override val targetArguments: Sequence<TargetArguments>
get() = sequenceOf(_targetArguments)
override val environmentBuilders: Sequence<EnvironmentBuilder>
get() = _command.environmentBuilders
override val resultsAnalyzer: ResultsAnalyzer
get() = _command.resultsAnalyzer
override val resultsObserver: Observer<CommandResultEvent>
get() = _command.resultsObserver
}
}
|
apache-2.0
|
79670ce6992421869f0afcd5ba748844
| 37.272727 | 112 | 0.631025 | 5.654511 | false | false | false | false |
genonbeta/TrebleShot
|
app/src/main/java/org/monora/uprotocol/client/android/backend/Backend.kt
|
1
|
11818
|
/*
* Copyright (C) 2021 Veli Tasalı
*
* 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.backend
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiConfiguration
import android.util.Log
import androidx.collection.ArraySet
import androidx.core.content.ContextCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.Transformations
import androidx.lifecycle.liveData
import dagger.Lazy
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.activity.HomeActivity
import org.monora.uprotocol.client.android.app.Activity
import org.monora.uprotocol.client.android.config.AppConfig
import org.monora.uprotocol.client.android.database.model.Transfer
import org.monora.uprotocol.client.android.database.model.UClient
import org.monora.uprotocol.client.android.database.model.UTransferItem
import org.monora.uprotocol.client.android.service.BackgroundService
import org.monora.uprotocol.client.android.service.backgroundservice.Task
import org.monora.uprotocol.client.android.util.DynamicNotification
import org.monora.uprotocol.client.android.util.Permissions
import java.util.concurrent.CancellationException
import javax.inject.Inject
import javax.inject.Singleton
typealias TaskFilter = (Task) -> Boolean
typealias TaskRegistry<T> = (applicationScope: CoroutineScope, params: T, state: MutableLiveData<Task.State>) -> Job
typealias TaskSubscriber<T> = (Task) -> T?
// is this my new favorite font? I think it is!
@Singleton
class Backend @Inject constructor(
@ApplicationContext val context: Context,
services: Lazy<Services>,
) {
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private val bgIntent = Intent(context, BackgroundService::class.java)
private val bgStopIntent = Intent(context, BackgroundService::class.java).also {
it.action = BackgroundService.ACTION_STOP_BG_SERVICE
}
val bgNotification
get() = taskNotification?.takeIf { hasTasks() } ?: services.notifications.foregroundNotification
private var foregroundActivitiesCount = 0
private var foregroundActivity: Activity? = null
val services: Services by lazy {
services.get()
}
private val taskSet: MutableSet<Task> = ArraySet()
private val _tasks = MutableLiveData<List<Task>>(emptyList())
val tasks = liveData {
emitSource(_tasks)
}
private var taskNotification: DynamicNotification? = null
private var taskNotificationTime: Long = 0
private var tileEnabled = false
private var _tileState = MutableLiveData(false)
var tileState = liveData {
emitSource(_tileState)
}
fun cancelAllTasks() {
val cancellationCause = CancellationException("Application exited")
applicationScope.coroutineContext.cancelChildren(cancellationCause)
synchronized(taskSet) {
taskSet.forEach {
if (!it.job.isCancelled) it.job.cancel(cancellationCause)
}
}
}
fun cancelMatchingTasks(filter: TaskFilter): Boolean {
return synchronized(taskSet) {
var cancelledAny = false
taskSet.forEach {
if (filter(it)) {
it.job.cancel()
cancelledAny = true
}
}
cancelledAny
}
}
private fun ensureStarted() = services.start()
fun ensureStartedAfterWelcoming() {
takeBgServiceFgIfNeeded(true)
}
private fun ensureStopped() {
services.stop()
notifyTileState(false)
cancelAllTasks()
}
fun getHotspotConfig(): WifiConfiguration? {
return services.hotspotManager.configuration
}
fun hasTasks(): Boolean = taskSet.isNotEmpty()
fun hasTask(filter: TaskFilter): Boolean {
return synchronized(taskSet) {
taskSet.forEach {
if (filter(it)) return@synchronized true
}
false
}
}
@Synchronized
fun notifyActivityInForeground(activity: Activity, inForeground: Boolean) {
if (!inForeground && foregroundActivitiesCount == 0) return
val wasInForeground = foregroundActivitiesCount > 0
foregroundActivitiesCount += if (inForeground) 1 else -1
val isInForeground = foregroundActivitiesCount > 0
val newlySwitchedGrounds = isInForeground != wasInForeground
if (Permissions.checkRunningConditions(context)) {
takeBgServiceFgIfNeeded(newlySwitchedGrounds)
}
foregroundActivity = if (newlySwitchedGrounds) null else if (inForeground) activity else foregroundActivity
}
private fun notifyTileState(newState: Boolean) {
tileEnabled = newState
_tileState.value = newState
}
fun publishTaskNotifications(force: Boolean): Boolean {
val notified = System.nanoTime()
if (notified <= taskNotificationTime && !force) return false
if (!hasTasks()) {
takeBgServiceFgIfNeeded(newlySwitchedGrounds = false)
return false
}
taskNotificationTime = System.nanoTime() + AppConfig.DELAY_DEFAULT_NOTIFICATION * 1e6.toLong()
taskNotification = services.notifications.notifyTasksNotification(taskSet.toList(), taskNotification)
return true
}
fun <T : Any> register(name: String, params: T, registry: TaskRegistry<T>): Task {
val state = MutableLiveData<Task.State>(Task.State.Pending)
val job = registry(applicationScope, params, state)
val task = Task(name, params, job, state)
registerInternal(task, state, true)
return task
}
private fun registerInternal(task: Task, state: MutableLiveData<Task.State>, addition: Boolean) {
// For observers to work correctly and to set values instead of posting them, we launch a coroutine on main
// thread.
applicationScope.launch {
val result = synchronized(taskSet) {
if (addition) taskSet.add(task) else taskSet.remove(task)
}
if (result) {
Log.d(TAG, "registerInternal: ${if (addition) "Registered" else "Removed"} `${task.name}`")
if (addition) {
task.state.observeForever(object : Observer<Task.State> {
override fun onChanged(t: Task.State) {
val changesPosted: Boolean
when (t) {
is Task.State.Pending, is Task.State.Finished -> {
changesPosted = true
publishTaskNotifications(true)
}
is Task.State.Running, is Task.State.Progress -> {
changesPosted = publishTaskNotifications(false)
}
is Task.State.Error -> {
changesPosted = false
}
}
if (t is Task.State.Finished) {
task.state.removeObserver(this)
}
if (changesPosted) {
_tasks.value = taskSet.toList()
}
}
})
task.job.invokeOnCompletion {
registerInternal(task, state, false)
}
} else {
state.value = Task.State.Finished
}
}
}
}
fun <T> subscribeToTask(condition: TaskSubscriber<T>): LiveData<Task.Change<T>?> {
val dummyLiveData = liveData<Task.Change<T>?> {
emit(null)
}
var previous: Pair<Task, LiveData<Task.Change<T>?>>? = null
return Transformations.switchMap(tasks) { list ->
if (previous == null || Task.State.Finished == previous?.first?.state?.value) {
previous = null
for (task in list) {
val exported = condition(task)
if (exported != null) {
previous = task to Transformations.map(task.state) {
Task.Change(task, exported, it)
}
break
}
}
}
previous?.second ?: dummyLiveData
}
}
fun <T> subscribeToTasks(condition: TaskSubscriber<T>): LiveData<List<Task.Change<T>>> {
return Transformations.switchMap(tasks) { list ->
liveData<List<Task.Change<T>>> {
val filtered = mutableListOf<Task.Change<T>>()
for (task in list) {
val exported = condition(task)
if (exported != null) {
filtered.add(Task.Change(task, exported, task.state.value ?: Task.State.Pending))
}
}
emit(filtered)
}
}
}
fun takeBgServiceFgIfNeeded(
newlySwitchedGrounds: Boolean,
forceStop: Boolean = false,
) {
// Do not try to tweak this!!!
val hasTasks = hasTasks()
val hasServices = (services.hotspotManager.started || services.isServingAnything || tileEnabled)
val inForeground = foregroundActivitiesCount > 0
val newlyInForeground = newlySwitchedGrounds && inForeground
val newlyInBackground = newlySwitchedGrounds && !inForeground
val keepRunning = (hasServices || hasTasks) && !forceStop
if (newlyInForeground || (tileEnabled && !forceStop)) {
ensureStarted()
} else if (!inForeground && !keepRunning) {
ensureStopped()
}
if (newlyInBackground && keepRunning) {
ContextCompat.startForegroundService(context, bgIntent)
} else if (newlyInForeground || (!inForeground && !keepRunning)) {
ContextCompat.startForegroundService(context, bgStopIntent)
}
if (!forceStop && !hasTasks) {
if (hasServices && !inForeground) {
services.notifications.foregroundNotification.show()
} else {
services.notifications.foregroundNotification.cancel()
}
}
}
fun takeBgServiceFgThroughTogglingTile() {
notifyTileState(!tileEnabled)
takeBgServiceFgIfNeeded(newlySwitchedGrounds = false)
}
fun toggleHotspot() = services.toggleHotspot()
companion object {
private const val TAG = "Backend"
}
}
|
gpl-2.0
|
aa5c1fb886c002d789441ac67b9e135a
| 33.961538 | 116 | 0.616823 | 4.942284 | false | false | false | false |
zdary/intellij-community
|
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/ParameterNullityInference.kt
|
2
|
8799
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.dataFlow.inference
import com.intellij.lang.LighterAST
import com.intellij.lang.LighterASTNode
import com.intellij.psi.CommonClassNames
import com.intellij.psi.JavaTokenType
import com.intellij.psi.impl.source.JavaLightTreeUtil
import com.intellij.psi.impl.source.tree.ElementType
import com.intellij.psi.impl.source.tree.JavaElementType.*
import com.intellij.psi.impl.source.tree.LightTreeUtil
import com.intellij.psi.tree.TokenSet
import java.util.*
internal fun inferNotNullParameters(tree: LighterAST, parameterNames: List<String?>, statements: List<LighterASTNode>): BitSet {
val canBeNulls = parameterNames.filterNotNullTo(HashSet())
if (canBeNulls.isEmpty()) return BitSet()
val notNulls = HashSet<String>()
val queue = ArrayDeque(statements)
while (queue.isNotEmpty() && canBeNulls.isNotEmpty()) {
val element = queue.removeFirst()
val type = element.tokenType
when (type) {
CONDITIONAL_EXPRESSION, EXPRESSION_STATEMENT -> JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
RETURN_STATEMENT -> {
queue.clear()
JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
}
FOR_STATEMENT -> {
val condition = JavaLightTreeUtil.findExpressionChild(tree, element)
queue.clear()
if (condition != null) {
queue.addFirst(condition)
LightTreeUtil.firstChildOfType(tree, element, ElementType.JAVA_STATEMENT_BIT_SET)?.let(queue::addFirst)
}
else {
// no condition == endless loop: we may analyze body (at least until break/return/if/etc.)
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
}
WHILE_STATEMENT -> {
queue.clear()
val expression = JavaLightTreeUtil.findExpressionChild(tree, element)
if (expression?.tokenType == LITERAL_EXPRESSION &&
LightTreeUtil.firstChildOfType(tree, expression, JavaTokenType.TRUE_KEYWORD) != null) {
// while(true) == endless loop: we may analyze body (at least until break/return/if/etc.)
tree.getChildren(element).asReversed().forEach(queue::addFirst)
} else {
dereference(tree, expression, canBeNulls, notNulls, queue)
}
}
FOREACH_STATEMENT, SWITCH_STATEMENT, IF_STATEMENT, THROW_STATEMENT -> {
queue.clear()
val expression = JavaLightTreeUtil.findExpressionChild(tree, element)
dereference(tree, expression, canBeNulls, notNulls, queue)
}
BINARY_EXPRESSION, POLYADIC_EXPRESSION -> {
if (LightTreeUtil.firstChildOfType(tree, element, TokenSet.create(JavaTokenType.ANDAND, JavaTokenType.OROR)) != null) {
JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
}
else {
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
}
EMPTY_STATEMENT, ASSERT_STATEMENT, DO_WHILE_STATEMENT, DECLARATION_STATEMENT, BLOCK_STATEMENT -> {
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
SYNCHRONIZED_STATEMENT -> {
val sync = JavaLightTreeUtil.findExpressionChild(tree, element)
dereference(tree, sync, canBeNulls, notNulls, queue)
LightTreeUtil.firstChildOfType(tree, element, CODE_BLOCK)?.let(queue::addFirst)
}
FIELD, PARAMETER, LOCAL_VARIABLE -> {
canBeNulls.remove(JavaLightTreeUtil.getNameIdentifierText(tree, element))
JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
}
EXPRESSION_LIST -> {
val children = JavaLightTreeUtil.getExpressionChildren(tree, element)
// When parameter is passed to another method, that method may have "null -> fail" contract,
// so without knowing this we cannot continue inference for the parameter
children.forEach { ignore(tree, it, canBeNulls) }
children.asReversed().forEach(queue::addFirst)
}
ASSIGNMENT_EXPRESSION -> {
val lvalue = JavaLightTreeUtil.findExpressionChild(tree, element)
ignore(tree, lvalue, canBeNulls)
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
ARRAY_ACCESS_EXPRESSION -> JavaLightTreeUtil.getExpressionChildren(tree, element).forEach {
dereference(tree, it, canBeNulls, notNulls, queue)
}
METHOD_REF_EXPRESSION, REFERENCE_EXPRESSION -> {
val qualifier = JavaLightTreeUtil.findExpressionChild(tree, element)
dereference(tree, qualifier, canBeNulls, notNulls, queue)
}
CLASS, METHOD, LAMBDA_EXPRESSION -> {
// Ignore classes, methods and lambda expression bodies as it's not known whether they will be instantiated/executed.
// For anonymous classes argument list, field initializers and instance initialization sections are checked.
}
TRY_STATEMENT -> {
queue.clear()
val canCatchNpe = LightTreeUtil.getChildrenOfType(tree, element, CATCH_SECTION)
.asSequence()
.map { LightTreeUtil.firstChildOfType(tree, it, PARAMETER) }
.filterNotNull()
.map { parameter -> LightTreeUtil.firstChildOfType(tree, parameter, TYPE) }
.any { canCatchNpe(tree, it) }
if (!canCatchNpe) {
LightTreeUtil.getChildrenOfType(tree, element, RESOURCE_LIST).forEach(queue::addFirst)
LightTreeUtil.firstChildOfType(tree, element, CODE_BLOCK)?.let(queue::addFirst)
// stop analysis after first try as we are not sure how execution goes further:
// whether or not it visit catch blocks, etc.
}
}
else -> {
if (ElementType.JAVA_STATEMENT_BIT_SET.contains(type)) {
// Unknown/unprocessed statement: just stop processing the rest of the method
queue.clear()
}
else {
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
}
}
}
val notNullParameters = BitSet()
parameterNames.forEachIndexed { index, s -> if (notNulls.contains(s)) notNullParameters.set(index) }
return notNullParameters
}
private val NPE_CATCHERS = setOf("Throwable", "Exception", "RuntimeException", "NullPointerException",
CommonClassNames.JAVA_LANG_THROWABLE, CommonClassNames.JAVA_LANG_EXCEPTION,
CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION, CommonClassNames.JAVA_LANG_NULL_POINTER_EXCEPTION)
fun canCatchNpe(tree: LighterAST, type: LighterASTNode?): Boolean {
if (type == null) return false
val codeRef = LightTreeUtil.firstChildOfType(tree, type, JAVA_CODE_REFERENCE)
val name = JavaLightTreeUtil.getNameIdentifierText(tree, codeRef)
if (name == null) {
// Multicatch
return LightTreeUtil.getChildrenOfType(tree, type, TYPE).any { canCatchNpe(tree, it) }
}
return NPE_CATCHERS.contains(name)
}
private fun ignore(tree: LighterAST,
expression: LighterASTNode?,
canBeNulls: HashSet<String>) {
val stripped = JavaLightTreeUtil.skipParenthesesDown(tree, expression)
if (stripped != null &&
stripped.tokenType == REFERENCE_EXPRESSION && JavaLightTreeUtil.findExpressionChild(tree, stripped) == null) {
canBeNulls.remove(JavaLightTreeUtil.getNameIdentifierText(tree, stripped))
}
}
private fun dereference(tree: LighterAST,
expression: LighterASTNode?,
canBeNulls: HashSet<String>,
notNulls: HashSet<String>,
queue: ArrayDeque<LighterASTNode>) {
val stripped = JavaLightTreeUtil.skipParenthesesDown(tree, expression)
if (stripped == null) return
if (stripped.tokenType == REFERENCE_EXPRESSION && JavaLightTreeUtil.findExpressionChild(tree, stripped) == null) {
JavaLightTreeUtil.getNameIdentifierText(tree, stripped)?.takeIf(canBeNulls::remove)?.let(notNulls::add)
}
else {
queue.addFirst(stripped)
}
}
/**
* Returns list of parameter names. A null in returned list means that either parameter name
* is absent in the source or it's a primitive type (thus nullity inference does not apply).
*/
internal fun getParameterNames(tree: LighterAST, method: LighterASTNode): List<String?> {
val parameterList = LightTreeUtil.firstChildOfType(tree, method, PARAMETER_LIST) ?: return emptyList()
val parameters = LightTreeUtil.getChildrenOfType(tree, parameterList, PARAMETER)
return parameters.map {
if (LightTreeUtil.firstChildOfType(tree, it, ElementType.PRIMITIVE_TYPE_BIT_SET) != null) null
else JavaLightTreeUtil.getNameIdentifierText(tree, it)
}
}
|
apache-2.0
|
61ef53021cc8af6ef87005a0b7c15deb
| 47.346154 | 140 | 0.692465 | 4.810826 | false | false | false | false |
zdary/intellij-community
|
platform/lang-api/src/com/intellij/refactoring/suggested/Utils.kt
|
13
|
1216
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.suggested
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.SmartPsiElementPointer
val DocumentEvent.oldRange: TextRange
get() = TextRange(offset, offset + oldLength)
val DocumentEvent.newRange: TextRange
get() = TextRange(offset, offset + newLength)
val RangeMarker.range: TextRange?
get() {
if (!isValid) return null
val start = startOffset
val end = endOffset
return if (start in 0..end) {
TextRange(start, end)
}
else {
// Probably a race condition had happened and range marker is invalidated
null
}
}
val PsiElement.startOffset: Int
get() = textRange.startOffset
val PsiElement.endOffset: Int
get() = textRange.endOffset
fun <E : PsiElement> E.createSmartPointer(): SmartPsiElementPointer<E> =
SmartPointerManager.getInstance(project).createSmartPsiElementPointer(this)
|
apache-2.0
|
40f0be446bba4ef762c046a536d349c1
| 30.179487 | 140 | 0.759868 | 4.342857 | false | false | false | false |
leafclick/intellij-community
|
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/Icon.kt
|
1
|
1353
|
// 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.intellij.build.images.sync
import com.intellij.ide.plugins.newui.PluginLogo
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.intellij.build.images.imageSize
import org.jetbrains.intellij.build.images.isImage
import java.io.File
internal class Icon(private val file: File) {
val isValid by lazy {
if (dimension != null) {
val pixels = if (file.name.contains("@2x")) 64 else 32
dimension!!.height <= pixels && dimension!!.width <= pixels || isPluginLogo()
}
else false
}
private val dimension by lazy {
if (file.exists() && isImage(file.toPath())) {
try {
muteStdErr {
imageSize(file.toPath())
}
}
catch (e: Exception) {
log("WARNING: $file: ${e.message}")
null
}
}
else null
}
private val pluginIcon = PluginLogo.getIconFileName(true)
private val pluginIconDark = PluginLogo.getIconFileName(false)
private fun isPluginLogo() = dimension?.let {
it.height == PluginLogo.height() && it.width == PluginLogo.width()
} == true && with(file.canonicalPath.let(FileUtil::toSystemIndependentName)) {
endsWith(pluginIcon) || endsWith(pluginIconDark)
}
}
|
apache-2.0
|
f6d75759f37118014d73b21d81415e50
| 32.02439 | 140 | 0.678492 | 3.979412 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/EvaluateCompileTimeExpressionIntention.kt
|
2
|
3175
|
// 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.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class EvaluateCompileTimeExpressionIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("evaluate.compile.time.expression")
) {
companion object {
val constantNodeTypes = listOf(KtNodeTypes.FLOAT_CONSTANT, KtNodeTypes.CHARACTER_CONSTANT, KtNodeTypes.INTEGER_CONSTANT)
}
override fun isApplicableTo(element: KtBinaryExpression): Boolean {
if (element.getStrictParentOfType<KtBinaryExpression>() != null || !element.isConstantExpression()) return false
val constantValue = element.getConstantValue() ?: return false
setTextGetter { KotlinBundle.message("replace.with.0", constantValue) }
return true
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
val constantValue = element.getConstantValue() ?: return
element.replace(KtPsiFactory(element).createExpression(constantValue))
}
private fun KtExpression?.isConstantExpression(): Boolean {
return when (val expression = KtPsiUtil.deparenthesize(this)) {
is KtConstantExpression -> expression.elementType in constantNodeTypes
is KtPrefixExpression -> expression.baseExpression.isConstantExpression()
is KtBinaryExpression -> expression.left.isConstantExpression() && expression.right.isConstantExpression()
else -> false
}
}
private fun KtBinaryExpression.getConstantValue(): String? {
val context = analyze(BodyResolveMode.PARTIAL)
val type = getType(context) ?: return null
val constantValue = ConstantExpressionEvaluator.getConstant(this, context)?.toConstantValue(type) ?: return null
return when (val value = constantValue.value) {
is Char -> "'${StringUtil.escapeStringCharacters(value.toString())}'"
is Long -> "${value}L"
is Float -> when {
value.isNaN() -> "Float.NaN"
value.isInfinite() -> if (value > 0.0f) "Float.POSITIVE_INFINITY" else "Float.NEGATIVE_INFINITY"
else -> "${value}f"
}
is Double -> when {
value.isNaN() -> "Double.NaN"
value.isInfinite() -> if (value > 0.0) "Double.POSITIVE_INFINITY" else "Double.NEGATIVE_INFINITY"
else -> value.toString()
}
else -> value.toString()
}
}
}
|
apache-2.0
|
c1ac0136ba9e75c920f67541a5d3a225
| 47.846154 | 158 | 0.701732 | 5.104502 | false | false | false | false |
fabmax/kool
|
kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/vk/VkResource.kt
|
1
|
1162
|
package de.fabmax.kool.platform.vk
import org.lwjgl.system.MemoryStack
import org.lwjgl.vulkan.VK10
import java.nio.LongBuffer
abstract class VkResource {
var isDestroyed = false
private set
private val dependingResources = mutableListOf<VkResource>()
protected fun destroyDependingResources() {
for (i in dependingResources.indices.reversed()) {
dependingResources[i].destroy()
}
}
protected abstract fun freeResources()
fun addDependingResource(resource: VkResource) {
dependingResources += resource
}
fun removeDependingResource(resource: VkResource) {
dependingResources -= resource
}
fun destroy() {
if (!isDestroyed) {
destroyDependingResources()
freeResources()
isDestroyed = true
}
}
fun checkVk(code: Int, msg: (Int) -> String = { "Check failed" }) {
check(code == VK10.VK_SUCCESS) { msg(code) }
}
inline fun MemoryStack.checkCreatePointer(block: MemoryStack.(LongBuffer) -> Int): Long {
val lp = mallocLong(1)
checkVk(block(lp))
return lp[0]
}
}
|
apache-2.0
|
effd716bbd39a865abef702051f3a8f0
| 24.282609 | 93 | 0.634251 | 4.384906 | false | false | false | false |
ingokegel/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/create/GHPRMergeDirectionModelImpl.kt
|
1
|
1671
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.toolwindow.create
import com.intellij.collaboration.ui.SimpleEventListener
import com.intellij.util.EventDispatcher
import git4idea.GitBranch
import git4idea.GitRemoteBranch
import git4idea.ui.branch.MergeDirectionModel
import org.jetbrains.plugins.github.util.GHGitRepositoryMapping
import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager
import org.jetbrains.plugins.github.util.GithubUtil.Delegates.observableField
class GHPRMergeDirectionModelImpl(override val baseRepo: GHGitRepositoryMapping,
private val repositoriesManager: GHHostedRepositoriesManager) : MergeDirectionModel<GHGitRepositoryMapping> {
private val changeEventDispatcher = EventDispatcher.create(SimpleEventListener::class.java)
override var baseBranch: GitRemoteBranch? by observableField(null, changeEventDispatcher)
override var headRepo: GHGitRepositoryMapping? = null
private set
override var headBranch: GitBranch? = null
private set
override var headSetByUser: Boolean = false
override fun setHead(repo: GHGitRepositoryMapping?, branch: GitBranch?) {
headRepo = repo
headBranch = branch
changeEventDispatcher.multicaster.eventOccurred()
}
override fun addAndInvokeDirectionChangesListener(listener: () -> Unit) =
SimpleEventListener.addAndInvokeListener(changeEventDispatcher, listener)
override fun getKnownRepoMappings(): List<GHGitRepositoryMapping> = repositoriesManager.knownRepositories.toList()
}
|
apache-2.0
|
acf2e4917763e86e49846fc3354c975f
| 46.771429 | 143 | 0.812687 | 5.173375 | false | false | false | false |
blackwoodseven/kubernetes-node-slack-notifier
|
src/test/kotlin/com/blackwoodseven/kubernetes/node_watcher/MainSpec.kt
|
1
|
3268
|
package com.blackwoodseven.kubernetes.node_watcher
import inet.ipaddr.IPAddressString
import org.amshove.kluent.mock
import org.amshove.kluent.shouldEqual
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import java.time.Instant
import java.util.concurrent.ConcurrentHashMap
class MainSpec : Spek({
describe("the system should be sane") {
it("should calculate correctly") {
4 shouldEqual 2 + 2
}
}
describe("processNodeChange") {
it("should do nothing for MODIFIED") {
val nodeMap = ConcurrentHashMap(mapOf(
"node1" to IPAddressString("127.0.0.1").address,
"node2" to IPAddressString("127.0.0.2").address
))
val nodeChange = NodeChange(
NodeChangeType.MODIFIED,
mock(Node::class)
)
processNodeChange(nodeChange, nodeMap)
nodeMap shouldEqual mapOf(
"node1" to IPAddressString("127.0.0.1").address,
"node2" to IPAddressString("127.0.0.2").address
)
}
it("should return a new map with the new node for ADDED") {
val nodeMap = ConcurrentHashMap(mapOf(
"node1" to IPAddressString("127.0.0.1").address,
"node2" to IPAddressString("127.0.0.2").address
))
val newNode = Node(
NodeMetadata(
"node3",
Instant.now()
),
NodeStatus(
listOf(
NodeAddress(
"ExternalIP",
IPAddressString("127.0.0.3").address
)
)
)
)
val nodeChange = NodeChange(
NodeChangeType.ADDED,
newNode
)
processNodeChange(nodeChange, nodeMap)
nodeMap shouldEqual mapOf(
"node1" to IPAddressString("127.0.0.1").address,
"node2" to IPAddressString("127.0.0.2").address,
"node3" to IPAddressString("127.0.0.3").address
)
}
it("should return a new map without the removed node for DELETED") {
val nodeMap = ConcurrentHashMap(mapOf(
"node1" to IPAddressString("127.0.0.1").address,
"node2" to IPAddressString("127.0.0.2").address
))
val deletedNode = Node(
NodeMetadata(
"node2",
Instant.now()
),
mock(NodeStatus::class)
)
val nodeChange = NodeChange(
NodeChangeType.DELETED,
deletedNode
)
processNodeChange(nodeChange, nodeMap)
nodeMap shouldEqual mapOf(
"node1" to IPAddressString("127.0.0.1").address
)
}
}
})
|
apache-2.0
|
cad5664b14f607c51c3dd90508aab870
| 31.356436 | 80 | 0.472766 | 5.082426 | false | false | false | false |
mvysny/vaadin-on-kotlin
|
vok-framework/src/main/kotlin/eu/vaadinonkotlin/VaadinOnKotlin.kt
|
1
|
2818
|
package eu.vaadinonkotlin
import org.slf4j.LoggerFactory
import java.util.*
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicInteger
public object VaadinOnKotlin {
/**
* Initializes the Vaadin-On-Kotlin framework. Just call this from your context listener.
*/
public fun init() {
if (!::asyncExecutor.isInitialized || asyncExecutor.isShutdown) {
// TomEE also has by default 5 threads, so I guess this is okay :-D
asyncExecutor = Executors.newScheduledThreadPool(5, threadFactory)
}
val plugins: List<VOKPlugin> = pluginsLoader.toList()
plugins.forEach { it.init() }
isStarted = true
log.info("Vaadin On Kotlin initialized with plugins ${plugins.map { it.javaClass.simpleName }}")
}
/**
* Destroys the Vaadin-On-Kotlin framework. Just call this from your context listener.
*/
public fun destroy() {
if (isStarted) {
isStarted = false
Services.singletons.destroy()
pluginsLoader.forEach { it.destroy() }
asyncExecutor.shutdown()
asyncExecutor.awaitTermination(10, TimeUnit.SECONDS)
}
}
/**
* True if [init] has been called.
*/
@Volatile
public var isStarted: Boolean = false
private set
/**
* The executor used by [async] and [scheduleAtFixedRate]. You can submit your own tasks as you wish.
*
* You can set your own custom executor, but do so before [init] is called.
*/
@Volatile
public lateinit var asyncExecutor: ScheduledExecutorService
/**
* The thread factory used by the [async] method. By default, the factory
* creates non-daemon threads named "async-ID".
*
* Needs to be set before [init] is called.
*/
@Volatile
public var threadFactory: ThreadFactory = object : ThreadFactory {
private val id = AtomicInteger()
override fun newThread(r: Runnable): Thread {
val thread = Thread(r)
thread.name = "async-${id.incrementAndGet()}"
// not a good idea to create daemon threads: if the executor is not shut
// down properly and the JVM terminates, daemon threads are killed on the spot,
// without even calling finally blocks on them, as the JVM halts.
// See Section 7.4.2 of the "Java Concurrency In Practice" Book for more info.
return thread
}
}
private val log = LoggerFactory.getLogger(javaClass)
/**
* Discovers VOK plugins, so that they can be inited in [init] and closed on [destroy]. Uses a standard [ServiceLoader]
* machinery for discovery.
*/
private val pluginsLoader: ServiceLoader<VOKPlugin> = ServiceLoader.load(VOKPlugin::class.java)
}
|
mit
|
67719313f972785f1f977822269674c6
| 35.128205 | 123 | 0.64088 | 4.665563 | false | false | false | false |
alexstyl/Memento-Calendar
|
android_common/src/main/java/com/alexstyl/specialdates/date/IntentDateExtensions.kt
|
3
|
898
|
package com.alexstyl.specialdates.date
import android.content.Intent
val EXTRA_DAY_OF_MONTH = "extra:day_of_month"
val EXTRA_MONTH = "extra:month"
val EXTRA_YEAR = "extra:year"
fun Intent.putExtraDate(date: Date): Intent {
return putExtra(EXTRA_DAY_OF_MONTH, date.dayOfMonth)
.putExtra(EXTRA_MONTH, date.month)
.putExtra(EXTRA_YEAR, date.year)
}
fun Intent.getDateExtraOrThrow(): Date {
val dayOfMonth = getExtraOrThrow(this, EXTRA_DAY_OF_MONTH)
@MonthInt val month = getExtraOrThrow(this, EXTRA_MONTH)
val year = getExtraOrThrow(this, EXTRA_YEAR)
return Date.on(dayOfMonth, month, year)
}
private fun getExtraOrThrow(intent: Intent, extra: String): Int {
val intExtra = intent.getIntExtra(extra, -1)
if (intExtra == -1) {
throw IllegalArgumentException("Passing Intent did not include extra [$extra]")
}
return intExtra
}
|
mit
|
94fbf5b631b0482e5772f7bd3da6b3dd
| 28.933333 | 87 | 0.703786 | 3.620968 | false | false | false | false |
ThePreviousOne/Untitled
|
app/src/main/java/eu/kanade/tachiyomi/data/source/SourceManager.kt
|
1
|
4445
|
/*
* This file is part of TachiyomiEX. as of commit bf05952582807b469e721cf8ca3be36e8db17f28
*
* 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.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
package eu.kanade.tachiyomi.data.source
import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.content.Context
import android.os.Environment
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.source.online.OnlineSource
import eu.kanade.tachiyomi.data.source.online.YamlOnlineSource
import eu.kanade.tachiyomi.data.source.online.R18.*
import eu.kanade.tachiyomi.data.source.online.english.*
import eu.kanade.tachiyomi.data.source.online.english.dynasty.*
import eu.kanade.tachiyomi.data.source.online.german.*
import eu.kanade.tachiyomi.data.source.online.italian.*
import eu.kanade.tachiyomi.data.source.online.portuguese.*
import eu.kanade.tachiyomi.data.source.online.russian.*
import eu.kanade.tachiyomi.data.source.online.spanish.*
import eu.kanade.tachiyomi.util.hasPermission
import org.yaml.snakeyaml.Yaml
import timber.log.Timber
import java.io.File
open class SourceManager(private val context: Context) {
private val sourcesMap = createSources()
open fun get(sourceKey: String): Source? {
return sourcesMap[sourceKey]
}
fun getOnlineSources() = sourcesMap.values.filterIsInstance(OnlineSource::class.java)
private fun createOnlineSourceList(): List<Source> = listOf(
DH(Sources.DOUJINSHIHENTAI),
HB(Sources.HENTAIBEAST),
MH(Sources.MASSIVEHENTAI),
DHA(Sources.DOUJINSHIHENTAIA),
RIH(Sources.READINCESTHENTAI),
LHM(Sources.LOVEHENTAIMANGA),
Batoto(Sources.BATOTO),
Kissmanga(Sources.KISSMANGA),
Mangafox(Sources.MANGAFOX),
Readmanga(Sources.READMANGA),
Mintmanga(Sources.MINTMANGA),
Mangachan(Sources.MANGACHAN),
Readmangatoday(Sources.READMANGATODAY),
Mangasee(Sources.MANGASEE),
WieManga(Sources.WIEMANGA),
Mangapanda(Sources.MANGAPANDA),
Mangareader(Sources.MANGAREADER),
Mangago(Sources.MANGAGO),
DynastySeries(Sources.DYNASTYSERIES),
DynastyIssues(Sources.DYNASTYISSUES),
DynastyAnthologies(Sources.DYNASTYANTHOLOGIES),
DynastyDoujins(Sources.DYNASTYDOUJINS),
MangahereEN(Sources.MANGAHEREEN),
MangahereES(Sources.MANGAHEREES),
NinemangaDE(Sources.NINEMANGADE),
NinemangaEN(Sources.NINEMANGAEN),
NinemangaES(Sources.NINEMANGAES),
NinemangaBR(Sources.NINEMANGABR),
NinemangaIT(Sources.NINEMANGAIT),
NinemangaRU(Sources.NINEMANGARU),
MangaedenEN(Sources.MANGAEDENEN),
MangaedenIT(Sources.MANGAEDENIT)
)
private fun createSources(): Map<String, Source> = hashMapOf<String, Source>().apply {
createOnlineSourceList().forEach { put(it.id, it) }
val parsersDir = File(Environment.getExternalStorageDirectory().absolutePath +
File.separator + context.getString(R.string.app_name), "parsers")
if (parsersDir.exists() && context.hasPermission(READ_EXTERNAL_STORAGE)) {
val yaml = Yaml()
for (file in parsersDir.listFiles().filter { it.extension == "yml" }) {
try {
val map = file.inputStream().use { yaml.loadAs(it, Map::class.java) }
YamlOnlineSource(map).let { put(it.id, it) }
} catch (e: Exception) {
Timber.e("Error loading source from file. Bad format?")
}
}
}
}
}
|
gpl-3.0
|
0cb7f8b138af32ab3c11c43fe24e348a
| 41.333333 | 90 | 0.68189 | 3.902546 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinArtifactsDownloader.kt
|
1
|
6555
|
// 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.compiler.configuration
import com.intellij.jarRepository.JarRepositoryManager
import com.intellij.jarRepository.RemoteRepositoriesConfiguration
import com.intellij.jarRepository.RemoteRepositoryDescription
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.ide.impl.toVirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.annotations.Nls
import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts.Companion.KOTLIN_DIST_ARTIFACT_ID
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts.Companion.KOTLIN_DIST_LOCATION_PREFIX
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts.Companion.KOTLIN_JPS_PLUGIN_CLASSPATH_ARTIFACT_ID
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts.Companion.KOTLIN_MAVEN_GROUP_ID
import org.jetbrains.kotlin.idea.artifacts.lazyUnpackJar
import org.jetbrains.kotlin.idea.base.plugin.KotlinBasePluginBundle
import java.awt.EventQueue
import java.io.File
object KotlinArtifactsDownloader {
fun getUnpackedKotlinDistPath(version: String): File =
if (IdeKotlinVersion.get(version) == KotlinPluginLayout.instance.standaloneCompilerVersion) KotlinPluginLayout.instance.kotlinc
else KOTLIN_DIST_LOCATION_PREFIX.resolve(version)
fun getUnpackedKotlinDistPath(project: Project) =
KotlinJpsPluginSettings.jpsVersion(project)?.let { getUnpackedKotlinDistPath(it) } ?: KotlinPluginLayout.instance.kotlinc
fun isKotlinDistInitialized(version: String): Boolean {
if (IdeKotlinVersion.get(version) == KotlinPluginLayout.instance.standaloneCompilerVersion) {
return true
}
val unpackedTimestamp = getUnpackedKotlinDistPath(version).lastModified()
val mavenJarTimestamp = KotlinMavenUtils.findArtifact(KOTLIN_MAVEN_GROUP_ID, KOTLIN_DIST_ARTIFACT_ID, version)
?.toFile()?.lastModified() ?: 0
return unpackedTimestamp != 0L && mavenJarTimestamp != 0L && unpackedTimestamp >= mavenJarTimestamp
}
fun getKotlinJpsPluginJarPath(version: String): File {
if (IdeKotlinVersion.get(version) == KotlinPluginLayout.instance.standaloneCompilerVersion) {
return KotlinPluginLayout.instance.jpsPluginJar
}
return KotlinMavenUtils.findArtifactOrFail(KOTLIN_MAVEN_GROUP_ID, KOTLIN_JPS_PLUGIN_CLASSPATH_ARTIFACT_ID, version).toFile()
}
fun lazyDownloadAndUnpackKotlincDist(
project: Project,
version: String,
indicator: ProgressIndicator,
onError: (String) -> Unit,
): File? = lazyDownloadMavenArtifact(
project,
KOTLIN_DIST_ARTIFACT_ID,
version,
indicator,
KotlinBasePluginBundle.message("progress.text.downloading.kotlinc.dist"),
onError
)?.let { lazyUnpackJar(it, getUnpackedKotlinDistPath(version)) }
@Synchronized // Avoid manipulations with the same files from different threads
fun lazyDownloadMavenArtifact(
project: Project,
artifactId: String,
version: String,
indicator: ProgressIndicator,
@Nls indicatorDownloadText: String,
onError: (String) -> Unit,
): File? {
if (IdeKotlinVersion.get(version) == KotlinPluginLayout.instance.standaloneCompilerVersion) {
if (artifactId == KOTLIN_JPS_PLUGIN_CLASSPATH_ARTIFACT_ID) {
return KotlinPluginLayout.instance.jpsPluginJar
}
if (artifactId == KOTLIN_DIST_ARTIFACT_ID) {
return KotlinPluginLayout.instance.kotlinc
}
}
val expectedMavenArtifactJarPath = KotlinMavenUtils.findArtifact(KOTLIN_MAVEN_GROUP_ID, artifactId, version)?.toFile()
expectedMavenArtifactJarPath?.takeIf { it.exists() }?.let {
return it
}
indicator.text = indicatorDownloadText
return downloadMavenArtifact(artifactId, version, project, indicator, onError)
}
private fun downloadMavenArtifact(
artifactId: String,
version: String,
project: Project,
indicator: ProgressIndicator,
onError: (String) -> Unit
): File? {
check(!EventQueue.isDispatchThread()) {
"Don't call downloadMavenArtifact on UI thread"
}
val prop = RepositoryLibraryProperties(
KOTLIN_MAVEN_GROUP_ID,
artifactId,
version,
/* includeTransitiveDependencies = */false,
emptyList()
)
val repos = RemoteRepositoriesConfiguration.getInstance(project).repositories +
listOf( // TODO remove once KTI-724 is fixed
RemoteRepositoryDescription(
"kotlin.ide.plugin.dependencies",
"Kotlin IDE Plugin Dependencies",
"https://cache-redirector.jetbrains.com/maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-ide-plugin-dependencies"
)
)
val downloadedCompiler = JarRepositoryManager.loadDependenciesSync(
project,
prop,
/* loadSources = */ false,
/* loadJavadoc = */ false,
/* copyTo = */ null,
repos,
indicator
)
if (downloadedCompiler.isEmpty()) {
with(prop) {
onError("Failed to download maven artifact ($groupId:$artifactId${getVersion()}). " +
"Searched the artifact in following repos:\n" +
repos.joinToString("\n") { it.url })
}
return null
}
return downloadedCompiler.singleOrNull().let { it ?: error("Expected to download only single artifact") }.file
.toVirtualFileUrl(VirtualFileUrlManager.getInstance(project)).presentableUrl.let { File(it) }
.also {
val expectedMavenArtifactJarPath = KotlinMavenUtils.findArtifact(KOTLIN_MAVEN_GROUP_ID, artifactId, version)?.toFile()
check(it == expectedMavenArtifactJarPath) {
"Expected maven artifact path ($expectedMavenArtifactJarPath) doesn't match actual artifact path ($it)"
}
}
}
}
|
apache-2.0
|
d68d0c2cf970569f99e9b2072f2762ca
| 45.489362 | 137 | 0.678871 | 5.141176 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/configuration/projectUtils.kt
|
1
|
2634
|
// 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.configuration
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.search.FileTypeIndex
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.psi.UserDataProperty
fun hasKotlinFilesOnlyInTests(module: Module): Boolean {
return !hasKotlinFilesInSources(module) && FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, module.getModuleScope(true))
}
fun hasKotlinFilesInSources(module: Module): Boolean {
return FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, module.getModuleScope(false))
}
var Module.externalCompilerVersion: String? by UserDataProperty(Key.create("EXTERNAL_COMPILER_VERSION"))
fun findLatestExternalKotlinCompilerVersion(project: Project): IdeKotlinVersion? {
return findExternalKotlinCompilerVersions(project).maxOrNull()
}
fun findExternalKotlinCompilerVersions(project: Project): Set<IdeKotlinVersion> {
val result = LinkedHashSet<IdeKotlinVersion>()
var hasJpsModules = false
runReadAction {
for (module in ModuleManager.getInstance(project).modules) {
if (module.getBuildSystemType() == BuildSystemType.JPS) {
if (!hasJpsModules) hasJpsModules = true
} else {
val externalVersion = module.externalCompilerVersion?.let(IdeKotlinVersion::opt)
if (externalVersion != null) {
result.add(externalVersion)
}
}
}
}
if (hasJpsModules) {
val projectGlobalVersion = KotlinJpsPluginSettings.jpsVersion(project)?.let(IdeKotlinVersion::opt)
if (projectGlobalVersion != null) {
result.add(projectGlobalVersion)
}
}
return result
}
fun <T> Project.syncNonBlockingReadAction(smartMode: Boolean = false, task: () -> T): T =
ReadAction.nonBlocking<T> {
task()
}
.expireWith(KotlinPluginDisposable.getInstance(this))
.let {
if (smartMode) it.inSmartMode(this) else it
}
.executeSynchronously()
|
apache-2.0
|
98ecc46598816abbd95ff51152fe9c84
| 38.313433 | 133 | 0.736522 | 4.711986 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.