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
Bambooin/trime
app/src/main/java/com/osfans/trime/settings/fragments/ToolkitFragment.kt
1
1137
package com.osfans.trime.settings.fragments import android.os.Bundle import android.view.Menu import androidx.core.view.forEach import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import com.osfans.trime.R import com.osfans.trime.util.ShortcutUtils @Suppress("unused") class ToolkitFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { val context = preferenceManager.context val screen = preferenceManager.createPreferenceScreen(context) screen.addPreference( Preference(context).apply { setTitle(R.string.real_time_logs) isIconSpaceReserved = false setOnPreferenceClickListener { ShortcutUtils.launchLogActivity(context) true } } ) preferenceScreen = screen setHasOptionsMenu(true) } override fun onPrepareOptionsMenu(menu: Menu) { menu.forEach { item -> item.isVisible = false } super.onPrepareOptionsMenu(menu) } }
gpl-3.0
2108e70f290396d621b18747b0f5cac2
31.485714
85
0.675462
5.263889
false
false
false
false
seventhroot/elysium
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/profile/RPKDiscordProfileProviderImpl.kt
1
2194
/* * Copyright 2020 Ren Binden * * 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.rpkit.players.bukkit.profile import com.rpkit.players.bukkit.RPKPlayersBukkit import com.rpkit.players.bukkit.database.table.RPKDiscordProfileTable import net.dv8tion.jda.api.entities.User class RPKDiscordProfileProviderImpl(private val plugin: RPKPlayersBukkit): RPKDiscordProfileProvider { override fun getDiscordProfile(id: Int): RPKDiscordProfile? { return plugin.core.database.getTable(RPKDiscordProfileTable::class).get(id) } override fun getDiscordProfile(user: User): RPKDiscordProfile { val discordProfileTable = plugin.core.database.getTable(RPKDiscordProfileTable::class) var discordProfile = discordProfileTable.get(user) if (discordProfile == null) { discordProfile = RPKDiscordProfileImpl(discordId = user.idLong, profile = RPKThinProfileImpl(user.name)) discordProfileTable.insert(discordProfile) } return discordProfile } override fun getDiscordProfiles(profile: RPKProfile): List<RPKDiscordProfile> { return plugin.core.database.getTable(RPKDiscordProfileTable::class).get(profile) } override fun addDiscordProfile(profile: RPKDiscordProfile) { plugin.core.database.getTable(RPKDiscordProfileTable::class).insert(profile) } override fun updateDiscordProfile(profile: RPKDiscordProfile) { plugin.core.database.getTable(RPKDiscordProfileTable::class).update(profile) } override fun removeDiscordProfile(profile: RPKDiscordProfile) { plugin.core.database.getTable(RPKDiscordProfileTable::class).delete(profile) } }
apache-2.0
afd53d73359b64953d6bded1731bd646
40.415094
116
0.752051
4.542443
false
false
false
false
mpranj/libelektra
src/bindings/jna/libelektra-kotlin/src/main/kotlin/org/libelektra/dsl/KeyDSL.kt
2
1616
package org.libelektra.dsl import org.libelektra.Key /** * KeyDSL provides a DSL API for building Keys * It provides a way to instantiate complex keys in a readable way. * Should not be used directly, but implicitly by calling [keyOf] * * @param name the name of the key, e.g. user:/test */ class KeyDSL(private val name: String) { var value: Any? = null private val metaKeys: MutableList<Key> = mutableListOf() fun build(): Key { return Key.create(name, value).apply { metaKeys.forEach { setMeta(it.name, it.string) } } } fun metaKey(name: String, value: Any? = null) { require(name.startsWith("meta:/")) { "Meta keys must have name prefix 'meta:/'" } metaKeys.add(Key.create(name, value)) } } /** * Builder function for keys * * @param name the name of the key, e.g. user:/test * @param initializer a block to set value and meta keys for the created key */ fun keyOf(name: String, initializer: KeyDSL.() -> Unit = {}): Key { return KeyDSL(name).apply(initializer).build() } /** * Constructs a new key * * @param name key name starting with / and an optional namespace, e.g. user:/foo * @param value optional value of a primitive type * @param metaKeys optional meta keys added to this key, meta keys must have a name starting with meta:/ * @return the new key with given properties */ fun <T> keyOf(name: String, value: T? = null, vararg metaKeys: Key): Key { return Key.create(name, value).apply { metaKeys.forEach { setMeta(it.name, it.string) } } }
bsd-3-clause
fbb1656eeb532a5015fbb7c629973b49
27.857143
104
0.641708
3.607143
false
false
false
false
soeminnminn/EngMyanDictionary
app/src/main/java/com/s16/engmyan/utils/DefinitionBuilder.kt
1
3285
package com.s16.engmyan.utils import android.net.Uri import android.text.SpannableString import android.text.Spanned import androidx.core.text.HtmlCompat import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import android.text.TextUtils import android.text.style.URLSpan import android.view.View import com.s16.utils.RabbitConverter import java.util.regex.Pattern class DefinitionBuilder { interface OnWordLinkClickListener { fun onWordLinkClick(word: String) } private var definition: String? = null private var keywords: String? = null private var linkClickListener: OnWordLinkClickListener? = null private var clickableWordLink: Boolean = false fun setDefinition(definition: String) : DefinitionBuilder { this.definition = definition return this } fun setKeywords(keywords: String?) : DefinitionBuilder { this.keywords = keywords return this } fun setClickableWordLink(clickable: Boolean): DefinitionBuilder { this.clickableWordLink = clickable return this } fun setOnWordLinkClickListener(listener: OnWordLinkClickListener) { linkClickListener = listener } suspend fun convertToZawgyi(): String = withContext(Dispatchers.IO) { val converted = definition?.let { text -> RabbitConverter.uni2zg(text.trim()) } definition = converted converted ?: "" } suspend fun build(): Spanned? = withContext(Dispatchers.IO) { definition?.let { text -> val html = HtmlCompat.fromHtml(text.trim(), HtmlCompat.FROM_HTML_MODE_COMPACT) if (clickableWordLink && keywords != null && keywords!!.isNotEmpty()) { val keywordsMatcher = "[^,]+".toPattern().matcher(keywords) val spannableString = SpannableString(html) val chars = CharArray(html.length) TextUtils.getChars(html, 0, html.length, chars, 0) val plainText = String(chars) while (keywordsMatcher.find()) { val value = "${keywordsMatcher.group()}" val regex = "([^A-Za-z\\/\\?=])($value)([^A-Za-z\\/\\?=])" .toPattern(Pattern.CASE_INSENSITIVE) val textMatcher = regex.matcher(plainText) while (textMatcher.find()) { spannableString.setSpan( LinkSpan("file:///android_asset/definition?w=$value"), textMatcher.start(2), textMatcher.end(2), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } } spannableString } else { html } } } inner class LinkSpan(url: String) : URLSpan(url) { override fun onClick(widget: View) { val uri = Uri.parse(url) val word = uri.getQueryParameter("w") if (linkClickListener != null) { linkClickListener!!.onWordLinkClick(word ?: "") } } } }
gpl-2.0
ce3c19ea7bc42aed807596836a13939b
30.902913
94
0.566819
5.140845
false
false
false
false
gradle/gradle
build-logic/binary-compatibility/src/test/kotlin/gradlebuild/binarycompatibility/SinceAndIncubatingRulesKotlinTest.kt
3
12900
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gradlebuild.binarycompatibility import org.junit.Test class SinceAndIncubatingRulesKotlinTest : AbstractBinaryCompatibilityTest() { private val publicKotlinMembers = """ fun foo() {} val bar: String = "bar" val bool: Boolean = true val isBool: Boolean = true var bazar = "bazar" var bazool: Boolean = true var isFool: Boolean = true fun String.fooExt() {} fun Int.fooExt() {} val String.barExt: String get() = "bar" var Int.bazarExt: String get() = "bar" set(value) = Unit operator fun String.invoke(p: String, block: String.() -> Unit) = Unit """ private val annotatedKotlinMembers = """ /** @since 2.0 */ @Incubating fun foo() {} /** @since 2.0 */ @get:Incubating val bar: String = "bar" /** @since 2.0 */ @get:Incubating val bool: Boolean = true /** @since 2.0 */ @get:Incubating val isBool: Boolean = true /** @since 2.0 */ @get:Incubating @set:Incubating var bazar = "bazar" /** @since 2.0 */ @get:Incubating @set:Incubating var bazool: Boolean = true /** @since 2.0 */ @get:Incubating @set:Incubating var isFool: Boolean = true /** @since 2.0 */ @Incubating fun String.fooExt() {} /** @since 2.0 */ @Incubating fun Int.fooExt() {} /** @since 2.0 */ @get:Incubating val String.barExt: String get() = "bar" /** @since 2.0 */ @get:Incubating @set:Incubating var Int.bazarExt: String get() = "bar" set(value) = Unit /** @since 2.0 */ @Incubating operator fun String.invoke(p: String, block: String.() -> Unit) = Unit """ @Test fun `new top-level kotlin members`() { checkNotBinaryCompatibleKotlin( v2 = """ $publicKotlinMembers const val cathedral = "cathedral" """ ) { assertHasNoInformation() assertHasNoWarning() assertHasErrors( // Kotlin file-facade classes are ignored by the @since rule listOf("Class com.example.SourceKt: Is not annotated with @Incubating."), added("Field", "cathedral"), added("Method", "SourceKt.foo()"), added("Method", "SourceKt.fooExt(java.lang.String)"), added("Method", "SourceKt.fooExt(int)"), added("Method", "SourceKt.getBar()"), added("Method", "SourceKt.getBarExt(java.lang.String)"), added("Method", "SourceKt.getBazar()"), added("Method", "SourceKt.getBazarExt(int)"), added("Method", "SourceKt.getBazool()"), added("Method", "SourceKt.getBool()"), added("Method", "SourceKt.invoke(java.lang.String,java.lang.String,kotlin.jvm.functions.Function1)"), added("Method", "SourceKt.isBool()"), added("Method", "SourceKt.isFool()"), added("Method", "SourceKt.setBazar(java.lang.String)"), added("Method", "SourceKt.setBazarExt(int,java.lang.String)"), added("Method", "SourceKt.setBazool(boolean)"), added("Method", "SourceKt.setFool(boolean)") ) } // with existing non-incubating file-facade class, new members must be annotated with @Incubating and @since checkBinaryCompatibleKotlin( v1 = """ val existing = "file-facade-class" """, v2 = """ val existing = "file-facade-class" $annotatedKotlinMembers /** @since 2.0 */ @field:Incubating const val cathedral = "cathedral" """ ) { assertHasNoWarning() assertHasInformation( newApi("Field", "cathedral"), newApi("Method", "SourceKt.foo()"), newApi("Method", "SourceKt.fooExt(java.lang.String)"), newApi("Method", "SourceKt.fooExt(int)"), newApi("Method", "SourceKt.getBar()"), newApi("Method", "SourceKt.getBarExt(java.lang.String)"), newApi("Method", "SourceKt.getBazar()"), newApi("Method", "SourceKt.getBazarExt(int)"), newApi("Method", "SourceKt.getBazool()"), newApi("Method", "SourceKt.getBool()"), newApi("Method", "SourceKt.invoke(java.lang.String,java.lang.String,kotlin.jvm.functions.Function1)"), newApi("Method", "SourceKt.isBool()"), newApi("Method", "SourceKt.isFool()"), newApi("Method", "SourceKt.setBazar(java.lang.String)"), newApi("Method", "SourceKt.setBazarExt(int,java.lang.String)"), newApi("Method", "SourceKt.setBazool(boolean)"), newApi("Method", "SourceKt.setFool(boolean)") ) } // new file-facade class can be annotated with @Incubating, members must be annotated with @since checkBinaryCompatible( v2 = { withFile( "kotlin/com/example/Source.kt", """ @file:Incubating package com.example import org.gradle.api.Incubating ${annotatedKotlinMembers.lineSequence().filter { !it.contains("Incubating") }.joinToString("\n")} /** @since 2.0 */ const val cathedral = "cathedral" """ ) } ) { assertHasNoWarning() assertHasInformation( newApi("Class", "SourceKt"), newApi("Field", "cathedral"), newApi("Method", "SourceKt.foo()"), newApi("Method", "SourceKt.fooExt(java.lang.String)"), newApi("Method", "SourceKt.fooExt(int)"), newApi("Method", "SourceKt.getBar()"), newApi("Method", "SourceKt.getBarExt(java.lang.String)"), newApi("Method", "SourceKt.getBazar()"), newApi("Method", "SourceKt.getBazarExt(int)"), newApi("Method", "SourceKt.getBazool()"), newApi("Method", "SourceKt.getBool()"), newApi("Method", "SourceKt.invoke(java.lang.String,java.lang.String,kotlin.jvm.functions.Function1)"), newApi("Method", "SourceKt.isBool()"), newApi("Method", "SourceKt.isFool()"), newApi("Method", "SourceKt.setBazar(java.lang.String)"), newApi("Method", "SourceKt.setBazarExt(int,java.lang.String)"), newApi("Method", "SourceKt.setBazool(boolean)"), newApi("Method", "SourceKt.setFool(boolean)") ) } } @Test fun `new top-level kotlin types`() { // Singleton INSTANCE fields of `object`s are public checkNotBinaryCompatibleKotlin( v2 = """ interface Foo class Bar enum class Bazar object Cathedral """ ) { assertHasNoInformation() assertHasNoWarning() assertHasErrors( added("Class", "Bar"), added("Constructor", "Bar()"), added("Class", "Bazar"), added("Method", "Bazar.valueOf(java.lang.String)"), added("Method", "Bazar.values()"), added("Class", "Cathedral"), added("Field", "INSTANCE"), added("Class", "Foo") ) } checkBinaryCompatibleKotlin( v2 = """ /** @since 2.0 */ @Incubating interface Foo /** @since 2.0 */ @Incubating class Bar /** @since 2.0 */ @Incubating enum class Bazar /** @since 2.0 */ @Incubating object Cathedral """ ) { assertHasNoWarning() assertHasInformation( newApi("Class", "Bar"), newApi("Class", "Bazar"), newApi("Method", "Bazar.valueOf(java.lang.String)"), newApi("Method", "Bazar.values()"), newApi("Class", "Cathedral"), newApi("Field", "INSTANCE"), newApi("Class", "Foo") ) } } @Test fun `new kotlin types members`() { val baseline = """ /** @since 1.0 */ interface Foo /** @since 1.0 */ class Bar() """ checkNotBinaryCompatibleKotlin( v1 = baseline, v2 = """ /** @since 1.0 */ interface Foo : AutoCloseable { fun foo() override fun close() } /** @since 1.0 */ class Bar() { constructor(bar: String) : this() $publicKotlinMembers } """ ) { assertHasNoInformation() assertHasNoWarning() assertHasErrors( added("Method", "Bar.foo()"), added("Method", "Bar.fooExt(java.lang.String)"), added("Method", "Bar.fooExt(int)"), added("Method", "Bar.getBar()"), added("Method", "Bar.getBarExt(java.lang.String)"), added("Method", "Bar.getBazar()"), added("Method", "Bar.getBazarExt(int)"), added("Method", "Bar.getBazool()"), added("Method", "Bar.getBool()"), added("Method", "Bar.invoke(java.lang.String,java.lang.String,kotlin.jvm.functions.Function1)"), added("Method", "Bar.isBool()"), added("Method", "Bar.isFool()"), added("Method", "Bar.setBazar(java.lang.String)"), added("Method", "Bar.setBazarExt(int,java.lang.String)"), added("Method", "Bar.setBazool(boolean)"), added("Method", "Bar.setFool(boolean)"), added("Constructor", "Bar(java.lang.String)"), added("Method", "Foo.foo()") ) } checkBinaryCompatibleKotlin( v1 = baseline, v2 = """ /** @since 1.0 */ interface Foo { /** @since 2.0 */ @Incubating fun foo() } /** @since 1.0 */ class Bar() { /** @since 2.0 */ @Incubating constructor(bar: String) : this() $annotatedKotlinMembers } """ ) { assertHasNoWarning() assertHasInformation( newApi("Method", "Bar.foo()"), newApi("Method", "Bar.fooExt(java.lang.String)"), newApi("Method", "Bar.fooExt(int)"), newApi("Method", "Bar.getBar()"), newApi("Method", "Bar.getBarExt(java.lang.String)"), newApi("Method", "Bar.getBazar()"), newApi("Method", "Bar.getBazarExt(int)"), newApi("Method", "Bar.getBazool()"), newApi("Method", "Bar.getBool()"), newApi("Method", "Bar.invoke(java.lang.String,java.lang.String,kotlin.jvm.functions.Function1)"), newApi("Method", "Bar.isBool()"), newApi("Method", "Bar.isFool()"), newApi("Method", "Bar.setBazar(java.lang.String)"), newApi("Method", "Bar.setBazarExt(int,java.lang.String)"), newApi("Method", "Bar.setBazool(boolean)"), newApi("Method", "Bar.setFool(boolean)"), newApi("Method", "Foo.foo()") ) } } }
apache-2.0
234edbc9dddda4d7fe0d40e5d4dad2b2
30.386861
118
0.487519
4.621999
false
false
false
false
EvidentSolutions/dalesbred
dalesbred/src/test/kotlin/org/dalesbred/dialect/PostgreSQLLargeObjectTest.kt
1
2633
/* * Copyright (c) 2017 Evident Solutions Oy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.dalesbred.dialect import org.dalesbred.TestDatabaseProvider import org.dalesbred.TransactionalTestsRule import org.dalesbred.datatype.InputStreamWithSize import org.dalesbred.datatype.ReaderWithSize import org.junit.Assert.assertArrayEquals import org.junit.Rule import org.junit.Test import kotlin.test.assertEquals class PostgreSQLLargeObjectTest { private val db = TestDatabaseProvider.createPostgreSQLDatabase() @get:Rule val rule = TransactionalTestsRule(db) @Test fun streamBlobToDatabaseByteArray() { db.update("drop table if exists blob_test") db.update("create temporary table blob_test (id int, blob_data bytea)") val originalData = byteArrayOf(25, 35, 3) db.update("insert into blob_test values (1, ?)", InputStreamWithSize(originalData.inputStream(), originalData.size.toLong())) val data = db.findUnique(ByteArray::class.java, "select blob_data from blob_test where id=1") assertArrayEquals(originalData, data) } @Test fun streamReaderToDatabaseText() { db.update("drop table if exists text_test") db.update("create temporary table text_test (id int, text_data text)") val originalData = "foo" db.update("insert into text_test values (1, ?)", ReaderWithSize(originalData.reader(), originalData.length.toLong())) val data = db.findUnique(String::class.java, "select text_data from text_test where id=1") assertEquals(originalData, data) } }
mit
0833ea021c62111648dcaf46d7b45d7a
40.140625
133
0.74022
4.373754
false
true
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/service/CacheService.kt
1
5784
package cn.yiiguxing.plugin.translate.service import cn.yiiguxing.plugin.translate.STORAGE_NAME import cn.yiiguxing.plugin.translate.TRANSLATION_DIRECTORY import cn.yiiguxing.plugin.translate.trans.Lang import cn.yiiguxing.plugin.translate.trans.Translation import cn.yiiguxing.plugin.translate.util.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.Service import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.diagnostic.Logger import com.intellij.util.io.createDirectories import com.intellij.util.io.delete import com.intellij.util.io.readText import java.io.IOException import java.nio.file.DirectoryNotEmptyException import java.nio.file.Files import java.nio.file.attribute.BasicFileAttributes @Service @State(name = "Cache", storages = [(Storage(STORAGE_NAME))]) class CacheService : PersistentStateComponent<CacheService.State> { private val state = State() private val memoryCache = LruCache<MemoryCacheKey, Translation>(MAX_MEMORY_CACHE_SIZE) override fun getState(): State = state override fun loadState(state: State) { this.state.lastTrimTime = state.lastTrimTime } fun putMemoryCache(text: String, srcLang: Lang, targetLang: Lang, translatorId: String, translation: Translation) { memoryCache.put(MemoryCacheKey(text, srcLang, targetLang, translatorId), translation) if (Lang.AUTO == srcLang) { memoryCache.put(MemoryCacheKey(text, translation.srcLang, targetLang, translatorId), translation) } if (Lang.AUTO == targetLang) { memoryCache.put(MemoryCacheKey(text, srcLang, translation.targetLang, translatorId), translation) } if (Lang.AUTO == srcLang && Lang.AUTO == targetLang) { memoryCache.put( MemoryCacheKey(text, translation.srcLang, translation.targetLang, translatorId), translation ) } } fun getMemoryCache(text: String, srcLang: Lang, targetLang: Lang, translatorId: String): Translation? { return memoryCache[MemoryCacheKey(text, srcLang, targetLang, translatorId)] } fun getMemoryCacheSnapshot(): Map<MemoryCacheKey, Translation> { return memoryCache.snapshot } fun putDiskCache(key: String, translation: String) { try { CACHE_DIR.createDirectories() CACHE_DIR.resolve(key).writeSafe { it.write(translation.toByteArray()) } println("DEBUG - Puts disk cache: $key") trimDiskCachesIfNeed() } catch (e: Exception) { LOG.w(e) } } fun getDiskCache(key: String): String? { return try { CACHE_DIR.resolve(key).takeIf { Files.isRegularFile(it) }?.readText()?.apply { println("DEBUG - Disk cache hit: $key") } } catch (e: Exception) { LOG.w(e) null } } @Synchronized private fun trimDiskCachesIfNeed() { val now = System.currentTimeMillis() val duration = now - state.lastTrimTime if (duration < 0 || duration > TRIM_INTERVAL) { state.lastTrimTime = now executeOnPooledThread { try { trimDiskCaches() } catch (e: Exception) { LOG.w(e) } } } } private fun trimDiskCaches() { val names = CACHE_DIR .toFile() .list { _, name -> !name.endsWith(".tmp") } ?.takeIf { it.size > MAX_DISK_CACHE_SIZE } ?: return names.asSequence() .map { name -> CACHE_DIR.resolve(name) } .sortedBy { file -> try { Files.readAttributes(file, BasicFileAttributes::class.java).lastAccessTime().toMillis() } catch (e: NoSuchFileException) { -1L } } .take(names.size - MAX_DISK_CACHE_SIZE) .forEach { file -> try { Files.deleteIfExists(file) } catch (e: DirectoryNotEmptyException) { // ignore } } LOG.d("Disk cache has been trimmed.") } fun getDiskCacheSize(): Long { val names = CACHE_DIR .toFile() .list { _, name -> !name.endsWith(".tmp") } ?: return 0 return names.asSequence() .map { name -> try { Files.size(CACHE_DIR.resolve(name)) } catch (e: IOException) { 0L } } .sum() } fun evictAllDiskCaches() { try { CACHE_DIR.delete(true) } catch (e: Throwable) { // ignore } } /** * Data class for memory cache key */ data class MemoryCacheKey( val text: String, val srcLang: Lang, val targetLang: Lang, val translator: String = "unknown" ) data class State(@Volatile var lastTrimTime: Long = System.currentTimeMillis()) companion object { private const val MAX_MEMORY_CACHE_SIZE = 1024 private const val MAX_DISK_CACHE_SIZE = 1024 private const val TRIM_INTERVAL = 5 * 24 * 60 * 60 * 1000 // 5 days private val CACHE_DIR = TRANSLATION_DIRECTORY.resolve("caches") private val LOG = Logger.getInstance(CacheService::class.java) val instance: CacheService get() = ApplicationManager.getApplication().getService(CacheService::class.java) } }
mit
5da5926034d4e188883147f2b53106e4
32.057143
119
0.59509
4.586836
false
false
false
false
androidx/constraintlayout
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/verification/AnchorTest01.kt
2
12032
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.constraintlayout.verification import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layoutId import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.ConstraintSet import com.example.constraintlayout.R @Preview(group = "AnchorTest01") @Composable public fun AnchorTest01() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'anchortest01' }, button1: { height: { value: '20%' }, centerVertically: 'parent', start: ['title', 'start'] }, button2: { height: { value: '20%' }, centerVertically: 'parent', start: ['title', 'end'] }, button3: { height: { value: '20%' }, centerVertically: 'parent', start: ['title', 'start', 100] }, button4: { height: { value: '20%' }, visibility: 'gone', top: ['title', 'bottom'] }, button5: { height: { value: '20%' }, top: ['title', 'bottom'], start: ['button4', 'start', 200, 100] }, title: { height: '10%', top: ['parent', 'top'] } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button1"), onClick = {}, ) { Text(text = "btn1") } Button( modifier = Modifier.layoutId("button2"), onClick = {}, ) { Text(text = "btn2") } Button( modifier = Modifier.layoutId("button3"), onClick = {}, ) { Text(text = "btn3") } Button( modifier = Modifier.layoutId("button4"), onClick = {}, ) { Text(text = "btn4") } Button( modifier = Modifier.layoutId("button5"), onClick = {}, ) { Text(text = "btn5") } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "ABC dsa sdfs sdf ABC dsa sdfs sdf",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } } @Preview(group = "AnchorTest01") @Composable fun AnchorTest02() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'anchortest02' }, button1: { height: { value: '20%' }, centerVertically: 'parent', end: ['title', 'start'] }, button2: { height: { value: '20%' }, centerVertically: 'parent', end: ['title', 'end'] }, button3: { height: { value: '20%' }, centerVertically: 'parent', end: ['title', 'end', 100] }, button4: { height: { value: '20%' }, visibility: 'gone', end: ['parent', 'end'], top: ['title', 'bottom'] }, button5: { height: { value: '20%' }, top: ['title', 'bottom'], end: ['button4', 'end', 300, 100] }, title: { height: '10%', top: ['parent', 'top'], end: ['parent', 'end'] } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button1"), onClick = {}, ) { Text(text = "btn1") } Button( modifier = Modifier.layoutId("button2"), onClick = {}, ) { Text(text = "btn2") } Button( modifier = Modifier.layoutId("button3"), onClick = {}, ) { Text(text = "btn3") } Button( modifier = Modifier.layoutId("button4"), onClick = {}, ) { Text(text = "btn4") } Button( modifier = Modifier.layoutId("button5"), onClick = {}, ) { Text(text = "btn5") } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "ABC dsa sdfs sdf ABC dsa sdfs sdf",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } } @Preview(group = "AnchorTest01") @Composable fun AnchorTest03() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'anchortest03' }, button1: { height: { value: '5%' }, end: ['parent', 'end'], top: ['title', 'top'] }, button2: { height: { value: '5%' }, top: ['title', 'bottom'] }, button3: { height: { value: '5%' }, top: ['title', 'bottom', 100] }, button4: { height: { value: '5%' }, visibility: 'gone', end: ['title', 'end'], top: ['title', 'bottom', 100] }, button5: { height: { value: '5%' }, end: ['title', 'end'], top: ['button4', 'bottom', 300, 100] }, title: { height: '10%', top: ['parent', 'top'] } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button1"), onClick = {}, ) { Text(text = "btn1") } Button( modifier = Modifier.layoutId("button2"), onClick = {}, ) { Text(text = "btn2") } Button( modifier = Modifier.layoutId("button3"), onClick = {}, ) { Text(text = "btn3") } Button( modifier = Modifier.layoutId("button4"), onClick = {}, ) { Text(text = "btn4") } Button( modifier = Modifier.layoutId("button5"), onClick = {}, ) { Text(text = "btn5") } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "ABC dsa sdfs sdf ABC dsa sdfs sdf",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } } @Preview(group = "AnchorTest01") @Composable fun AnchorTest04() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'anchortest04' }, button1: { height: { value: '5%' }, end: ['parent', 'end'], bottom: ['title', 'top'] }, button2: { height: { value: '5%' }, start: ['title', 'end'], bottom: ['title', 'bottom'] }, button3: { height: { value: '5%' }, bottom: ['title', 'bottom', 100] }, button4: { height: { value: '5%' }, visibility: 'gone', end: ['title', 'end'], bottom: ['title', 'bottom', 100] }, button5: { height: { value: '5%' }, end: ['title', 'end'], bottom: ['button4', 'bottom', 300, 100] }, title: { height: '10%', centerVertically: 'parent', } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button1"), onClick = {}, ) { Text(text = "btn1") } Button( modifier = Modifier.layoutId("button2"), onClick = {}, ) { Text(text = "btn2") } Button( modifier = Modifier.layoutId("button3"), onClick = {}, ) { Text(text = "btn3") } Button( modifier = Modifier.layoutId("button4"), onClick = {}, ) { Text(text = "btn4") } Button( modifier = Modifier.layoutId("button5"), onClick = {}, ) { Text(text = "btn5") } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "ABC dsa sdfs sdf ABC dsa sdfs sdf",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } } @Preview(group = "AnchorTest01") @Composable fun AnchorTest05() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'anchortest05' }, button1: { height: { value: '10%' }, circular: ['title'] }, button2: { height: { value: '20%' }, circular: ['title',50] }, button3: { height: { value: '20%' }, circular: ['title', 90, 200] }, title: { height: '10%', centerVertically: 'parent', centerHorizontally: 'parent' } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button1"), onClick = {}, ) { Text(text = "btn1") } Button( modifier = Modifier.layoutId("button2"), onClick = {}, ) { Text(text = "btn2") } Button( modifier = Modifier.layoutId("button3"), onClick = {}, ) { Text(text = "btn3") } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "ABC dsa sdfs sdf ABC dsa sdfs sdf",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } }
apache-2.0
e34a5b582d020263cf2bfd4930973da1
29.08
98
0.421875
4.818582
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/profile/profiles/PlainProfileCreator.kt
1
6547
package net.perfectdreams.loritta.morenitta.profile.profiles import dev.kord.common.entity.Snowflake import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.dao.Profile import net.perfectdreams.loritta.morenitta.utils.* import net.perfectdreams.loritta.common.locale.BaseLocale import net.dv8tion.jda.api.entities.Guild import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.morenitta.profile.ProfileGuildInfoData import net.perfectdreams.loritta.morenitta.profile.ProfileUserInfoData import net.perfectdreams.loritta.morenitta.profile.ProfileUtils import net.perfectdreams.loritta.morenitta.utils.extensions.readImage import java.awt.* import java.awt.image.BufferedImage import java.io.File import java.io.FileInputStream open class PlainProfileCreator(loritta: LorittaBot, internalName: String, val folderName: String) : StaticProfileCreator(loritta, internalName) { class PlainWhiteProfileCreator(loritta: LorittaBot) : PlainProfileCreator(loritta, "plainWhite", "white") class PlainOrangeProfileCreator(loritta: LorittaBot) : PlainProfileCreator(loritta, "plainOrange", "orange") class PlainPurpleProfileCreator(loritta: LorittaBot) : PlainProfileCreator(loritta, "plainPurple", "purple") class PlainAquaProfileCreator(loritta: LorittaBot) : PlainProfileCreator(loritta, "plainAqua", "aqua") class PlainGreenProfileCreator(loritta: LorittaBot) : PlainProfileCreator(loritta, "plainGreen", "green") class PlainGreenHeartsProfileCreator(loritta: LorittaBot) : PlainProfileCreator(loritta, "plainGreenHearts", "green_hearts") override suspend fun create( sender: ProfileUserInfoData, user: ProfileUserInfoData, userProfile: Profile, guild: ProfileGuildInfoData?, badges: List<BufferedImage>, locale: BaseLocale, i18nContext: I18nContext, background: BufferedImage, aboutMe: String, allowedDiscordEmojis: List<Snowflake>? ): BufferedImage { val profileWrapper = readImage(File(LorittaBot.ASSETS, "profile/plain/profile_wrapper_$folderName.png")) val latoBold = loritta.graphicsFonts.latoBold val latoBlack = loritta.graphicsFonts.latoBlack val latoRegular22 = latoBold.deriveFont(22f) val latoBlack16 = latoBlack.deriveFont(16f) val latoRegular16 = latoBold.deriveFont(16f) val latoBlack12 = latoBlack.deriveFont(12f) val base = BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB) // Base val graphics = base.graphics.enableFontAntiAliasing() val avatar = LorittaUtils.downloadImage(loritta, user.avatarUrl)!!.getScaledInstance(152, 152, BufferedImage.SCALE_SMOOTH) graphics.drawImage(background.getScaledInstance(800, 600, BufferedImage.SCALE_SMOOTH), 0, 0, null) ProfileUtils.getMarriageInfo(loritta, userProfile)?.let { (marriage, marriedWith) -> val marrySection = readImage(File(LorittaBot.ASSETS, "profile/plain/marry.png")) graphics.drawImage(marrySection, 0, 0, null) graphics.color = Color.WHITE graphics.font = latoBlack12 ImageUtils.drawCenteredString(graphics, locale["profile.marriedWith"], Rectangle(635, 350, 165, 14), latoBlack12) graphics.font = latoRegular16 ImageUtils.drawCenteredString(graphics, marriedWith.name + "#" + marriedWith.discriminator, Rectangle(635, 350 + 16, 165, 18), latoRegular16) graphics.font = latoBlack12 ImageUtils.drawCenteredString(graphics, DateUtils.formatDateDiff(marriage.marriedSince, System.currentTimeMillis(), locale), Rectangle(635, 350 + 16 + 18, 165, 14), latoBlack12) } graphics.color = Color.BLACK graphics.drawImage(profileWrapper, 0, 0, null) drawAvatar(avatar, graphics) val oswaldRegular50 = Constants.OSWALD_REGULAR .deriveFont(50F) val oswaldRegular42 = Constants.OSWALD_REGULAR .deriveFont(42F) graphics.font = oswaldRegular50 graphics.drawText(loritta, user.name, 162, 461) // Nome do usuário graphics.font = oswaldRegular42 drawReputations(user, graphics) drawBadges(badges, graphics) graphics.font = latoBlack16 val biggestStrWidth = drawUserInfo(user, userProfile, guild, graphics) graphics.font = latoRegular22 drawAboutMeWrapSpaces(graphics, graphics.fontMetrics, aboutMe, 162, 484, 773 - biggestStrWidth - 4, 600, allowedDiscordEmojis) return base.makeRoundedCorners(15) } fun drawAvatar(avatar: Image, graphics: Graphics) { graphics.drawImage( avatar.toBufferedImage() .makeRoundedCorners(999), 3, 406, null ) } fun drawBadges(badges: List<BufferedImage>, graphics: Graphics) { var x = 2 for (badge in badges) { graphics.drawImage(badge.getScaledInstance(35, 35, BufferedImage.SCALE_SMOOTH), x, 564, null) x += 37 } } suspend fun drawReputations(user: ProfileUserInfoData, graphics: Graphics) { val font = graphics.font val reputations = ProfileUtils.getReputationCount(loritta, user) ImageUtils.drawCenteredString(graphics, "$reputations reps", Rectangle(634, 404, 166, 52), font) } suspend fun drawUserInfo(user: ProfileUserInfoData, userProfile: Profile, guild: ProfileGuildInfoData?, graphics: Graphics): Int { val userInfo = mutableListOf<String>() userInfo.add("Global") val globalPosition = ProfileUtils.getGlobalExperiencePosition(loritta, userProfile) if (globalPosition != null) userInfo.add("#$globalPosition / ${userProfile.xp} XP") else userInfo.add("${userProfile.xp} XP") if (guild != null) { val localProfile = ProfileUtils.getLocalProfile(loritta, guild, user) val localPosition = ProfileUtils.getLocalExperiencePosition(loritta, localProfile) val xpLocal = localProfile?.xp // Iremos remover os emojis do nome da guild, já que ele não calcula direito no stringWidth userInfo.add(guild.name.replace(Constants.EMOJI_PATTERN.toRegex(), "")) if (xpLocal != null) { if (localPosition != null) { userInfo.add("#$localPosition / $xpLocal XP") } else { userInfo.add("$xpLocal XP") } } else { userInfo.add("???") } } val globalEconomyPosition = ProfileUtils.getGlobalEconomyPosition(loritta, userProfile) userInfo.add("Sonhos") if (globalEconomyPosition != null) userInfo.add("#$globalEconomyPosition / ${userProfile.money}") else userInfo.add("${userProfile.money}") val biggestStrWidth = graphics.fontMetrics.stringWidth(userInfo.maxByOrNull { graphics.fontMetrics.stringWidth(it) }!!) var y = 475 for (line in userInfo) { graphics.drawText(loritta, line, 773 - biggestStrWidth - 2, y) y += 16 } return biggestStrWidth } }
agpl-3.0
20b9b2be5c5341dc573510ac5c37cc53
38.191617
180
0.760544
3.791425
false
false
false
false
Haldir65/AndroidRepo
otherprojects/_011_androidX/app/src/main/java/com/me/harris/droidx/cronet/CronetActivity.kt
1
1633
package com.me.harris.droidx.cronet import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.me.harris.droidx.R import kotlinx.android.synthetic.main.activity_cronet.* import org.chromium.net.CronetEngine import java.util.concurrent.Executors // https://developer.android.com/guide/topics/connectivity/cronet/ class CronetActivity :AppCompatActivity(){ // https://jsonplaceholder.typicode.com/posts // Network requests issued using the Cronet Library are asynchronous by default. // read() -> onReadCompleted() -> read() -> .... onSucceeded()/aka finished companion object { val JSON_URL = "https://jsonplaceholder.typicode.com/posts" val TAG = "CronetActivity" } val cronetEngine:CronetEngine by lazy { val myBuilder = CronetEngine.Builder(this) myBuilder.build() } val executor by lazy { Executors.newSingleThreadExecutor() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_cronet) btn_1.setOnClickListener { val callback = SimpleUrlRequestCallback( ) val builder = cronetEngine.newUrlRequestBuilder( JSON_URL, callback, executor ) // Measure the start time of the request so that // we can measure latency of the entire request cycle callback.start = System.nanoTime() // Start the request builder.build().start() Log.e(TAG,"STARTED") } } }
apache-2.0
9537388ae8f42c2e6f98d360e367f377
29.259259
84
0.661972
4.473973
false
false
false
false
christophpickl/kpotpourri
build4k/src/main/kotlin/com/github/christophpickl/kpotpourri/build/github.kt
1
3241
package com.github.christophpickl.kpotpourri.build import com.github.christophpickl.kpotpourri.common.http.httpRequest import java.io.File import java.net.URLEncoder class GitHub( private val build4k: Build4k, private val repoOwner: String, private val repoName: String, private val authToken: String ) { /** * @return the upload URL to use to upload assets to this release */ fun createRelease(tagName: String, releaseBody: String): String { val url = "https://api.github.com/repos/$repoOwner/$repoName/releases" Out.info("Creating release '$tagName' at: $url") return httpRequest( url = url, method = "POST" ) { addHeader("Authorization" to "token $authToken") addHeader("Content-Type" to "application/json") doWithOutput { out -> out.bufferedWriter().use { writer -> writer.write(""" { "tag_name": "$tagName", "name": "$tagName", "body": "${releaseBody.replace("\"", "\\\"").replace("\n", "\\n")}", "target_commitish": "master", "draft": false, "prerelease": false } """.trimIndent()) } } readResponseBody = true val response = execute() if (response.statusCode != 201) { build4k.fail("GitHub returned status code ${response.statusCode} while requesting URL: $url") } extractUploadUrl(response.responseBody!!) } } fun uploadArtifact(uploadUrl: String, contentType: String, file: File) { if (!file.exists()) { build4k.fail("Upload file does not exist: ${file.canonicalPath}") } val fullUrl = "$uploadUrl?name=${URLEncoder.encode(file.name, Charsets.UTF_8.name())}" Out.info("Uploading release artifact: ${file.canonicalPath}") Out.info("Upload URL: $fullUrl") httpRequest( url = fullUrl, method = "POST" ) { addHeader("Authorization" to "token $authToken") addHeader("Content-Type" to contentType) doWithOutput { out -> out.write(file.readBytes()) } val response = execute() if (response.statusCode != 201) { build4k.fail("GitHub returned status code ${response.statusCode} while requesting URL: $fullUrl") } } } // same as: $response | jq -r '.upload_url' | sed -e 's/{?name,label}//g'` private fun extractUploadUrl(response: String): String { val key = "\"upload_url\"" val index = response.indexOf(key) require(index > 0) { "JSON did not contain $key key!" } val responseAfterUploadUrl = response.substring(index + key.length) val start = responseAfterUploadUrl.indexOf("\"") + 1 val end = responseAfterUploadUrl.indexOf("\"", startIndex = start) return responseAfterUploadUrl.substring(start, end).replace("{?name,label}", "") } }
apache-2.0
b1300b104c42e8ff1c6d126a7b93aa01
38.048193
113
0.544276
4.683526
false
false
false
false
robinverduijn/gradle
buildSrc/subprojects/binary-compatibility/src/test/kotlin/org/gradle/binarycompatibility/NullabilityChangesTest.kt
1
9312
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.binarycompatibility import org.junit.Test class NullabilityChangesTest : AbstractBinaryCompatibilityTest() { @Test fun `from non-null returning to null returning is breaking (java)`() { checkNotBinaryCompatibleJava( v1 = """ public class Source { public String nonFinalField = "some"; public final String finalField = "some"; public String foo() { return "bar"; } } """, v2 = """ public class Source { @Nullable public String nonFinalField = null; @Nullable public final String finalField = null; @Nullable public String foo() { return "bar"; } } """ ) { assertHasErrors( "Field nonFinalField: Nullability breaking change.", "Field finalField: From non-nullable to nullable breaking change.", "Method com.example.Source.foo(): From non-null returning to null returning breaking change." ) assertHasNoWarning() assertHasNoInformation() } } @Test fun `from non-null returning to null returning is breaking (kotlin)`() { checkNotBinaryCompatibleKotlin( v1 = """ class Source { val someVal: String = "some" var someVar: String = "some" fun foo(): String = "bar" } """, v2 = """ class Source { val someVal: String? = null var someVar: String? = null fun foo(): String? = null } """ ) { assertHasErrors( "Method com.example.Source.foo(): From non-null returning to null returning breaking change.", "Method com.example.Source.getSomeVal(): From non-null returning to null returning breaking change.", "Method com.example.Source.getSomeVar(): From non-null returning to null returning breaking change." ) assertHasWarnings( "Method com.example.Source.setSomeVar(java.lang.String): Parameter 0 nullability changed from non-nullable to nullable" ) assertHasNoInformation() } } @Test fun `from null accepting to non-null accepting is breaking (java)`() { checkNotBinaryCompatibleJava( v1 = """ public class Source { public Source(@Nullable String some) {} @Nullable public String nonFinalField = null; public String foo(@Nullable String bar) { return "some"; } } """, v2 = """ public class Source { public Source(String some) {} public String nonFinalField = "some"; public String foo(String bar) { return bar; } } """ ) { assertHasErrors( "Field nonFinalField: Nullability breaking change.", "Method com.example.Source.foo(java.lang.String): Parameter 0 from null accepting to non-null accepting breaking change.", "Constructor com.example.Source(java.lang.String): Parameter 0 from null accepting to non-null accepting breaking change." ) assertHasNoWarning() assertHasNoInformation() } } @Test fun `from null accepting to non-null accepting is breaking (kotlin)`() { checkNotBinaryCompatibleKotlin( v1 = """ class Source(some: String?) { var someVar: String? = null fun foo(bar: String?) {} } """, v2 = """ class Source(some: String) { var someVar: String = "some" fun foo(bar: String) {} } """ ) { assertHasErrors( "Method com.example.Source.foo(java.lang.String): Parameter 0 from null accepting to non-null accepting breaking change.", "Method com.example.Source.setSomeVar(java.lang.String): Parameter 0 from null accepting to non-null accepting breaking change.", "Constructor com.example.Source(java.lang.String): Parameter 0 from null accepting to non-null accepting breaking change." ) assertHasWarnings( "Method com.example.Source.getSomeVar(): Return nullability changed from nullable to non-nullable" ) assertHasNoInformation() } } @Test fun `from null returning to non-null returning is not breaking (java)`() { checkBinaryCompatibleJava( v1 = """ public class Source { @Nullable public final String finalField = null; @Nullable public String foo(String bar) { return bar; } } """, v2 = """ public class Source { public final String finalField = null; public String foo(String bar) { return bar; } } """ ) { assertHasNoError() assertHasWarnings( "Field finalField: Nullability changed from nullable to non-nullable", "Method com.example.Source.foo(java.lang.String): Return nullability changed from nullable to non-nullable" ) assertHasNoInformation() } } @Test fun `from null returning to non-null returning is not breaking (kotlin)`() { checkBinaryCompatibleKotlin( v1 = """ class Source { val someVal: String? = null fun foo(): String? = null } """, v2 = """ class Source { val someVal: String = "some" fun foo(): String = "bar" } """ ) { assertHasNoError() assertHasWarnings( "Method com.example.Source.foo(): Return nullability changed from nullable to non-nullable", "Method com.example.Source.getSomeVal(): Return nullability changed from nullable to non-nullable" ) assertHasNoInformation() } } @Test fun `from non-null accepting to null accepting is not breaking (java)`() { checkBinaryCompatibleJava( v1 = """ public class Source { public Source(String some) {} public String foo(String bar) { return bar; } } """, v2 = """ public class Source { public Source(@Nullable String some) {} public String foo(@Nullable String bar) { return "some"; } } """ ) { assertHasNoError() assertHasWarnings( "Method com.example.Source.foo(java.lang.String): Parameter 0 nullability changed from non-nullable to nullable", "Constructor com.example.Source(java.lang.String): Parameter 0 nullability changed from non-nullable to nullable" ) assertHasNoInformation() } } @Test fun `from non-null accepting to null accepting is not breaking (kotlin)`() { checkBinaryCompatibleKotlin( v1 = """ class Source(some: String) { fun foo(bar: String) {} } operator fun Source.invoke(arg: String) {} """, v2 = """ class Source(some: String?) { fun foo(bar: String?) {} } operator fun Source.invoke(arg: String?) {} """ ) { assertHasNoError() assertHasWarnings( "Method com.example.Source.foo(java.lang.String): Parameter 0 nullability changed from non-nullable to nullable", "Constructor com.example.Source(java.lang.String): Parameter 0 nullability changed from non-nullable to nullable", "Method com.example.SourceKt.invoke(com.example.Source,java.lang.String): Parameter 1 nullability changed from non-nullable to nullable" ) assertHasNoInformation() } } }
apache-2.0
eb01644b83b39f0d933008bd4f493d2d
37.008163
152
0.526954
5.33945
false
false
false
false
Ph1b/MaterialAudiobookPlayer
data/src/main/kotlin/de/ph1b/audiobook/data/BookMetaData.kt
1
673
package de.ph1b.audiobook.data import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.util.UUID @Entity(tableName = "bookMetaData") data class BookMetaData( @ColumnInfo(name = "id") @PrimaryKey val id: UUID, @ColumnInfo(name = "type") val type: Book.Type, @ColumnInfo(name = "author") val author: String?, @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "root") val root: String, @ColumnInfo(name = "addedAtMillis") val addedAtMillis: Long ) { init { require(name.isNotEmpty()) { "name must not be empty" } require(root.isNotEmpty()) { "root must not be empty" } } }
lgpl-3.0
518ada415e88778bf111ee5dbbdf68b4
22.206897
59
0.692422
3.451282
false
false
false
false
Kotlin/dokka
runners/maven-plugin/src/main/kotlin/MavenDokkaLogger.kt
1
613
package org.jetbrains.dokka.maven import org.apache.maven.plugin.logging.Log import org.jetbrains.dokka.utilities.DokkaLogger class MavenDokkaLogger(val log: Log) : DokkaLogger { override var warningsCount: Int = 0 override var errorsCount: Int = 0 override fun debug(message: String) = log.debug(message) override fun info(message: String) = log.info(message) override fun progress(message: String) = log.info(message) override fun warn(message: String) = log.warn(message).also { warningsCount++ } override fun error(message: String) = log.error(message).also { errorsCount++ } }
apache-2.0
1d5992adf24f275cadf150705893b2d1
39.866667
83
0.738989
3.807453
false
false
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/modules/ReactionRoles.kt
1
4661
package me.mrkirby153.KirBot.modules import com.google.common.cache.CacheBuilder import com.google.common.cache.CacheLoader import com.mrkirby153.bfs.model.Model import me.mrkirby153.KirBot.database.models.guild.ReactionRole import me.mrkirby153.KirBot.event.Subscribe import me.mrkirby153.KirBot.module.Module import me.mrkirby153.KirBot.utils.checkPermissions import me.mrkirby153.KirBot.utils.nameAndDiscrim import me.mrkirby153.kcutils.utils.IdGenerator import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.entities.Member import net.dv8tion.jda.api.entities.Message import net.dv8tion.jda.api.entities.Role import net.dv8tion.jda.api.events.message.MessageDeleteEvent import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent import net.dv8tion.jda.api.events.message.react.MessageReactionRemoveEvent class ReactionRoles : Module("reaction-roles") { private val reactionRoleCache = CacheBuilder.newBuilder().maximumSize(100).build(object : CacheLoader<String, List<ReactionRole>>() { override fun load(key: String): List<ReactionRole> { return Model.where(ReactionRole::class.java, "message_id", key).get() } }) private val idGenerator = IdGenerator(IdGenerator.ALPHA + IdGenerator.NUMBERS) override fun onLoad() { } @Subscribe fun onReactionAdd(event: MessageReactionAddEvent) { val member = event.member ?: return val rolesToGive = getRoles(event, member, false) if (rolesToGive.isNotEmpty()) if (event.guild.selfMember.canInteract(member)) { debug("Giving ${member.user.nameAndDiscrim} ${rolesToGive.size} roles") rolesToGive.forEach { event.guild.addRoleToMember(member, it).queue() } } else { debug("Can't give ${member.user.nameAndDiscrim} roles") } } @Subscribe fun onReactionRemove(event: MessageReactionRemoveEvent) { val member = event.member ?: return val rolesToTake = getRoles(event, member, true) if (rolesToTake.isNotEmpty()) if (event.guild.selfMember.canInteract(member)) { debug("Taking ${member.user.nameAndDiscrim} ${rolesToTake.size} roles") rolesToTake.forEach { event.guild.removeRoleFromMember(member, it).queue() } } else { debug("Can't take ${member.user.nameAndDiscrim} roles") } } @Subscribe fun onMessageDelete(event: MessageDeleteEvent) { // Clean up any reaction roles Model.where(ReactionRole::class.java, "message_id", event.messageId).delete() } fun addReactionRole(message: Message, role: Role, emote: String, custom: Boolean) { val rc = ReactionRole() rc.id = idGenerator.generate(10) rc.channelId = message.channel.id rc.messageId = message.id rc.role = role rc.emote = emote rc.custom = custom rc.save() // Invalidate the cache reactionRoleCache.invalidate(message.id) // Add our reaction to the message if(message.channel.checkPermissions(Permission.MESSAGE_ADD_REACTION)) { if (custom) { val resolvedEmote = message.guild.getEmoteById(emote) ?: return message.addReaction(resolvedEmote).queue() } else { message.addReaction(emote).queue() } } } @Throws(IllegalArgumentException::class) fun removeReactionRole(id: String, guild: Guild) { val role = Model.where(ReactionRole::class.java, "id", id).first() ?: throw IllegalArgumentException("No reaction role with that id was found") if (role.guildId != guild.id) throw IllegalArgumentException("Reaction role not found on this guild") reactionRoleCache.invalidate(role.messageId) role.delete() } private fun getRoles(event: GenericMessageReactionEvent, member: Member, has: Boolean): List<Role> { val roles = reactionRoleCache.get(event.messageId) val matchingReactionRoles = roles.filter { role -> if (event.reactionEmote.isEmote) role.emote == event.reactionEmote.emote.id else role.emote == event.reactionEmote.name } val rolesToGive = matchingReactionRoles.mapNotNull { it.role }.filter { if (has) it in member.roles else it !in member.roles } return rolesToGive } }
mit
379797d3090cd2d21042df438059cd4f
37.528926
180
0.664664
4.214286
false
false
false
false
LummECS/Lumm
lumm/core/src/main/java/dk/sidereal/lumm/components/renderer/color/ColorDrawerBuilder.kt
1
2220
package dk.sidereal.lumm.components.renderer.color import com.badlogic.gdx.graphics.Color import dk.sidereal.lumm.components.renderer.Drawer import dk.sidereal.lumm.components.renderer.DrawerBuilder public class ColorDrawerBuilder() : DrawerBuilder<ColorDrawer>() { private var sizeX: Float = 0.toFloat() private var sizeY:Float = 0.toFloat() private var offsetX: Float = 0.toFloat() private var offsetY:Float = 0.toFloat() private var originX: Float = 0.toFloat() private val originY: Float = 0.toFloat() private var rotationDegrees: Float = 0.toFloat() private var tintColor: Color? = null private var transparency: Float = 0.toFloat() override fun build(name: String?): ColorDrawer { val drawer = ColorDrawer(renderer, null, true) if (sizeX != 0f && sizeY != 0f) drawer.setSize(sizeX, sizeY) drawer.setOffsetPosition(offsetX, offsetY) drawer.setOrigin(originX, originY) if (tintColor != null) drawer.setTintColor(tintColor!!) drawer.setRotation(rotationDegrees, false) return drawer } // region setters and getters fun setSize(sizeX: Float, sizeY: Float): ColorDrawerBuilder { this.sizeX = sizeX this.sizeY = sizeY return this } fun setSizeAndCenter(sizeX: Float, sizeY: Float): ColorDrawerBuilder { return setSize(sizeX, sizeY).setOffsetPosition(-sizeX / 2f, -sizeY / 2f) } fun setOffsetPosition(offsetX: Float, offsetY: Float): ColorDrawerBuilder { this.offsetX = offsetX this.offsetY = offsetY return this } fun setOrigin(originX: Float, originY: Float): ColorDrawerBuilder { this.originX = originX this.offsetY = originY return this } fun setRotation(rotationDegrees: Float): ColorDrawerBuilder { this.rotationDegrees = rotationDegrees return this } fun setColor(tintColor: Color): ColorDrawerBuilder { this.tintColor = tintColor return this } fun setTransparency(transparency: Float): ColorDrawerBuilder { this.transparency = transparency return this } // endregion }
apache-2.0
3e4e9f8303b79fc5864c945d0c687d71
25.759036
80
0.662162
4.615385
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsBorrowCheckerInspection.kt
3
1987
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.codeInspection.ProblemsHolder import org.rust.ide.annotator.fixes.AddMutableFix import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.types.isMutable import org.rust.lang.core.types.ty.TyReference import org.rust.lang.core.types.type class RsBorrowCheckerInspection : RsLocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitMethodCall(o: RsMethodCall) { val fn = o.reference.resolve() as? RsFunction ?: return val receiver = o.receiver if (checkMethodRequiresMutable(receiver, fn)) { registerProblem(holder, receiver, receiver) } } override fun visitUnaryExpr(unaryExpr: RsUnaryExpr) { val expr = unaryExpr.expr ?: return if (unaryExpr.operatorType == UnaryOperator.REF_MUT && !expr.isMutable) { registerProblem(holder, expr, expr) } } } private fun registerProblem(holder: ProblemsHolder, expr: RsExpr, nameExpr: RsExpr) { val fix = AddMutableFix.createIfCompatible(nameExpr).let { if (it == null) emptyArray() else arrayOf(it) } holder.registerProblem(expr, "Cannot borrow immutable local variable `${nameExpr.text}` as mutable", *fix) } private fun checkMethodRequiresMutable(receiver: RsExpr, fn: RsFunction): Boolean { if (!receiver.isMutable && fn.selfParameter != null && fn.selfParameter?.mutability?.isMut == true && fn.selfParameter?.isRef == true) { val type = receiver.type return type !is TyReference || !type.mutability.isMut } return false } }
mit
9dafab3c9f3aafba10962f4846926663
37.211538
114
0.638148
4.567816
false
false
false
false
androidthings/endtoend-base
companionApp/src/main/java/com/example/androidthings/endtoend/companion/domain/SendToggleCommandUseCase.kt
1
6694
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androidthings.endtoend.companion.domain import android.util.Log import com.example.androidthings.endtoend.companion.data.ToggleCommand import com.example.androidthings.endtoend.companion.data.ToggleCommandDao import com.example.androidthings.endtoend.shared.domain.Result import com.example.androidthings.endtoend.shared.domain.UseCase import com.example.androidthings.endtoend.shared.util.jsonArray import com.example.androidthings.endtoend.shared.util.jsonObject import com.google.firebase.functions.FirebaseFunctions import org.json.JSONObject import java.util.UUID import java.util.concurrent.TimeoutException /** Use case parameters. */ data class SendToggleCommandParameters( val userId: String, val command: ToggleCommand, val timeout: Long = 0 ) /** Wrapper class that reports the result state of a given request. */ data class SendToggleCommandResult( val command: ToggleCommand, val result: Result<Unit> ) /** Use case that sends a toggle request to a Cloud Function. */ class SendToggleCommandUseCase( private val toggleCommandDao: ToggleCommandDao ) : UseCase<SendToggleCommandParameters, SendToggleCommandResult>() { private val firebaseFunctions = FirebaseFunctions.getInstance() override fun execute(parameters: SendToggleCommandParameters) { scheduler.execute { executeSync(parameters) } } private fun executeSync(parameters: SendToggleCommandParameters) { val command = parameters.command if (!toggleCommandDao.addCommand(command)) { // There's already a command for this toggle, so report an error. result.postValue(SendToggleCommandResult( command, Result.Error(IllegalArgumentException("A request already exists for this toggle"))) ) return } val json = buildJsonPayload(parameters) if (json == null) { // Nothing to send, so make sure the command is removed from local storage. toggleCommandDao.removeCommand(command) result.postValue( SendToggleCommandResult( command, Result.Error(IllegalArgumentException("Error converting command to JSON")) ) ) return } // Notify that we're loading result.postValue( SendToggleCommandResult(command, Result.Loading) ) // Call the cloud function firebaseFunctions.getHttpsCallable("toggleCommand") // TODO replace with function name .call(json) .addOnCompleteListener { task -> if (task.isSuccessful) { if (parameters.timeout > 0) { scheduleDelayedTimeout(parameters) } else { SendToggleCommandResult(command, Result.success) } } else { // Sending failed, so make sure the command is removed from local storage. toggleCommandDao.removeCommand(command) val ex = task.exception ?: RuntimeException("Task failed with unknown error") result.postValue( SendToggleCommandResult(command, Result.Error(ex)) ) } } } private fun scheduleDelayedTimeout(parameters: SendToggleCommandParameters) { scheduler.executeDelayed(parameters.timeout) { val removed = toggleCommandDao.removeCommand(parameters.command) result.postValue( SendToggleCommandResult( parameters.command, if (removed) { Result.Error(TimeoutException("Toggle request timed out")) } else { Result.success } ) ) } } /** * Create a JSON payload for the Cloud Function. Returns null if the conversion fails. */ private fun buildJsonPayload(parameters: SendToggleCommandParameters): JSONObject? { val command = parameters.command try { return jsonObject( "requestId" to UUID.randomUUID().toString(), "inputs" to jsonArray( jsonObject( "intent" to "action.devices.EXECUTE", "payload" to jsonObject( "commands" to jsonArray( jsonObject( "devices" to jsonArray( jsonObject( "id" to command.gizmoId, "customData" to jsonObject( // Cloud Function needs this to look up FCM token "userId" to parameters.userId ) ) ), "execution" to jsonArray( jsonObject( "command" to "action.devices.commands.SetToggles", "params" to jsonObject( "updateToggleSettings" to jsonObject( command.toggleId to command.targetState ) ) ) ) ) ) ) ) ) ) } catch (e: Exception) { Log.e("SendToggleCommandUseCase", "Error buillding payload from command: $command") } return null } }
apache-2.0
b8e28fb2915fc68189d3cc6a40b22440
39.083832
99
0.540783
5.83101
false
false
false
false
GlimpseFramework/glimpse-framework
api/src/main/kotlin/glimpse/SquareMatrix.kt
1
1800
package glimpse internal class SquareMatrix(val size: Int, private val elements: (Int, Int) -> Float) { companion object { fun nullMatrix(size: Int) = SquareMatrix(size) { row, col -> 0f } fun identity(size: Int) = SquareMatrix(size) { row, col -> if (row == col) 1f else 0f } } operator fun get(row: Int, col: Int): Float { require(row in 0..size - 1) { "Row ${row} out of bounds: 0..${size - 1}" } require(col in 0..size - 1) { "Column ${col} out of bounds: 0..${size - 1}" } return elements(row, col) } /** * Determinant of the matrix. */ val det: Float by lazy { if (size == 1) this[0, 0] else (0..size - 1).map { item -> this[0, item] * comatrix[0, item] }.sum() } private val comatrix: SquareMatrix by lazy { SquareMatrix(size) { row, col -> cofactor(row, col) } } private fun cofactor(row: Int, col: Int): Float = minor(row, col) * if ((row + col) % 2 == 0) 1f else -1f private fun minor(row: Int, col: Int): Float = sub(row, col).det internal fun sub(delRow: Int, delCol: Int) = SquareMatrix(size - 1) { row, col -> this[if (row < delRow) row else row + 1, if (col < delCol) col else col + 1] } /** * Adjugate matrix. */ val adj: SquareMatrix by lazy { comatrix.transpose() } fun transpose(): SquareMatrix = SquareMatrix(size) { row, col -> this[col, row] } fun inverse(): SquareMatrix = SquareMatrix(size) { row, col -> adj[row, col] / det } operator fun times(other: SquareMatrix): SquareMatrix { require(other.size == size) { "Cannot multiply matrices of different sizes." } return SquareMatrix(size) { row, col -> (0..size - 1).map {this[row, it] * other[it, col] }.sum() } } fun asList(): List<Float> = (0..size * size - 1).map { this[it % size, it / size] } fun asMatrix(): Matrix = Matrix(asList()) }
apache-2.0
815204749e4f585941156f85353ea76e
28.032258
87
0.617222
2.870813
false
false
false
false
MFlisar/Lumberjack
library/src/main/java/timber/log/BaseTree.kt
1
7176
package timber.log import android.util.Log import com.michaelflisar.lumberjack.L import com.michaelflisar.lumberjack.data.StackData import java.io.PrintWriter import java.io.StringWriter abstract class BaseTree : Timber.Tree() { // we overwrite all log functions because the base classes Timber.prepareLog is private and we need to make a small adjustment // to get correct line numbers for kotlin exceptions (only the IDE does convert the line limbers correctly based on a mapping table) override fun v(message: String?, vararg args: Any?) { prepareLog( Log.VERBOSE, null, message, *args ) } override fun v(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.VERBOSE, t, message, *args ) } override fun v(t: Throwable?) { prepareLog(Log.VERBOSE, t, null) } override fun d(message: String?, vararg args: Any?) { prepareLog(Log.DEBUG, null, message, *args) } override fun d(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.DEBUG, t, message, *args ) } override fun d(t: Throwable?) { prepareLog(Log.DEBUG, t, null) } override fun i(message: String?, vararg args: Any?) { prepareLog(Log.INFO, null, message, *args) } override fun i(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.INFO, t, message, *args ) } override fun i(t: Throwable?) { prepareLog(Log.INFO, t, null) } override fun w(message: String?, vararg args: Any?) { prepareLog(Log.WARN, null, message, *args) } override fun w(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.WARN, t, message, *args ) } override fun w(t: Throwable?) { prepareLog(Log.WARN, t, null) } override fun e(message: String?, vararg args: Any?) { prepareLog(Log.ERROR, null, message, *args) } override fun e(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.ERROR, t, message, *args ) } override fun e(t: Throwable?) { prepareLog(Log.ERROR, t, null) } override fun wtf(message: String?, vararg args: Any?) { prepareLog( Log.ASSERT, null, message, *args ) } override fun wtf(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.ASSERT, t, message, *args ) } override fun wtf(t: Throwable?) { prepareLog(Log.ASSERT, t, null) } override fun log(priority: Int, message: String?, vararg args: Any?) { prepareLog( priority, null, message, *args ) } override fun log(priority: Int, t: Throwable?, message: String?, vararg args: Any?) { prepareLog( priority, t, message, *args ) } override fun log(priority: Int, t: Throwable?) { prepareLog(priority, t, null) } override fun isLoggable(tag: String?, priority: Int): Boolean { return tag == null || (L.filter?.isTagEnabled(this, tag) ?: true) } // copied from Timber.Tree because it's private in the base class private fun getStackTraceString(t: Throwable): String { // Don't replace this with Log.getStackTraceString() - it hides // UnknownHostException, which is not what we want. val sw = StringWriter(256) val pw = PrintWriter(sw, false) t.printStackTrace(pw) pw.flush() return sw.toString() } // -------------------- // custom code // -------------------- private fun prepareLog(priority: Int, t: Throwable?, message: String?, vararg args: Any?) { // custom: we create a stack data object val callStackCorrection = getCallStackCorrection() ?: 0 var stackData = getStackTrace() stackData = stackData.copy(callStackIndex = stackData.callStackIndex + callStackCorrection) // Consume tag even when message is not loggable so that next message is correctly tagged. @Suppress("NAME_SHADOWING") var message = message val customTag = super.getTag() val prefix = getPrefix(customTag, stackData) if (!isLoggable(customTag, priority)) { return } if (message != null && message.isEmpty()) { message = null } if (message == null) { if (t == null) { return // Swallow message if it's null and there's no throwable. } message = getStackTraceString(t) } else { if (args.isNotEmpty()) { message = String.format(message, *args) } if (t != null) { message += " - " + getStackTraceString(t).trimIndent() } } log(priority, prefix, message, t, stackData) } final override fun log( priority: Int, tag: String?, message: String, t: Throwable? ) { /* empty, we use our own function with StackData */ } abstract fun log( priority: Int, prefix: String, message: String, t: Throwable?, stackData: StackData ) // -------------------- // custom code - extended tag // -------------------- protected fun formatLine(prefix: String, message: String) = L.formatter.formatLine(this, prefix, message) // -------------------- // custom code - extended tag // -------------------- private fun getPrefix(customTag: String?, stackData: StackData): String { return L.formatter.formatLogPrefix(customTag, stackData) } // -------------------- // custom code - callstack depth // -------------------- companion object { internal const val CALL_STACK_INDEX = 4 } private val callStackCorrection = ThreadLocal<Int>() private fun getCallStackCorrection(): Int? { val correction = callStackCorrection.get() if (correction != null) { callStackCorrection.remove() } return correction } internal fun setCallStackCorrection(value: Int) { callStackCorrection.set(value) } private val stackTrace = ThreadLocal<StackData>() private fun getStackTrace(): StackData { val trace = stackTrace.get()!! stackTrace.remove() return trace } internal fun setStackTrace(trace: StackData) { stackTrace.set(trace) } }
apache-2.0
2d0852bb454c82345914b3e12153ded1
26.39313
136
0.526895
4.620734
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/provider/GamesIdPublishersProvider.kt
1
1744
package com.boardgamegeek.provider import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.net.Uri import android.provider.BaseColumns import com.boardgamegeek.provider.BggContract.* import com.boardgamegeek.provider.BggContract.Companion.PATH_GAMES import com.boardgamegeek.provider.BggContract.Companion.PATH_PUBLISHERS import com.boardgamegeek.provider.BggDatabase.GamesPublishers.GAME_ID import com.boardgamegeek.provider.BggDatabase.Tables class GamesIdPublishersProvider : BaseProvider() { override fun getType(uri: Uri) = Publishers.CONTENT_TYPE override val path = "$PATH_GAMES/#/$PATH_PUBLISHERS" override val defaultSortOrder = Publishers.DEFAULT_SORT public override fun buildSimpleSelection(uri: Uri): SelectionBuilder { val gameId = Games.getGameId(uri) return SelectionBuilder().table(Tables.GAMES_PUBLISHERS).whereEquals(GAME_ID, gameId) } override fun buildExpandedSelection(uri: Uri): SelectionBuilder { val gameId = Games.getGameId(uri) return SelectionBuilder() .table(Tables.GAMES_PUBLISHERS_JOIN_PUBLISHERS) .mapToTable(BaseColumns._ID, Tables.PUBLISHERS) .mapToTable(Publishers.Columns.PUBLISHER_ID, Tables.PUBLISHERS) .mapToTable(Publishers.Columns.UPDATED, Tables.PUBLISHERS) .whereEquals("${Tables.GAMES_PUBLISHERS}.$GAME_ID", gameId) } override fun insert(context: Context, db: SQLiteDatabase, uri: Uri, values: ContentValues): Uri { values.put(GAME_ID, Games.getGameId(uri)) val rowId = db.insertOrThrow(Tables.GAMES_PUBLISHERS, null, values) return Games.buildPublisherUri(rowId) } }
gpl-3.0
547d749b8a8961083d857da1371080fe
41.536585
101
0.750573
4.48329
false
false
false
false
shkschneider/android_Skeleton
core/src/main/kotlin/me/shkschneider/skeleton/ui/transforms/ZoomOutTranformer.kt
1
697
package me.shkschneider.skeleton.ui.transforms import android.view.View // <https://github.com/ToxicBakery/ViewPagerTransforms> class ZoomOutTranformer : BaseTransformer() { override fun onTransform(page: View, position: Float) { val scale = 1.toFloat() + Math.abs(position) page.scaleX = scale page.scaleY = scale page.pivotX = page.width * 0.1.toFloat() page.pivotY = page.height * 0.1.toFloat() page.alpha = if (position < (-1).toFloat() || position > 1.toFloat()) 1.toFloat() else 1.toFloat() - (scale - 1.toFloat()) if (position == (-1).toFloat()) { page.translationX = (page.width * -1).toFloat() } } }
apache-2.0
95ba3def6db407573473097a0b100ea0
33.85
130
0.618364
3.611399
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/data/LanternDataRegistrationBuilder.kt
1
2649
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data import org.lanternpowered.api.cause.CauseStack import org.lanternpowered.api.cause.first import org.lanternpowered.api.plugin.PluginContainer import org.lanternpowered.api.util.collections.toImmutableList import org.lanternpowered.api.util.collections.toImmutableMap import org.lanternpowered.api.util.collections.toImmutableSet import org.lanternpowered.server.catalog.AbstractCatalogBuilder import org.lanternpowered.api.key.NamespacedKey import org.spongepowered.api.data.DataProvider import org.spongepowered.api.data.DataRegistration import org.spongepowered.api.data.DuplicateProviderException import org.spongepowered.api.data.Key import org.spongepowered.api.data.persistence.DataStore class LanternDataRegistrationBuilder : AbstractCatalogBuilder<DataRegistration, DataRegistration.Builder>(), DataRegistration.Builder { private val keys = mutableSetOf<Key<*>>() private var providers = mutableMapOf<Key<*>, DataProvider<*, *>>() private var stores = mutableListOf<DataStore>() override fun store(store: DataStore) = apply { // TODO: Check for overlapping store targets this.stores.add(store) } override fun provider(provider: DataProvider<*, *>) = apply { val key = provider.getKey() if (!this.providers.containsKey(key)) throw DuplicateProviderException() this.providers[key] = provider key(key) } override fun key(key: Key<*>) = apply { this.keys.add(key) } override fun key(key: Key<*>, vararg others: Key<*>) = apply { key(key) key(others.asIterable()) } override fun key(keys: Iterable<Key<*>>) = apply { keys.forEach { key(it) } } override fun reset() = apply { super.reset() this.keys.clear() this.providers.clear() this.stores.clear() } override fun build(key: NamespacedKey): DataRegistration { val keys = this.keys.toImmutableSet() check(keys.isNotEmpty()) { "At least one key must be added" } val pluginContainer = CauseStack.first<PluginContainer>()!! val providers = this.providers.toImmutableMap() val stores = this.stores.toImmutableList() return LanternDataRegistration(key, pluginContainer, keys, stores, providers) } }
mit
5f244349cf9b1aac62a6c6c84ecc446e
34.797297
135
0.711212
4.415
false
false
false
false
koreader/android-luajit-launcher
app/src/main/java/org/koreader/launcher/device/lights/TolinoRootController.kt
1
4976
package org.koreader.launcher.device.lights import android.app.Activity import android.provider.Settings import android.util.Log import org.koreader.launcher.device.LightsInterface import org.koreader.launcher.extensions.read import org.koreader.launcher.extensions.write import java.io.File /* Special controller for Tolino Epos/Epos2. * see https://github.com/koreader/koreader/pull/6332 * * Thanks to @zwim */ class TolinoRootController : LightsInterface { companion object { private const val TAG = "Lights" private const val BRIGHTNESS_MAX = 255 private const val WARMTH_MAX = 10 private const val MIN = 0 private const val ACTUAL_BRIGHTNESS_FILE = "/sys/class/backlight/mxc_msp430_fl.0/actual_brightness" // always readable, same for Epos2 and Vision4 private const val COLOR_FILE_EPOS2 = "/sys/class/backlight/tlc5947_bl/color" private const val COLOR_FILE_VISION4HD = "/sys/class/backlight/lm3630a_led/color" private val COLOR_FILE = if (File(COLOR_FILE_VISION4HD).exists()) COLOR_FILE_VISION4HD else COLOR_FILE_EPOS2 } override fun getPlatform(): String { return "tolino" } override fun hasFallback(): Boolean { return false } override fun hasWarmth(): Boolean { return true } override fun needsPermission(): Boolean { return false } // try to toggle on frontlight switch on Tolinos, returns the former switch state override fun enableFrontlightSwitch(activity: Activity): Int { // ATTENTION: getBrightness, setBrightness use the Android range 0..255 // in the brightness files the used range is 0..100 val startBrightness = getBrightness(activity) val actualBrightnessFile = File(ACTUAL_BRIGHTNESS_FILE) val startBrightnessFromFile = try { actualBrightnessFile.readText().trim().toInt() } catch (e: Exception) { Log.w(TAG, "$e") -1 } // change the brightness through android. Be aware one step in Android is less than one step in the file if (startBrightness > BRIGHTNESS_MAX/2) setBrightness(activity, startBrightness - (BRIGHTNESS_MAX/100+1)) else setBrightness(activity, startBrightness + (BRIGHTNESS_MAX/100+1)) // we have to wait until the android changes seep through to the file, // 50ms is to less, 60ms seems to work, so use 80 to have some safety Thread.sleep(80) val actualBrightnessFromFile = try { actualBrightnessFile.readText().trim().toInt() } catch (e: Exception) { Log.w(TAG, "$e") -1 } setBrightness(activity, startBrightness) if (startBrightnessFromFile == actualBrightnessFromFile) { return try { // try to send keyevent to system to turn on frontlight, needs extended permissions Runtime.getRuntime().exec("su -c input keyevent KEYCODE_BUTTON_A && echo OK") 1 } catch (e: Exception) { e.printStackTrace() 0 } } return 1 } override fun getBrightness(activity: Activity): Int { return try { Settings.System.getInt(activity.applicationContext.contentResolver, "screen_brightness") } catch (e: Exception) { Log.w(TAG, e.toString()) 0 } } override fun getWarmth(activity: Activity): Int { return WARMTH_MAX - File(COLOR_FILE).read() } override fun setBrightness(activity: Activity, brightness: Int) { if (brightness < MIN || brightness > BRIGHTNESS_MAX) { Log.w(TAG, "brightness value of of range: $brightness") return } Log.v(TAG, "Setting brightness to $brightness") try { Settings.System.putInt(activity.applicationContext.contentResolver, "screen_brightness", brightness) } catch (e: Exception) { Log.w(TAG, "$e") } } override fun setWarmth(activity: Activity, warmth: Int) { if (warmth < MIN || warmth > WARMTH_MAX) { Log.w(TAG, "warmth value of of range: $warmth") return } val colorFile = File(COLOR_FILE) Log.v(TAG, "Setting warmth to $warmth") try { if (!colorFile.canWrite()) { Runtime.getRuntime().exec("su -c chmod 666 $COLOR_FILE") } colorFile.write(WARMTH_MAX - warmth) } catch (e: Exception) { Log.w(TAG, "$e") } } override fun getMinWarmth(): Int { return MIN } override fun getMaxWarmth(): Int { return WARMTH_MAX } override fun getMinBrightness(): Int { return MIN } override fun getMaxBrightness(): Int { return BRIGHTNESS_MAX } }
mit
069ec9fcdfe0e67e6778cc865337a30f
31.311688
154
0.606913
4.282272
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/services/RecentSearchesServices.kt
1
2287
package com.pr0gramm.app.services import android.content.SharedPreferences import androidx.core.content.edit import com.pr0gramm.app.Logger import com.pr0gramm.app.MoshiInstance import com.pr0gramm.app.util.getStringOrNull import java.util.* import kotlin.reflect.javaType import kotlin.reflect.typeOf /** * Helps with recent searches */ class RecentSearchesServices( private val sharedPreferences: SharedPreferences) { private val logger = Logger("RecentSearchesServices") private val searches: MutableList<String> = ArrayList() init { restoreState() } fun storeTerm(term: String) { synchronized(searches) { removeCaseInsensitive(term) searches.add(0, term) persistStateAsync() } } fun searches(): List<String> { synchronized(searches) { return searches.toList() } } fun clearHistory() { synchronized(searches) { searches.clear() persistStateAsync() } } /** * Removes all occurrences of the given term, independend of case. */ private fun removeCaseInsensitive(term: String) { searches.removeAll { it.equals(term, ignoreCase = true) } } private fun persistStateAsync() { try { // write searches as json val encoded = MoshiInstance.adapter<List<String>>(LIST_OF_STRINGS).toJson(searches) sharedPreferences.edit { putString(KEY, encoded) } } catch (ignored: Exception) { logger.warn { "Could not persist recent searches" } } } private fun restoreState() { try { val serialized = sharedPreferences.getStringOrNull(KEY) ?: "[]" searches.addAll(MoshiInstance.adapter<List<String>>(LIST_OF_STRINGS).fromJson(serialized) ?: listOf()) } catch (error: Exception) { logger.warn("Could not deserialize recent searches", error) } } companion object { private const val KEY = "RecentSearchesServices.terms" @OptIn(ExperimentalStdlibApi::class) @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") private val LIST_OF_STRINGS = typeOf<java.util.List<String>>().javaType } }
mit
f60b1e4355c0bc16c216184e1c615e94
25.593023
101
0.628334
4.60161
false
false
false
false
TWiStErRob/TWiStErRob
JFixturePlayground/src/main/java/net/twisterrob/test/jfixture/examples/journey/JourneyMapper.kt
1
545
package net.twisterrob.test.jfixture.examples.journey import net.twisterrob.test.jfixture.examples.journey.TransportMode.TRAIN import java.time.Duration class JourneyMapper : (Journey) -> Model { override fun invoke(journey: Journey) = Model( journey.id, origin = journey.legs.first().origin.name, destination = journey.legs.last().destination.name, length = Duration.between(journey.legs.first().departure, journey.legs.last().arrival), changeCount = journey.legs.size - 1, trainOnly = journey.legs.all { it.mode == TRAIN } ) }
unlicense
f29130da94c9cee104c60b305d45e03e
35.333333
89
0.752294
3.516129
false
true
false
false
SuperAwesomeLTD/sa-mobile-sdk-android
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/components/ConnectionProvider.kt
1
2275
package tv.superawesome.sdk.publisher.common.components import android.content.Context import android.net.ConnectivityManager import android.telephony.TelephonyManager import tv.superawesome.sdk.publisher.common.models.ConnectionType interface ConnectionProviderType { fun findConnectionType(): ConnectionType } class ConnectionProvider(private val context: Context) : ConnectionProviderType { override fun findConnectionType(): ConnectionType { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return ConnectionType.Unknown return findConnectionTypeLegacy(connectivityManager) } private fun findCellularType(type: Int): ConnectionType = when (type) { TelephonyManager.NETWORK_TYPE_UNKNOWN -> ConnectionType.Unknown TelephonyManager.NETWORK_TYPE_GSM, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN, TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_EDGE -> ConnectionType.Cellular2g TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP, TelephonyManager.NETWORK_TYPE_TD_SCDMA -> ConnectionType.Cellular3g TelephonyManager.NETWORK_TYPE_LTE, TelephonyManager.NETWORK_TYPE_IWLAN -> ConnectionType.Cellular4g else -> ConnectionType.Unknown } @Suppress("DEPRECATION") private fun findConnectionTypeLegacy(connectivityManager: ConnectivityManager): ConnectionType { val info = connectivityManager.activeNetworkInfo if (info == null || !info.isConnected) return ConnectionType.Unknown if (info.type == ConnectivityManager.TYPE_WIFI) return ConnectionType.Wifi if (info.type == ConnectivityManager.TYPE_MOBILE) return findCellularType(info.subtype) return ConnectionType.Unknown } }
lgpl-3.0
57fdda0116b6e4d12194fb0d2b2e61de
41.12963
100
0.741978
5.022075
false
false
false
false
NextFaze/dev-fun
devfun-internal/src/main/java/com/nextfaze/devfun/internal/pref/SharedPreferences.kt
1
6336
@file:Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") package com.nextfaze.devfun.internal.pref import android.content.Context import android.content.SharedPreferences import kotlin.reflect.KClass import kotlin.reflect.KProperty import java.lang.Enum as JavaLangEnum typealias OnChange<T> = (T, T) -> Unit interface KPreference<TValue : Any?> { var value: TValue val isSet: Boolean fun delete() operator fun getValue(thisRef: Any?, property: KProperty<*>): TValue operator fun setValue(thisRef: Any?, property: KProperty<*>, value: TValue) } interface KNullablePreference<T : Any> : KPreference<T?> class KSharedPreferences(private val preferences: SharedPreferences) { companion object { fun named(context: Context, name: String) = KSharedPreferences(context.getSharedPreferences(name, Context.MODE_PRIVATE)) } fun clear() { preferences.edit().clear().apply() } operator fun get(key: String, default: String): KPreference<String> = KStringPref(preferences, key, default) operator fun get(key: String, default: Int): KPreference<Int> = KIntPref(preferences, key, default) operator fun get(key: String, default: Long, onChange: OnChange<Long>? = null): KPreference<Long> = KLongPref(preferences, key, default, onChange) operator fun get(key: String, default: Float): KPreference<Float> = KFloatPref(preferences, key, default) operator fun get(key: String, default: Boolean, onChange: OnChange<Boolean>? = null): KPreference<Boolean> = KBooleanPref(preferences, key, default, onChange) operator fun <E : Enum<E>> get(key: String, default: E, onChange: OnChange<E>? = null): KPreference<E> = KEnumPref(preferences, key, default, onChange) operator fun get(key: String, default: Int? = null): KNullablePreference<Int> = KNullableIntPref(preferences, key, default) } private abstract class KPreferenceBase<TValue : Any?>( protected val preferences: SharedPreferences, protected val key: String, protected val default: TValue ) : KPreference<TValue> { override val isSet: Boolean get() = preferences.contains(key) override fun delete() = preferences.edit().remove(key).apply() override operator fun getValue(thisRef: Any?, property: KProperty<*>): TValue = value override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: TValue) { this.value = value } override fun toString() = "$key=$value ($default)" } private abstract class KPreferenceImpl<TValue : Any>( preferences: SharedPreferences, key: String, default: TValue ) : KPreferenceBase<TValue>(preferences, key, default) { abstract override var value: TValue } private abstract class KNullablePreferenceImpl<TValue : Any>( preferences: SharedPreferences, key: String, default: TValue? ) : KPreferenceBase<TValue?>(preferences, key, default) { abstract override var value: TValue? } private class KStringPref(preferences: SharedPreferences, key: String, default: String) : KPreferenceImpl<String>(preferences, key, default) { override var value: String get() = preferences.getString(key, default)!! set(value) = preferences.edit().putString(key, value).apply() } private class KIntPref(preferences: SharedPreferences, key: String, default: Int) : KPreferenceImpl<Int>(preferences, key, default) { override var value: Int get() = preferences.getInt(key, default) set(value) = preferences.edit().putInt(key, value).apply() } private class KNullableIntPref(preferences: SharedPreferences, key: String, default: Int?) : KNullablePreferenceImpl<Int>(preferences, key, default), KNullablePreference<Int> { override var value: Int? get() = if (preferences.contains(key)) preferences.getInt(key, 0) else null set(value) = preferences.edit().apply { when (value) { null -> remove(key) else -> putInt(key, value) } }.apply() } private class KLongPref(preferences: SharedPreferences, key: String, default: Long, private val onChange: OnChange<Long>?) : KPreferenceImpl<Long>(preferences, key, default) { override var value: Long get() = preferences.getLong(key, default) set(value) { val before = if (onChange != null) this.value else null preferences.edit().putLong(key, value).apply() if (onChange != null && before != null && before != value) { onChange.invoke(before, value) } } } private class KFloatPref(preferences: SharedPreferences, key: String, default: Float) : KPreferenceImpl<Float>(preferences, key, default) { override var value: Float get() = preferences.getFloat(key, default) set(value) = preferences.edit().putFloat(key, value).apply() } private class KBooleanPref(preferences: SharedPreferences, key: String, default: Boolean, private val onChange: OnChange<Boolean>?) : KPreferenceImpl<Boolean>(preferences, key, default) { override var value: Boolean get() = preferences.getBoolean(key, default) set(value) { val before = if (onChange != null) this.value else null preferences.edit().putBoolean(key, value).apply() if (onChange != null && before != null && before != value) { onChange.invoke(before, value) } } } private class KEnumPref<E : Enum<E>>(preferences: SharedPreferences, key: String, default: E, private val onChange: OnChange<E>?) : KPreferenceImpl<E>(preferences, key, default) { @Suppress("UNCHECKED_CAST") private val enumClass = default::class as KClass<E> override var value: E get() = enumClass.enumValueOf(preferences.getString(key, default.name)!!) ?: default set(value) { val before = if (onChange != null) this.value else null preferences.edit().putString(key, value.name).apply() if (onChange != null && before != null && before != value) { onChange.invoke(before, value) } } } private fun <E : Enum<E>> KClass<E>.enumValueOf(name: String): E? = try { JavaLangEnum.valueOf(java, name) } catch (ignore: Throwable) { null }
apache-2.0
cf91f8bc0b9c21904e58d1d553a0e69a
36.270588
133
0.669508
4.130378
false
false
false
false
henrikfroehling/timekeeper
domain/src/main/kotlin/de/froehling/henrik/timekeeper/domain/usecases/tasks/GetTasksUseCase.kt
1
2931
package de.froehling.henrik.timekeeper.domain.usecases.tasks import android.support.annotation.IntDef import kotlin.annotation.AnnotationRetention import kotlin.annotation.Retention import de.froehling.henrik.timekeeper.domain.executor.IPostThreadExecutor import de.froehling.henrik.timekeeper.domain.executor.IThreadExecutor import de.froehling.henrik.timekeeper.domain.repository.ITasksRepository import de.froehling.henrik.timekeeper.domain.usecases.UseCase import rx.Observable sealed class GetTasksUseCase(private val mTasksRepository: ITasksRepository, threadExecutor: IThreadExecutor, postThreadExecutor: IPostThreadExecutor) : UseCase(threadExecutor, postThreadExecutor) { @IntDef(FILTER_REQUEST_NAME_ASCENDING.toLong(), FILTER_REQUEST_NAME_DESCENDING.toLong(), FILTER_REQUEST_CREATED_ASCENDING.toLong(), FILTER_REQUEST_CREATED_DESCENDING.toLong(), FILTER_REQUEST_HOURLY_WAGE_ASCENDING.toLong(), FILTER_REQUEST_HOURLY_WAGE_DESCENDING.toLong(), FILTER_REQUEST_DURATION_ASCENDING.toLong(), FILTER_REQUEST_DURATION_DESCENDING.toLong()) @Retention(AnnotationRetention.SOURCE) annotation class FilterRequest @FilterRequest private var mFilterRequest = FILTER_REQUEST_NAME_ASCENDING fun setFilterRequest(@FilterRequest filterRequest: Int) { mFilterRequest = filterRequest } override fun buildUseCaseObservable(): Observable<out Any> { when (mFilterRequest) { FILTER_REQUEST_NAME_ASCENDING -> return mTasksRepository.getTasksFilteredByName(true) FILTER_REQUEST_NAME_DESCENDING -> return mTasksRepository.getTasksFilteredByName(false) FILTER_REQUEST_CREATED_ASCENDING -> return mTasksRepository.getTasksFilteredByCreated(true) FILTER_REQUEST_CREATED_DESCENDING -> return mTasksRepository.getTasksFilteredByCreated(false) FILTER_REQUEST_HOURLY_WAGE_ASCENDING -> return mTasksRepository.getTasksFilteredByHourlyWage(true) FILTER_REQUEST_HOURLY_WAGE_DESCENDING -> return mTasksRepository.getTasksFilteredByHourlyWage(false) FILTER_REQUEST_DURATION_ASCENDING -> return mTasksRepository.getTasksFilteredByDuration(true) FILTER_REQUEST_DURATION_DESCENDING -> return mTasksRepository.getTasksFilteredByDuration(false) } return mTasksRepository.getTasksFilteredByName(true) } companion object { const val FILTER_REQUEST_NAME_ASCENDING = 100 const val FILTER_REQUEST_NAME_DESCENDING = 200 const val FILTER_REQUEST_CREATED_ASCENDING = 300 const val FILTER_REQUEST_CREATED_DESCENDING = 400 const val FILTER_REQUEST_HOURLY_WAGE_ASCENDING = 500 const val FILTER_REQUEST_HOURLY_WAGE_DESCENDING = 600 const val FILTER_REQUEST_DURATION_ASCENDING = 700 const val FILTER_REQUEST_DURATION_DESCENDING = 800 } }
gpl-3.0
35059ff110477f9b21b9552666a00c31
50.421053
117
0.750256
4.572543
false
false
false
false
pedroSG94/rtmp-streamer-java
rtmp/src/main/java/com/pedro/rtmp/rtmp/RtmpClient.kt
1
17749
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtmp.rtmp import android.media.MediaCodec import android.util.Log import com.pedro.rtmp.amf.v0.AmfNumber import com.pedro.rtmp.amf.v0.AmfObject import com.pedro.rtmp.amf.v0.AmfString import com.pedro.rtmp.flv.video.ProfileIop import com.pedro.rtmp.rtmp.message.* import com.pedro.rtmp.rtmp.message.command.Command import com.pedro.rtmp.rtmp.message.control.Type import com.pedro.rtmp.rtmp.message.control.UserControl import com.pedro.rtmp.utils.AuthUtil import com.pedro.rtmp.utils.ConnectCheckerRtmp import com.pedro.rtmp.utils.CreateSSLSocket import com.pedro.rtmp.utils.RtmpConfig import java.io.* import java.net.InetSocketAddress import java.net.Socket import java.net.SocketAddress import java.net.SocketTimeoutException import java.nio.ByteBuffer import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit import java.util.regex.Pattern /** * Created by pedro on 8/04/21. */ class RtmpClient(private val connectCheckerRtmp: ConnectCheckerRtmp) { private val TAG = "RtmpClient" private val rtmpUrlPattern = Pattern.compile("^rtmps?://([^/:]+)(?::(\\d+))*/([^/]+)/?([^*]*)$") private var connectionSocket: Socket? = null private var reader: BufferedInputStream? = null private var writer: OutputStream? = null private var thread: ExecutorService? = null private val commandsManager = CommandsManager() private val rtmpSender = RtmpSender(connectCheckerRtmp, commandsManager) @Volatile var isStreaming = false private set private var url: String? = null private var tlsEnabled = false private var doingRetry = false private var numRetry = 0 private var reTries = 0 private var handler: ScheduledExecutorService? = null private var runnable: Runnable? = null private var publishPermitted = false val droppedAudioFrames: Long get() = rtmpSender.droppedAudioFrames val droppedVideoFrames: Long get() = rtmpSender.droppedVideoFrames val cacheSize: Int get() = rtmpSender.getCacheSize() val sentAudioFrames: Long get() = rtmpSender.getSentAudioFrames() val sentVideoFrames: Long get() = rtmpSender.getSentVideoFrames() /** * Must be called before connect */ fun setOnlyAudio(onlyAudio: Boolean) { commandsManager.audioDisabled = false commandsManager.videoDisabled = onlyAudio } /** * Must be called before connect */ fun setOnlyVideo(onlyVideo: Boolean) { commandsManager.videoDisabled = false commandsManager.audioDisabled = onlyVideo } fun forceAkamaiTs(enabled: Boolean) { commandsManager.akamaiTs = enabled } fun setWriteChunkSize(chunkSize: Int) { RtmpConfig.writeChunkSize = chunkSize } fun setAuthorization(user: String?, password: String?) { commandsManager.setAuth(user, password) } fun setReTries(reTries: Int) { numRetry = reTries this.reTries = reTries } fun shouldRetry(reason: String): Boolean { val validReason = doingRetry && !reason.contains("Endpoint malformed") return validReason && reTries > 0 } fun setAudioInfo(sampleRate: Int, isStereo: Boolean) { commandsManager.setAudioInfo(sampleRate, isStereo) rtmpSender.setAudioInfo(sampleRate, isStereo) } fun setVideoInfo(sps: ByteBuffer, pps: ByteBuffer, vps: ByteBuffer?) { Log.i(TAG, "send sps and pps") rtmpSender.setVideoInfo(sps, pps, vps) } fun setProfileIop(profileIop: ProfileIop) { rtmpSender.setProfileIop(profileIop) } fun setVideoResolution(width: Int, height: Int) { commandsManager.setVideoResolution(width, height) } fun setFps(fps: Int) { commandsManager.setFps(fps) } @JvmOverloads fun connect(url: String?, isRetry: Boolean = false) { if (!isRetry) doingRetry = true if (url == null) { isStreaming = false connectCheckerRtmp.onConnectionFailedRtmp( "Endpoint malformed, should be: rtmp://ip:port/appname/streamname") return } if (!isStreaming || isRetry) { this.url = url connectCheckerRtmp.onConnectionStartedRtmp(url) val rtmpMatcher = rtmpUrlPattern.matcher(url) if (rtmpMatcher.matches()) { tlsEnabled = (rtmpMatcher.group(0) ?: "").startsWith("rtmps") } else { connectCheckerRtmp.onConnectionFailedRtmp( "Endpoint malformed, should be: rtmp://ip:port/appname/streamname") return } commandsManager.host = rtmpMatcher.group(1) ?: "" val portStr = rtmpMatcher.group(2) commandsManager.port = portStr?.toInt() ?: 1935 commandsManager.appName = getAppName(rtmpMatcher.group(3) ?: "", rtmpMatcher.group(4) ?: "") commandsManager.streamName = getStreamName(rtmpMatcher.group(4) ?: "") commandsManager.tcUrl = getTcUrl((rtmpMatcher.group(0) ?: "").substring(0, (rtmpMatcher.group(0) ?: "").length - commandsManager.streamName.length)) isStreaming = true thread = Executors.newSingleThreadExecutor() thread?.execute post@{ try { if (!establishConnection()) { connectCheckerRtmp.onConnectionFailedRtmp("Handshake failed") return@post } val writer = this.writer ?: throw IOException("Invalid writer, Connection failed") commandsManager.sendChunkSize(writer) commandsManager.sendConnect("", writer) //read packets until you did success connection to server and you are ready to send packets while (!Thread.interrupted() && !publishPermitted) { //Handle all command received and send response for it. handleMessages() } //read packet because maybe server want send you something while streaming handleServerPackets() } catch (e: Exception) { Log.e(TAG, "connection error", e) connectCheckerRtmp.onConnectionFailedRtmp("Error configure stream, ${e.message}") return@post } } } } private fun handleServerPackets() { while (!Thread.interrupted()) { try { handleMessages() } catch (ignored: SocketTimeoutException) { //new packet not found } catch (e: Exception) { Thread.currentThread().interrupt() } } } private fun getAppName(app: String, name: String): String { return if (!name.contains("/")) { app } else { app + "/" + name.substring(0, name.indexOf("/")) } } private fun getStreamName(name: String): String { return if (!name.contains("/")) { name } else { name.substring(name.indexOf("/") + 1) } } private fun getTcUrl(url: String): String { return if (url.endsWith("/")) { url.substring(0, url.length - 1) } else { url } } @Throws(IOException::class) private fun establishConnection(): Boolean { val socket: Socket if (!tlsEnabled) { socket = Socket() val socketAddress: SocketAddress = InetSocketAddress(commandsManager.host, commandsManager.port) socket.connect(socketAddress, 5000) } else { socket = CreateSSLSocket.createSSlSocket(commandsManager.host, commandsManager.port) ?: throw IOException("Socket creation failed") } socket.soTimeout = 5000 val reader = BufferedInputStream(socket.getInputStream()) val writer = socket.getOutputStream() val timestamp = System.currentTimeMillis() / 1000 val handshake = Handshake() if (!handshake.sendHandshake(reader, writer)) return false commandsManager.timestamp = timestamp.toInt() commandsManager.startTs = System.nanoTime() / 1000 connectionSocket = socket this.reader = reader this.writer = writer return true } /** * Read all messages from server and response to it */ @Throws(IOException::class) private fun handleMessages() { val reader = this.reader ?: throw IOException("Invalid reader, Connection failed") var writer = this.writer ?: throw IOException("Invalid writer, Connection failed") val message = commandsManager.readMessageResponse(reader) when (message.getType()) { MessageType.SET_CHUNK_SIZE -> { val setChunkSize = message as SetChunkSize commandsManager.readChunkSize = setChunkSize.chunkSize Log.i(TAG, "chunk size configured to ${setChunkSize.chunkSize}") } MessageType.ACKNOWLEDGEMENT -> { val acknowledgement = message as Acknowledgement } MessageType.WINDOW_ACKNOWLEDGEMENT_SIZE -> { val windowAcknowledgementSize = message as WindowAcknowledgementSize RtmpConfig.acknowledgementWindowSize = windowAcknowledgementSize.acknowledgementWindowSize } MessageType.SET_PEER_BANDWIDTH -> { val setPeerBandwidth = message as SetPeerBandwidth commandsManager.sendWindowAcknowledgementSize(writer) } MessageType.ABORT -> { val abort = message as Abort } MessageType.AGGREGATE -> { val aggregate = message as Aggregate } MessageType.USER_CONTROL -> { val userControl = message as UserControl when (val type = userControl.type) { Type.PING_REQUEST -> { commandsManager.sendPong(userControl.event, writer) } else -> { Log.i(TAG, "user control command $type ignored") } } } MessageType.COMMAND_AMF0, MessageType.COMMAND_AMF3 -> { val command = message as Command val commandName = commandsManager.sessionHistory.getName(command.commandId) when (command.name) { "_result" -> { when (commandName) { "connect" -> { if (commandsManager.onAuth) { connectCheckerRtmp.onAuthSuccessRtmp() commandsManager.onAuth = false } commandsManager.createStream(writer) } "createStream" -> { try { commandsManager.streamId = (command.data[3] as AmfNumber).value.toInt() commandsManager.sendPublish(writer) } catch (e: ClassCastException) { Log.e(TAG, "error parsing _result createStream", e) } } } Log.i(TAG, "success response received from ${commandName ?: "unknown command"}") } "_error" -> { try { val description = ((command.data[3] as AmfObject).getProperty("description") as AmfString).value when (commandName) { "connect" -> { if (description.contains("reason=authfail") || description.contains("reason=nosuchuser")) { connectCheckerRtmp.onAuthErrorRtmp() } else if (commandsManager.user != null && commandsManager.password != null && description.contains("challenge=") && description.contains("salt=") //adobe response || description.contains("nonce=")) { //llnw response closeConnection() establishConnection() writer = this.writer ?: throw IOException("Invalid writer, Connection failed") commandsManager.onAuth = true if (description.contains("challenge=") && description.contains("salt=")) { //create adobe auth val salt = AuthUtil.getSalt(description) val challenge = AuthUtil.getChallenge(description) val opaque = AuthUtil.getOpaque(description) commandsManager.sendConnect(AuthUtil.getAdobeAuthUserResult(commandsManager.user ?: "", commandsManager.password ?: "", salt, challenge, opaque), writer) } else if (description.contains("nonce=")) { //create llnw auth val nonce = AuthUtil.getNonce(description) commandsManager.sendConnect(AuthUtil.getLlnwAuthUserResult(commandsManager.user ?: "", commandsManager.password ?: "", nonce, commandsManager.appName), writer) } } else if (description.contains("code=403")) { if (description.contains("authmod=adobe")) { closeConnection() establishConnection() writer = this.writer ?: throw IOException("Invalid writer, Connection failed") Log.i(TAG, "sending auth mode adobe") commandsManager.sendConnect("?authmod=adobe&user=${commandsManager.user}", writer) } else if (description.contains("authmod=llnw")) { Log.i(TAG, "sending auth mode llnw") commandsManager.sendConnect("?authmod=llnw&user=${commandsManager.user}", writer) } } else { connectCheckerRtmp.onAuthErrorRtmp() } } else -> { connectCheckerRtmp.onConnectionFailedRtmp(description) } } } catch (e: ClassCastException) { Log.e(TAG, "error parsing _error command", e) } } "onStatus" -> { try { when (val code = ((command.data[3] as AmfObject).getProperty("code") as AmfString).value) { "NetStream.Publish.Start" -> { commandsManager.sendMetadata(writer) connectCheckerRtmp.onConnectionSuccessRtmp() rtmpSender.output = writer rtmpSender.start() publishPermitted = true } "NetConnection.Connect.Rejected", "NetStream.Publish.BadName" -> { connectCheckerRtmp.onConnectionFailedRtmp("onStatus: $code") } else -> { Log.i(TAG, "onStatus $code response received from ${commandName ?: "unknown command"}") } } } catch (e: ClassCastException) { Log.e(TAG, "error parsing onStatus command", e) } } else -> { Log.i(TAG, "unknown ${command.name} response received from ${commandName ?: "unknown command"}") } } } MessageType.VIDEO, MessageType.AUDIO, MessageType.DATA_AMF0, MessageType.DATA_AMF3, MessageType.SHARED_OBJECT_AMF0, MessageType.SHARED_OBJECT_AMF3 -> { Log.e(TAG, "unimplemented response for ${message.getType()}. Ignored") } } } private fun closeConnection() { connectionSocket?.close() commandsManager.reset() } @JvmOverloads fun reConnect(delay: Long, backupUrl: String? = null) { reTries-- disconnect(false) runnable = Runnable { val reconnectUrl = backupUrl ?: url connect(reconnectUrl, true) } runnable?.let { handler = Executors.newSingleThreadScheduledExecutor() handler?.schedule(it, delay, TimeUnit.MILLISECONDS) } } fun disconnect() { runnable?.let { handler?.shutdownNow() } disconnect(true) } private fun disconnect(clear: Boolean) { if (isStreaming) rtmpSender.stop(clear) thread?.shutdownNow() val executor = Executors.newSingleThreadExecutor() executor.execute post@{ try { writer?.let { writer -> commandsManager.sendClose(writer) } reader?.close() reader = null writer?.close() writer = null closeConnection() } catch (e: IOException) { Log.e(TAG, "disconnect error", e) } } try { executor.shutdownNow() executor.awaitTermination(200, TimeUnit.MILLISECONDS) thread?.awaitTermination(100, TimeUnit.MILLISECONDS) thread = null } catch (e: Exception) { } if (clear) { reTries = numRetry doingRetry = false isStreaming = false connectCheckerRtmp.onDisconnectRtmp() } publishPermitted = false commandsManager.reset() } fun sendVideo(h264Buffer: ByteBuffer, info: MediaCodec.BufferInfo) { if (!commandsManager.videoDisabled) { rtmpSender.sendVideoFrame(h264Buffer, info) } } fun sendAudio(aacBuffer: ByteBuffer, info: MediaCodec.BufferInfo) { if (!commandsManager.audioDisabled) { rtmpSender.sendAudioFrame(aacBuffer, info) } } fun hasCongestion(): Boolean { return rtmpSender.hasCongestion() } fun resetSentAudioFrames() { rtmpSender.resetSentAudioFrames() } fun resetSentVideoFrames() { rtmpSender.resetSentVideoFrames() } fun resetDroppedAudioFrames() { rtmpSender.resetDroppedAudioFrames() } fun resetDroppedVideoFrames() { rtmpSender.resetDroppedVideoFrames() } @Throws(RuntimeException::class) fun resizeCache(newSize: Int) { rtmpSender.resizeCache(newSize) } fun setLogs(enable: Boolean) { rtmpSender.setLogs(enable) } }
apache-2.0
4f14d884126f51a80c6e19efe8e4975e
33.60039
137
0.630796
4.518585
false
false
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/telemetry/TelemetrySettingsProvider.kt
1
3583
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @file:Suppress("DEPRECATION") package org.mozilla.focus.telemetry import android.content.Context import org.mozilla.focus.R import org.mozilla.focus.ext.components import org.mozilla.focus.search.CustomSearchEngineStore import org.mozilla.focus.utils.Browsers import org.mozilla.focus.utils.Settings import org.mozilla.focus.utils.app import org.mozilla.telemetry.TelemetryHolder import org.mozilla.telemetry.measurement.SettingsMeasurement /** * SharedPreferenceSettingsProvider implementation that additionally injects settings value for * runtime preferences like "default browser" and "search engine". */ internal class TelemetrySettingsProvider( private val context: Context ) : SettingsMeasurement.SharedPreferenceSettingsProvider() { private val prefKeyDefaultBrowser: String private val prefKeySearchEngine: String private val prefKeyFretboardBucketNumber: String init { val resources = context.resources prefKeyDefaultBrowser = resources.getString(R.string.pref_key_default_browser) prefKeySearchEngine = resources.getString(R.string.pref_key_search_engine) prefKeyFretboardBucketNumber = resources.getString(R.string.pref_key_fretboard_bucket_number) } override fun containsKey(key: String): Boolean = when (key) { // Not actually a setting - but we want to report this like a setting. prefKeyDefaultBrowser -> true // We always want to report the current search engine - even if it's not in settings yet. prefKeySearchEngine -> true // Not actually a setting - but we want to report this like a setting. prefKeyFretboardBucketNumber -> true else -> super.containsKey(key) } override fun getValue(key: String): Any { return when (key) { prefKeyDefaultBrowser -> { // The default browser is not actually a setting. We determine if we are the // default and then inject this into telemetry. val context = TelemetryHolder.get().configuration.context val browsers = Browsers(context, Browsers.TRADITIONAL_BROWSER_URL) java.lang.Boolean.toString(browsers.isDefaultBrowser(context)) } prefKeySearchEngine -> { var value: Any? = super.getValue(key) if (value == null) { // If the user has never selected a search engine then this value is null. // However we still want to report the current search engine of the user. // Therefore we inject this value at runtime. value = context.components.searchEngineManager.getDefaultSearchEngine( context, Settings.getInstance(context).defaultSearchEngineName ).name } else if (CustomSearchEngineStore.isCustomSearchEngine((value as String?)!!, context)) { // Don't collect possibly sensitive info for custom search engines, send "custom" instead value = CustomSearchEngineStore.ENGINE_TYPE_CUSTOM } value } prefKeyFretboardBucketNumber -> { context.app.fretboard.getUserBucket(context) } else -> super.getValue(key) } } }
mpl-2.0
768a8f324f2ce2732a1b8a0114c4023c
43.234568
109
0.662573
5.00419
false
false
false
false
alpha-cross/ararat
library/src/main/java/org/akop/ararat/util/SparseArray.kt
2
3955
// Copyright (c) Akop Karapetyan // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package org.akop.ararat.util import java.util.Arrays // Not thread-safe! internal class SparseArray<E>(capacity: Int = DEFAULT_CAPACITY) { private var keys = IntArray(capacity) private var values = arrayOfNulls<Any?>(capacity) private var size: Int = 0 @Suppress("UNCHECKED_CAST") operator fun get(key: Int, defaultIfNotFound: E?): E? { val index = Arrays.binarySearch(keys, 0, size, key) return if (index >= 0) { values[index] as E } else defaultIfNotFound } operator fun get(key: Int): E? = get(key, null) operator fun set(key: Int, value: E) { put(key, value) } @Suppress("UNCHECKED_CAST") fun forEach(block: (k: Int, v: E) -> Unit) { (0 until size).forEach { block(keys[it], values[it] as E) } } fun put(key: Int, value: E) { var index = Arrays.binarySearch(keys, 0, size, key) if (index >= 0) { keys[index] = key values[index] = value } else { index = index.inv() if (size >= keys.size) { val newCapacity = size + CAPACITY_INCREMENT val newKeys = IntArray(newCapacity) val newValues = arrayOfNulls<Any>(newCapacity) // Copy head System.arraycopy(keys, 0, newKeys, 0, index) System.arraycopy(values, 0, newValues, 0, index) // Copy tail System.arraycopy(keys, index, newKeys, index + 1, size - index) System.arraycopy(values, index, newValues, index + 1, size - index) keys = newKeys values = newValues } else { for (i in size - 1 downTo index) { keys[i + 1] = keys[i] values[i + 1] = values[i] } } keys[index] = key values[index] = value size++ } } fun clear() { val capacity = keys.size keys = IntArray(capacity) values = arrayOfNulls(capacity) size = 0 } fun size(): Int = size fun capacity(): Int = keys.size fun keyAt(index: Int): Int { if (index < 0 || index >= size) throw ArrayIndexOutOfBoundsException(index) return keys[index] } @Suppress("UNCHECKED_CAST") fun valueAt(index: Int): E { if (index < 0 || index >= size) throw ArrayIndexOutOfBoundsException(index) return values[index] as E } override fun toString(): String = buildString { append("(") (0 until size).forEach { if (it > 0) append(",") append("${keys[it]}=${values[it]}") } append(")") } companion object { const val DEFAULT_CAPACITY = 10 const val CAPACITY_INCREMENT = 16 } }
mit
1e93d10654059e2499398b52486b4ceb
31.958333
83
0.593426
4.312977
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/channels/ChannelRecyclerViewAdapter.kt
1
6969
package org.tvheadend.tvhclient.ui.features.channels import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import org.tvheadend.data.entity.Channel import org.tvheadend.data.entity.Recording import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.ChannelListAdapterBinding import org.tvheadend.tvhclient.ui.common.interfaces.RecyclerViewClickInterface import org.tvheadend.tvhclient.util.extensions.isEqualTo import java.util.* import java.util.concurrent.CopyOnWriteArrayList class ChannelRecyclerViewAdapter internal constructor(private val viewModel: ChannelViewModel, private val isDualPane: Boolean, private val clickCallback: RecyclerViewClickInterface, private val lifecycleOwner: LifecycleOwner) : RecyclerView.Adapter<ChannelRecyclerViewAdapter.ChannelViewHolder>(), Filterable { private val recordingList = ArrayList<Recording>() private val channelList = ArrayList<Channel>() private var channelListFiltered: MutableList<Channel> = ArrayList() private var selectedPosition = 0 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChannelViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val itemBinding = ChannelListAdapterBinding.inflate(layoutInflater, parent, false) val viewHolder = ChannelViewHolder(itemBinding, viewModel, isDualPane) itemBinding.lifecycleOwner = lifecycleOwner return viewHolder } override fun onBindViewHolder(holder: ChannelViewHolder, position: Int) { if (channelListFiltered.size > position) { val channel = channelListFiltered[position] holder.bind(channel, position, selectedPosition == position, clickCallback) } } override fun onBindViewHolder(holder: ChannelViewHolder, position: Int, payloads: List<Any>) { onBindViewHolder(holder, position) } internal fun addItems(newItems: MutableList<Channel>) { updateRecordingState(newItems, recordingList) val oldItems = ArrayList(channelListFiltered) val diffResult = DiffUtil.calculateDiff(ChannelListDiffCallback(oldItems, newItems)) channelList.clear() channelListFiltered.clear() channelList.addAll(newItems) channelListFiltered.addAll(newItems) diffResult.dispatchUpdatesTo(this) if (selectedPosition > channelListFiltered.size) { selectedPosition = 0 } } override fun getItemCount(): Int { return channelListFiltered.size } override fun getItemViewType(position: Int): Int { return R.layout.channel_list_adapter } fun setPosition(pos: Int) { notifyItemChanged(selectedPosition) selectedPosition = pos notifyItemChanged(pos) } fun getItem(position: Int): Channel? { return if (channelListFiltered.size > position && position >= 0) { channelListFiltered[position] } else { null } } override fun getFilter(): Filter { return object : Filter() { override fun performFiltering(charSequence: CharSequence): FilterResults { val charString = charSequence.toString() val filteredList: MutableList<Channel> = ArrayList() if (charString.isNotEmpty()) { for (channel in CopyOnWriteArrayList(channelList)) { val name = channel.name ?: "" when { name.lowercase().contains(charString.lowercase()) -> filteredList.add(channel) } } } else { filteredList.addAll(channelList) } val filterResults = FilterResults() filterResults.values = filteredList return filterResults } override fun publishResults(charSequence: CharSequence, filterResults: FilterResults) { channelListFiltered.clear() @Suppress("UNCHECKED_CAST") channelListFiltered.addAll(filterResults.values as ArrayList<Channel>) notifyDataSetChanged() } } } /** * Whenever a recording changes in the database the list of available recordings are * saved in this recycler view. The previous list is cleared to avoid showing outdated * recording states. Each recording is checked if it belongs to the * currently shown program. If yes then its state is updated. * * @param list List of recordings */ internal fun addRecordings(list: List<Recording>) { recordingList.clear() recordingList.addAll(list) updateRecordingState(channelListFiltered, recordingList) } private fun updateRecordingState(channels: MutableList<Channel>, recordings: List<Recording>) { for (i in channels.indices) { val channel = channels[i] var recordingExists = false for (recording in recordings) { if (channel.programId > 0 && channel.programId == recording.eventId) { val oldRecording = channel.recording channel.recording = recording // Do a full update only when a new recording was added or the recording // state has changed which results in a different recording state icon // Otherwise do not update the UI if (oldRecording == null || !oldRecording.error.isEqualTo(recording.error) || !oldRecording.state.isEqualTo(recording.state)) { notifyItemChanged(i) } recordingExists = true break } } if (!recordingExists && channel.recording != null) { channel.recording = null notifyItemChanged(i) } channels[i] = channel } } class ChannelViewHolder(private val binding: ChannelListAdapterBinding, private val viewModel: ChannelViewModel, private val isDualPane: Boolean) : RecyclerView.ViewHolder(binding.root) { fun bind(channel: Channel, position: Int, isSelected: Boolean, clickCallback: RecyclerViewClickInterface) { binding.channel = channel binding.position = position binding.isSelected = isSelected binding.viewModel = viewModel binding.isDualPane = isDualPane binding.callback = clickCallback binding.executePendingBindings() } } }
gpl-3.0
58d3811b9376dd2c81bf2c8f2ab890e7
39.517442
311
0.643277
5.60209
false
false
false
false
PaulYerger/nbrb-listener
src/main/java/com/paulyerger/nbrb/listener/NbrbCheck.kt
1
1834
package com.paulyerger.nbrb.listener import java.time.LocalDate import java.time.LocalDateTime import java.time.format.DateTimeFormatter /** * Created by Pavel on 03.08.2015. */ public class NbrbCheck(vararg listeners: (info: RatesInfo) -> Unit) { private final val ratesDateFormat = DateTimeFormatter.ofPattern("dd.MM.yy") private final val lastUpdateDateFormat = DateTimeFormatter.ofPattern("HH:mm:ss dd.MM.yy") private var dateOfCurrentRate: LocalDate? = null private val changeRateListeners: List<(info: RatesInfo) -> Unit> init { changeRateListeners = listeners.toList() } public fun check(): LocalDate { val curState = NbrbPageState() // update if empty state or state was changed if (dateOfCurrentRate == null || (dateOfCurrentRate?.equals(curState.getCurrentDate()) == false)) { val difEUR = curState.getCurrentRateOfEUR() - curState.getPreviousRateOfEUR() val difUSD = curState.getCurrentRateOfUSD() - curState.getPreviousRateOfUSD() val difRUB = curState.getCurrentRateOfRUB() - curState.getPreviousRateOfRUB() val ratesInfo = RatesInfo(LocalDateTime.now().format(lastUpdateDateFormat), curState.getCurrentDate().format(ratesDateFormat), curState.getPreviousDate().format(ratesDateFormat), curState.getPreviousRateOfEUR(), curState.getPreviousRateOfUSD(), curState.getPreviousRateOfRUB(), curState.getCurrentRateOfEUR(), curState.getCurrentRateOfUSD(), curState.getCurrentRateOfRUB(), difEUR, difUSD, difRUB) // notify listeners changeRateListeners forEach { l -> l(ratesInfo) } dateOfCurrentRate = curState.getCurrentDate() } return curState.getCurrentDate() } }
apache-2.0
e1c258eece132420bc25679bf0b841e4
36.44898
122
0.685387
4.495098
false
false
false
false
mockk/mockk
modules/mockk-agent-api/src/jvmMain/kotlin/io/mockk/proxy/common/CancelableResult.kt
2
757
package io.mockk.proxy.common import io.mockk.proxy.Cancelable import io.mockk.proxy.MockKAgentException import java.util.concurrent.atomic.AtomicBoolean open class CancelableResult<T : Any>( private val value: T? = null, private val cancelBlock: () -> Unit = {} ) : Cancelable<T> { val fired = AtomicBoolean() override fun get() = value ?: throw MockKAgentException("Value for this result is not assigned") override fun cancel() { if (!fired.getAndSet(true)) { cancelBlock() } } fun <R : Any> withValue(value: R) = CancelableResult(value, cancelBlock) fun alsoOnCancel(block: () -> Unit) = CancelableResult(value) { cancel() block() } }
apache-2.0
e6a22b204aac28d61654733f29e9220e
24.233333
81
0.622193
4.159341
false
false
false
false
thatJavaNerd/JRAW
lib/src/test/kotlin/net/dean/jraw/test/integration/CommentNodeTest.kt
2
8737
package net.dean.jraw.test.integration import com.winterbe.expekt.should import net.dean.jraw.models.Comment import net.dean.jraw.models.MoreChildren import net.dean.jraw.models.Submission import net.dean.jraw.test.NoopNetworkAdapter import net.dean.jraw.test.TestConfig.reddit import net.dean.jraw.test.expectException import net.dean.jraw.test.newMockRedditClient import net.dean.jraw.tree.* import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it class CommentNodeTest : Spek({ val SUBMISSION_ID = "2zsyu4" val root: RootCommentNode by lazy { reddit.submission(SUBMISSION_ID).comments() } val a: CommentNode<Comment> by lazy { root.replies[0] } // reddit.com/comments/6t8ioo val complexTree: RootCommentNode by lazy { reddit.submission("92dd8").comments() } // reddit.com/comments/2onit4 val simpleTree: RootCommentNode by lazy { reddit.submission("2onit4").comments() } /* All tests are based on submission 2zsyu4 that has a comment structure like this: a / | \ b c d /|\ \ f g h i See reddit.com/comments/2zsyu4 for the actual Submission */ it("should have a submission with the same ID") { root.subject.id.should.equal(SUBMISSION_ID) root.depth.should.equal(0) // Only one top level reply root.replies.should.have.size(1) root.hasMoreChildren().should.be.`false` // Top level replies a.depth.should.equal(1) a.replies.should.have.size(3) // Depth-2 replies val b = a.replies[0] b.depth.should.equal(2) b.replies.should.have.size(0) val c = a.replies[1] c.depth.should.equal(2) c.replies.should.have.size(3) val d = a.replies[2] d.depth.should.equal(2) d.replies.should.have.size(1) // Depth-3 replies, only test the first one since the rest are similar (no children) val f = c.replies[0] f.depth.should.equal(3) f.replies.should.have.size(0) } fun <T> Iterator<T>.toList(): List<T> { val values: MutableList<T> = ArrayList() while (this.hasNext()) values.add(this.next()) return values } fun <T : CommentNode<*>> List<T>.mapToBody() = map { it.subject.body } fun <T : CommentNode<*>> Sequence<T>.mapToBody() = map { it.subject.body }.toList() fun MoreChildren.copy(): MoreChildren = MoreChildren.create(fullName, id, parentFullName, childrenIds) it("should provide an Iterator that iterates over direct children") { a.iterator() .toList() .mapToBody() .should.equal(listOf("b", "c", "d")) } describe("walkTree") { it("should correctly iterate pre-order") { a.walkTree(TreeTraversalOrder.PRE_ORDER) .mapToBody() .should.equal("a b c f g h d i".split(" ")) } it("should correctly iterate post-order") { a.walkTree(TreeTraversalOrder.POST_ORDER) .mapToBody() .should.equal("b f g h c i d a".split(" ")) } it("should correctly iterate breadth-first") { a.walkTree(TreeTraversalOrder.BREADTH_FIRST) .mapToBody() .should.equal("a b c d f g h i".split(" ")) } it("should default to pre-order") { a.walkTree().mapToBody().should.equal(a.walkTree(TreeTraversalOrder.PRE_ORDER).mapToBody()) } } describe("visualize") { it("shouldn't throw an Exception") { a.visualize() } } describe("totalSize") { it("should calculate the correct size of the node's children") { root.totalSize().should.equal(8) a.totalSize().should.equal(7) // Node 'b' is a leaf a.replies[0].totalSize().should.equal(0) } } describe("loadMore") { it("should throw an Exception when MoreChildren is null") { simpleTree.moreChildren.should.be.`null` expectException(IllegalStateException::class) { // Make sure we aren't executing any network requests val mockReddit = newMockRedditClient(NoopNetworkAdapter) simpleTree.loadMore(mockReddit) } } it("should return a new root instead of altering the tree") { // Highly unusual to see a popular post without a root MoreChildren complexTree.moreChildren.should.not.be.`null` val originalMore = complexTree.moreChildren!!.copy() var prevCount = complexTree.moreChildren!!.childrenIds.size prevCount.should.be.above(0) var fakeRoot: CommentNode<Submission> = complexTree // Make sure that calling RootCommentNode.loadMore() works exactly the same as calling // FakeRootCommentNode.loadMore() for (i in 0..2) { // This thread has 2000+ comments, we should be able to do a few rounds of this no problem fakeRoot.hasMoreChildren().should.be.`true` // go deeper... fakeRoot = fakeRoot.loadMore(reddit) // Make sure the original tree's MoreChildren wasn't altered complexTree.moreChildren.should.equal(originalMore) // The new root MoreChildren should contain fewer children IDs than it did previously fakeRoot.moreChildren!!.childrenIds.should.have.size.below(prevCount) // Make sure the new root MoreChildren has the same parent ID fakeRoot.moreChildren!!.parentFullName.should.equal(originalMore.parentFullName) // We should only be requesting a certain amount of children, and therefore be receiving up to a certain // amount of children. The reason we don't assert an exact number is that reddit may only return 97 // objects if we request 100 for whatever reason fakeRoot.replies.should.have.size.at.most(AbstractCommentNode.MORE_CHILDREN_LIMIT) prevCount = fakeRoot.moreChildren!!.childrenIds.size } } it("should handle thread continuations") { val threadContinuation = simpleTree.walkTree().first { it.hasMoreChildren() && it.moreChildren!!.isThreadContinuation } val parentDepth = threadContinuation.depth val fakeRoot = threadContinuation.loadMore(reddit) val flatTree = fakeRoot.walkTree() // The first element in the flat tree should represent the original comment flatTree.first().subject.fullName.should.equal(threadContinuation.subject.fullName) flatTree.first().depth.should.equal(threadContinuation.depth) // All nodes after the first should be children (directly or indirectly) for (node in flatTree.drop(1)) { node.depth.should.be.above(parentDepth) } } } describe("replaceMore") { it("should do nothing when MoreChildren is null") { simpleTree.moreChildren.should.be.`null` val original = simpleTree.walkTree().toList() // Use a mock RedditClient so we can assert no network requests are sent val fakeReddit = newMockRedditClient(NoopNetworkAdapter) simpleTree.replaceMore(fakeReddit) simpleTree.walkTree().toList().should.equal(original) } it("should alter the tree when called") { val tree = reddit.submission("92dd8").comments() val prevFlatTree = tree.walkTree().toList() // Create a copy of the data val prevMoreChildren = tree.moreChildren!!.copy() val prevSize = tree.totalSize() val newDirectChildren = tree.replaceMore(reddit) tree.moreChildren!!.parentFullName.should.equal(prevMoreChildren.parentFullName) // Make sure we've taken IDs out of the MoreChildren and added them to the tree tree.moreChildren!!.childrenIds.should.have.size.below(prevMoreChildren.childrenIds.size) tree.totalSize().should.be.above(prevSize) for (directChild in newDirectChildren) { // Make sure each reportedly new direct children are in fact: // (1) direct children and directChild.subject.parentFullName.should.equal(tree.subject.fullName) // (2) new children prevFlatTree.find { it.subject.fullName == directChild.subject.fullName }.should.be.`null` } } } })
mit
5b4adc2d41381c268871312417d3cd81
38.004464
131
0.61932
4.266113
false
false
false
false
dewarder/Android-Kotlin-Commons
akommons/src/main/java/com/dewarder/akommons/support/app/Fragment.kt
1
3015
/* * Copyright (C) 2017 Artem Hluhovskyi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ @file:[JvmName("SupportFragmentUtils") Suppress("unused")] package com.dewarder.akommons.support.app import android.app.Activity import android.app.Service import android.content.ComponentName import android.content.Intent import android.support.annotation.IdRes import android.support.annotation.StringRes import android.support.v4.app.Fragment import android.view.View import com.dewarder.akommons.content.* import com.dewarder.akommons.view.findView inline fun <V : View> Fragment.findView( @IdRes id: Int, init: V.() -> Unit ): V = view!!.findView(id, init) /** * Intents */ inline fun <reified T : Any> Fragment.intentFor( action: String? = null, flags: Int = -1 ): Intent = context.intentFor<T>(action, flags) inline fun <reified T : Any> Fragment.intentFor( action: String? = null, flags: Int = -1, init: Intent.() -> Unit ): Intent = intentFor<T>(action, flags).apply(init) inline fun <reified T : Activity> Fragment.startActivity( action: String? = null, flags: Int = -1 ) = startActivity(intentFor<T>(action, flags)) inline fun <reified T : Activity> Fragment.startActivity( action: String? = null, flags: Int = -1, init: Intent.() -> Unit ) = startActivity(intentFor<T>(action, flags).apply(init)) inline fun <reified T : Service> Fragment.startService( action: String? = null ): ComponentName = context.startService(intentFor<T>(action)) inline fun <reified T : Service> Fragment.startService( action: String? = null, init: Intent.() -> Unit ): ComponentName = context.startService(intentFor<T>(action = action, init = init)) /** * Toasts */ fun Fragment.showShortToast(@StringRes resId: Int) { context.showShortToast(resId) } fun Fragment.showShortToast(text: String) { context.showShortToast(text) } fun Fragment.showLongToast(@StringRes resId: Int) { context.showLongToast(resId) } fun Fragment.showLongToast(text: String) { context.showLongToast(text) } /** * Permissions */ fun Fragment.isPermissionsGranted(vararg permissions: Permission): Boolean = context.isPermissionsGranted(*permissions) fun Fragment.isPermissionsGranted(vararg permissions: String): Boolean = context.isPermissionsGranted(*permissions) fun Fragment.requestPermissions(requestCode: Int, vararg permissions: Permission) { requestPermissions(permissions.map(Permission::value).toTypedArray(), requestCode) }
apache-2.0
1b05683b856e24ac21a41aa4f009417f
28.281553
86
0.729685
3.941176
false
false
false
false
cashapp/sqldelight
sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/lang/SqlDelightCommenter.kt
1
1692
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.cash.sqldelight.intellij.lang import com.alecstrong.sql.psi.core.psi.SqlTypes import com.intellij.lang.CodeDocumentationAwareCommenter import com.intellij.psi.PsiComment import com.intellij.psi.tree.IElementType class SqlDelightCommenter : CodeDocumentationAwareCommenter { override fun getLineCommentTokenType(): IElementType = SqlTypes.COMMENT override fun getLineCommentPrefix() = "-- " override fun getBlockCommentTokenType(): IElementType? = null override fun getBlockCommentPrefix(): String? = null override fun getBlockCommentSuffix(): String? = null override fun getDocumentationCommentTokenType(): IElementType = SqlTypes.JAVADOC override fun isDocumentationComment(psiComment: PsiComment?) = psiComment?.tokenType == documentationCommentTokenType override fun getDocumentationCommentPrefix() = "/**" override fun getDocumentationCommentLinePrefix() = "*" override fun getDocumentationCommentSuffix() = "*/" override fun getCommentedBlockCommentPrefix(): String? = null override fun getCommentedBlockCommentSuffix(): String? = null }
apache-2.0
1232812169c72e95084b5b0d2f03be02
38.348837
82
0.775414
4.793201
false
false
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/recorder/metadata/sensor/MetadataSensorCollecting.kt
1
1440
package com.telenav.osv.recorder.metadata.sensor import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager /** * Class responsible of collecting sensor related to metadata. * * This will collect the data related to pressure sensor. */ class MetadataSensorCollecting : SensorEventListener{ private var sensorManager: SensorManager? = null private var isSensorRegistered = false; fun registerPressureListener(context: Context) { if (!isSensorRegistered) { sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager var pressureSensor: Sensor? = null if (sensorManager != null) { pressureSensor = sensorManager!!.getDefaultSensor(Sensor.TYPE_PRESSURE) } if (pressureSensor != null) { //sensorManager!!.registerListener(this, pressureSensor, frequency, notifyHandler) isSensorRegistered = true } else { //sendSensorUnavailabilityStatus(PressureObject(LibraryUtil.PHONE_SENSOR_NOT_AVAILABLE)) } } } data class PressureData(val timestamp: Long, val pressure: Float) override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { } override fun onSensorChanged(event: SensorEvent?) { } }
lgpl-3.0
5b585eda18bc63bedd4928bbec2249ae
31.75
104
0.692361
5.142857
false
false
false
false
shlusiak/Freebloks-Android
themes/src/main/java/de/saschahlusiak/freebloks/theme/ColorTheme.kt
1
1005
package de.saschahlusiak.freebloks.theme import android.content.res.Resources import android.graphics.Color import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.StringRes /** * Simple plain color theme, either defined via a color resource or a color value * * @param name unique key for this theme * @param label the label string resource id * @param colorRes color resource, or 0 * @param color color value, if [colorRes] is 0 */ class ColorTheme(override val name: String, @StringRes label: Int, @ColorRes val colorRes: Int = 0, @ColorInt val color: Int = 0) : BaseTheme(label = label) { constructor(name: String, @StringRes label: Int, r: Int, g: Int, b: Int): this( name = name, label = label, color = Color.rgb(r, g, b) ) override fun getColor(resources: Resources): Int { return if (colorRes != 0) { resources.getColor(colorRes) } else { color } } }
gpl-2.0
7e74a71caacc1d38ff98398db04bcaab
29.454545
129
0.671642
4.02
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/page/edithistory/EditHistoryItemView.kt
1
6710
package org.wikipedia.page.edithistory import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.graphics.Typeface import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.core.content.ContextCompat import androidx.core.graphics.ColorUtils import androidx.core.view.isVisible import androidx.core.widget.ImageViewCompat import org.wikipedia.R import org.wikipedia.databinding.ItemEditHistoryBinding import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.util.DateUtil import org.wikipedia.util.ResourceUtil import org.wikipedia.util.StringUtil class EditHistoryItemView(context: Context) : FrameLayout(context) { interface Listener { fun onClick() fun onLongClick() fun onUserNameClick(v: View) fun onToggleSelect() } var listener: Listener? = null private val binding = ItemEditHistoryBinding.inflate(LayoutInflater.from(context), this, true) init { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) binding.clickTargetView.setOnClickListener { listener?.onClick() } binding.clickTargetView.setOnLongClickListener { listener?.onLongClick() true } binding.selectButton.setOnClickListener { listener?.onToggleSelect() } binding.userNameText.setOnClickListener { listener?.onUserNameClick(it) } } fun setContents(itemRevision: MwQueryPage.Revision, currentQuery: String?) { val diffSize = itemRevision.diffSize binding.diffText.text = StringUtil.getDiffBytesText(context, diffSize) if (diffSize >= 0) { binding.diffText.setTextColor(if (diffSize > 0) ContextCompat.getColor(context, R.color.green50) else ResourceUtil.getThemedColor(context, R.attr.material_theme_secondary_color)) } else { binding.diffText.setTextColor(ContextCompat.getColor(context, R.color.red50)) } val userIcon = if (itemRevision.isAnon) R.drawable.ic_anonymous_ooui else R.drawable.ic_user_avatar binding.userNameText.setIconResource(userIcon) if (itemRevision.comment.isEmpty()) { binding.editHistoryTitle.setTypeface(Typeface.SANS_SERIF, Typeface.ITALIC) binding.editHistoryTitle.setTextColor(ResourceUtil.getThemedColor(context, R.attr.material_theme_secondary_color)) binding.editHistoryTitle.text = context.getString(R.string.page_edit_history_comment_placeholder) } else { binding.editHistoryTitle.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL) binding.editHistoryTitle.setTextColor(ResourceUtil.getThemedColor(context, R.attr.material_theme_primary_color)) binding.editHistoryTitle.text = if (itemRevision.minor) StringUtil.fromHtml(context.getString(R.string.page_edit_history_minor_edit, itemRevision.comment)) else itemRevision.comment StringUtil.highlightAndBoldenText(binding.editHistoryTitle, currentQuery, true, Color.YELLOW) } binding.userNameText.text = itemRevision.user binding.editHistoryTimeText.text = DateUtil.getTimeString(context, DateUtil.iso8601DateParse(itemRevision.timeStamp)) StringUtil.highlightAndBoldenText(binding.diffText, currentQuery, true, Color.YELLOW) StringUtil.highlightAndBoldenText(binding.userNameText, currentQuery, true, Color.YELLOW) } fun setSelectedState(selectedState: Int) { val colorDefault = ResourceUtil.getThemedColor(context, R.attr.paper_color) val colorSecondary = ResourceUtil.getThemedColorStateList(context, R.attr.material_theme_secondary_color) val colorUsername = ResourceUtil.getThemedColorStateList(context, R.attr.color_group_9) val colorFrom = ResourceUtil.getThemedColor(context, R.attr.colorAccent) val colorTo = ResourceUtil.getThemedColor(context, R.attr.color_group_68) binding.selectButton.isVisible = selectedState != EditHistoryListViewModel.SELECT_INACTIVE if (selectedState == EditHistoryListViewModel.SELECT_INACTIVE || selectedState == EditHistoryListViewModel.SELECT_NONE) { binding.selectButton.setImageResource(R.drawable.ic_check_empty_24) ImageViewCompat.setImageTintList(binding.selectButton, colorSecondary) binding.cardView.setDefaultBorder() binding.cardView.setCardBackgroundColor(colorDefault) binding.userNameText.backgroundTintList = ResourceUtil.getThemedColorStateList(context, R.attr.color_group_22) binding.userNameText.setTextColor(colorUsername) binding.userNameText.iconTint = colorUsername binding.editHistoryTimeText.setTextColor(colorSecondary) } else if (selectedState == EditHistoryListViewModel.SELECT_FROM) { binding.selectButton.setImageResource(R.drawable.ic_check_circle_black_24dp) ImageViewCompat.setImageTintList(binding.selectButton, ColorStateList.valueOf(colorFrom)) binding.cardView.strokeColor = colorFrom val cardBackground = ColorUtils.blendARGB(colorDefault, colorFrom, 0.05f) binding.cardView.setCardBackgroundColor(cardBackground) val buttonBackground = ColorUtils.blendARGB(cardBackground, colorFrom, 0.05f) binding.userNameText.backgroundTintList = ColorStateList.valueOf(buttonBackground) binding.userNameText.setTextColor(colorFrom) binding.userNameText.iconTint = ColorStateList.valueOf(colorFrom) binding.editHistoryTimeText.setTextColor(colorFrom) } else if (selectedState == EditHistoryListViewModel.SELECT_TO) { binding.selectButton.setImageResource(R.drawable.ic_check_circle_black_24dp) ImageViewCompat.setImageTintList(binding.selectButton, ColorStateList.valueOf(colorTo)) binding.cardView.strokeColor = ContextCompat.getColor(context, R.color.osage) val cardBackground = ColorUtils.blendARGB(colorDefault, colorTo, 0.05f) binding.cardView.setCardBackgroundColor(cardBackground) val buttonBackground = ColorUtils.blendARGB(cardBackground, colorTo, 0.05f) binding.userNameText.backgroundTintList = ColorStateList.valueOf(buttonBackground) binding.userNameText.setTextColor(colorTo) binding.userNameText.iconTint = ColorStateList.valueOf(colorTo) binding.editHistoryTimeText.setTextColor(colorTo) } } }
apache-2.0
74afba19b94071a61aecfbc51caff863
54.916667
193
0.737109
4.685754
false
false
false
false
alexcustos/linkasanote
app/src/main/java/com/bytesforge/linkasanote/about/AboutFragment.kt
1
9896
/* * LaaNo Android application * * @author Aleksandr Borisenko <[email protected]> * Copyright (C) 2017 Aleksandr Borisenko * * 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.bytesforge.linkasanote.about import android.app.AlertDialog import android.app.Dialog import android.content.ActivityNotFoundException import android.content.ComponentName import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.text.Spanned import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import com.bytesforge.linkasanote.BuildConfig import com.bytesforge.linkasanote.LaanoApplication import com.bytesforge.linkasanote.R import com.bytesforge.linkasanote.databinding.DialogAboutLicenseTermsBinding import com.bytesforge.linkasanote.databinding.FragmentAboutBinding import com.bytesforge.linkasanote.utils.ActivityUtils import com.bytesforge.linkasanote.utils.CommonUtils import com.bytesforge.linkasanote.utils.schedulers.BaseSchedulerProvider import com.google.common.base.Charsets import io.reactivex.Single import io.reactivex.disposables.CompositeDisposable import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import javax.inject.Inject class AboutFragment : Fragment(), AboutContract.View { private var presenter: AboutContract.Presenter? = null private var viewModel: AboutContract.ViewModel? = null override fun onResume() { super.onResume() presenter!!.subscribe() } override fun onPause() { super.onPause() presenter!!.unsubscribe() compositeDisposable.clear() } override val isActive: Boolean get() = isAdded override fun setPresenter(presenter: AboutContract.Presenter) { this.presenter = presenter } override fun setViewModel(viewModel: AboutContract.ViewModel) { this.viewModel = viewModel } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentAboutBinding.inflate(inflater, container, false) viewModel!!.setInstanceState(savedInstanceState) binding.presenter = presenter binding.viewModel = viewModel as AboutViewModel? return binding.root } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) viewModel!!.saveInstanceState(outState) } private fun getMarketIntent(): Intent? { val intent = requireContext().packageManager .getLaunchIntentForPackage(GOOGLE_PLAY_PACKAGE_NAME) ?: return null val androidComponent = ComponentName( GOOGLE_PLAY_PACKAGE_NAME, //"com.google.android.finsky.activities.LaunchUrlHandlerActivity" "com.google.android.finsky.activities.MarketDeepLinkHandlerActivity" ) intent.component = androidComponent val marketUriBuilder = Uri.parse(resources.getString(R.string.google_market)) .buildUpon() .appendQueryParameter("id", BuildConfig.APPLICATION_ID) intent.data = marketUriBuilder.build() //intent.setPackage(GOOGLE_PLAY_PACKAGE_NAME) return intent } private fun findMarketIntent(): Intent? { val marketUriBuilder = Uri.parse(resources.getString(R.string.google_market)) .buildUpon() .appendQueryParameter("id", BuildConfig.APPLICATION_ID) val intent = Intent(Intent.ACTION_VIEW, marketUriBuilder.build()) val apps = requireContext().packageManager.queryIntentActivities(intent, 0) for (app in apps) { if (app.activityInfo.applicationInfo.packageName == GOOGLE_PLAY_PACKAGE_NAME) { val activityInfo = app.activityInfo val componentName = ComponentName( activityInfo.applicationInfo.packageName, activityInfo.name ) var flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NEW_TASK flags = if (Build.VERSION.SDK_INT >= 21) { flags or Intent.FLAG_ACTIVITY_NEW_DOCUMENT } else { flags or Intent.FLAG_ACTIVITY_CLEAR_TASK } intent.addFlags(flags) //intent.addFlags( // Intent.FLAG_ACTIVITY_NEW_TASK // or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED // or Intent.FLAG_ACTIVITY_CLEAR_TOP //) intent.component = componentName //intent.setPackage(GOOGLE_PLAY_PACKAGE_NAME) return intent } } return null } override fun showGooglePlay() { var intent = findMarketIntent() ?: getMarketIntent() if (intent == null) { val webUriBuilder = Uri.parse(resources.getString(R.string.google_play)) .buildUpon() .appendQueryParameter("id", BuildConfig.APPLICATION_ID) intent = Intent(Intent.ACTION_VIEW, webUriBuilder.build()) } try { startActivity(intent) } catch (e: ActivityNotFoundException) { viewModel!!.showLaunchGooglePlayErrorSnackbar() } } override fun showLicenseTermsAlertDialog(licenseText: String) { val dialog = LicenseTermsDialog.newInstance(licenseText) dialog.show(parentFragmentManager, LicenseTermsDialog.DIALOG_TAG) } class LicenseTermsDialog : DialogFragment() { var binding: DialogAboutLicenseTermsBinding? = null private var licenseAsset: String? = null @JvmField @Inject var schedulerProvider: BaseSchedulerProvider? = null override fun onStart() { super.onStart() binding!!.licenseTerms.movementMethod = LinkMovementMethod.getInstance() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) licenseAsset = requireArguments().getString(ARGUMENT_LICENSE_ASSET) val application = requireActivity().application as LaanoApplication application.applicationComponent.inject(this) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val inflater = LayoutInflater.from(context) binding = DialogAboutLicenseTermsBinding.inflate(inflater, null, false) compositeDisposable.clear() val disposable = Single.fromCallable { getLicenseText( licenseAsset!! ) } .subscribeOn(schedulerProvider!!.computation()) .map { source: String? -> ActivityUtils.fromHtmlCompat(source!!) } .observeOn(schedulerProvider!!.ui()) .subscribe( { text: Spanned? -> binding!!.licenseTerms.text = text } ) { throwable: Throwable? -> CommonUtils.logStackTrace(TAG_E!!, throwable!!) } compositeDisposable.add(disposable) return AlertDialog.Builder(context) .setView(binding!!.root) .setPositiveButton(resources.getString(R.string.dialog_button_ok), null) .create() } private fun getLicenseText(assetName: String): String { val resources = requireContext().resources var licenseText: String try { var line: String? val builder = StringBuilder() val stream = resources.assets.open(assetName) val `in` = BufferedReader(InputStreamReader(stream, Charsets.UTF_8)) while (`in`.readLine().also { line = it } != null) { builder.append(line) builder.append('\n') } `in`.close() licenseText = builder.toString() } catch (e: IOException) { licenseText = resources.getString(R.string.about_fragment_error_license, assetName) } return licenseText } companion object { private const val ARGUMENT_LICENSE_ASSET = "LICENSE_ASSET" const val DIALOG_TAG = "LICENSE_TERMS" fun newInstance(licenseAsset: String?): LicenseTermsDialog { val args = Bundle() args.putString(ARGUMENT_LICENSE_ASSET, licenseAsset) val dialog = LicenseTermsDialog() dialog.arguments = args return dialog } } } companion object { private val TAG = AboutFragment::class.java.simpleName private val TAG_E = AboutFragment::class.java.canonicalName private const val GOOGLE_PLAY_PACKAGE_NAME = "com.android.vending" private val compositeDisposable: CompositeDisposable = CompositeDisposable() fun newInstance(): AboutFragment { return AboutFragment() } } }
gpl-3.0
c87ac5294b4497fd084202a4b2165682
37.964567
99
0.648646
5.162233
false
false
false
false
vimeo/vimeo-networking-java
model-generator/plugin/src/main/java/com/vimeo/modelgenerator/PsiToPoetHelpers.kt
1
9819
package com.vimeo.modelgenerator import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.vimeo.modelgenerator.extensions.* import com.vimeo.modelgenerator.visitor.ParcelableClassVisitor import org.gradle.api.GradleException import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.types.Variance private const val NULLABLE = '?' private const val STARTING_BRACKET = '<' private const val ENDING_BRACKET = '>' private const val COMMA = ',' private const val IN_VARIANCE = "in" private const val OUT_VARIANCE = "out" private const val STAR_PROJECTION = "*" private const val LAMBDA = "->" /** * Creates a list of annotations using [AnnotationSpec] for a kt prefixed object, * like [KtProperty] or [KtNamedFunction]. * * @param annotations a list of [KtAnnotationEntry] that can be pulled from most Kt * prefixed objects, like [KtParameter] or [KtClass]. * @param packageName the current package name of the worked on file. */ internal fun createAnnotations( annotations: List<KtAnnotationEntry>, packageName: String ): List<AnnotationSpec> = annotations.map { AnnotationSpec.builder( ClassName( packageName, it.shortName?.asString() ?: throw GradleException("Annotation name cannot be null.") ) ) .addMembers(it.valueArguments) .build() } /** * Creates a list of [TypeNames][TypeName] to be used as supers for a given class or interface. * * @param supers a list of [KtSuperTypeListEntry] that correspond to the given classes super classes. * @param packageName the current package name of the worked on file. */ internal fun createSuperTypes( supers: List<KtSuperTypeListEntry>, packageName: String ): List<TypeName> = supers .map { superType -> val type = superType.typeAsUserType ?: throw GradleException("Type cannot be null.") // If supertype is parameterized the type arguments would contain the parameters // Otherwise if no type arguments just return a regular supertype. if (type.typeArguments.isNotEmpty()) { ClassName( packageName, type.referenceExpression?.text.orEmpty() ).parameterizedBy(type.typeArguments.map { superTypeParam -> ClassName( packageName, superTypeParam.text ?: throw GradleException("$superTypeParam simpleName can't be empty") ) }) } else { ClassName( packageName, type.referenceExpression?.text ?: throw GradleException("$superType: simpleName can't be empty") ) } } /** * Creates a list of [TypeVariableNames][TypeVariableName] that can be used for Typed classes or functions. * * @param types a list of [KtTypeParameter] that will be used to type a class or function. * @param packageName the current package name of the worked on file. * @param constraints a list of [KtTypeConstraints][KtTypeConstraint] that the given [TypeVariableName] * will need to conform to, defaults to an empty list. * @param isInline a [Boolean] to denote if this is for a inline function, if so the [TypeVariableName] * will also be reified, defaults to false. * @param isParcelable a [Boolean] that denotes if the class using this method needs to be [android.os.Parcelable], defaults to false. */ internal fun createTypeVariables( types: List<KtTypeParameter>, packageName: String, constraints: List<KtTypeConstraint> = emptyList(), isInline: Boolean = false, isParcelable: Boolean = false ): List<TypeVariableName> = types.map { typeParam -> TypeVariableName( typeParam.name ?: throw GradleException("$typeParam: name can't be null"), bounds = constraints.map { typeConstraint -> createTypeName( typeConstraint.boundTypeReference, packageName ) }.toMutableList().apply { if (isParcelable) { this.add(ParcelableClassVisitor.PARCELABLE) } }, variance = when (typeParam.variance) { Variance.IN_VARIANCE -> KModifier.IN Variance.OUT_VARIANCE -> KModifier.OUT else -> null } ) .copy(reified = isInline) } /** * Creates a list of [ParameterSpec] that can be used. * * @param params a list of [KtParameters][KtParameter] that correspond to a constructor params for a class. * @param packageName the current package name of the worked on file. */ internal fun createConstructorParams( params: List<KtParameter>, packageName: String ): List<ParameterSpec> = params .map { ParameterSpec.builder( it.validateName, createTypeName(it.typeReference, packageName) ) .addIfConditionMet(it.modifierList?.isOverridden == true) { addModifiers(KModifier.OVERRIDE) } .addIfConditionMet(it.defaultValue != null) { defaultValue("%L", it.defaultValue?.text) } .addKdoc(it.docComment?.getDefaultSection()?.getContent().orEmpty()) .addAnnotations( createAnnotations( it.annotationEntries, packageName ) ) .addIfConditionMet(it.visibilityModifier != null) { addModifiers(it.visibilityModifier!!) } .build() } /** * Creates a [TypeName] that can be used to denote types for constructor params, class properties, * and function params and return types. * * @param type a [KtTypeReference] for the current type. * @param packageName the current package name of the worked on file. */ internal fun createTypeName( type: KtTypeReference?, packageName: String ): TypeName { if (type == null) { throw GradleException("TypeReference cannot be null.") } // Type is a lambda if (type.text.contains(LAMBDA)) { val functionType = type.children.find { it is KtFunctionType } as KtFunctionType val receiverType = if (functionType.receiverTypeReference != null) { createTypeName( functionType.receiverTypeReference, packageName ) } else { null } return LambdaTypeName.get( receiver = receiverType, parameters = createConstructorParams(functionType.parameters, packageName), returnType = createTypeName(functionType.returnTypeReference, packageName) ) } val nonNullName = type.text.removeSuffix(NULLABLE.toString()) val isOuterMostTypeNullable = type.text.last() == NULLABLE val parametersString = nonNullName.substringAfter(STARTING_BRACKET).substringBeforeLast(ENDING_BRACKET) val outerMostType = nonNullName.substringBefore(STARTING_BRACKET) // Regular type with no parameters if (!nonNullName.contains(STARTING_BRACKET) && !nonNullName.contains(ENDING_BRACKET)) { return ClassName( packageName, nonNullName ).copy(nullable = isOuterMostTypeNullable) } // Types like that take multiple parameters, like Map<String, String> or Foo<Bar, Baz>. if (parametersString.contains(COMMA)) { val params = parametersString.split(COMMA) .map { it.trim() } .map { when { it.contains(OUT_VARIANCE) -> { val sanitizedName = it.removePrefix(OUT_VARIANCE).trim() WildcardTypeName.producerOf( ClassName(packageName, sanitizedName) .copy(nullable = sanitizedName.contains(NULLABLE)) ) } it.contains(IN_VARIANCE) -> { val sanitizedName = it.removePrefix(IN_VARIANCE).trim() WildcardTypeName.consumerOf( ClassName(packageName, sanitizedName) .copy(nullable = sanitizedName.contains(NULLABLE)) ) } it == STAR_PROJECTION -> STAR else -> ClassName(packageName, it) .copy(nullable = it.contains(NULLABLE)) } } return ClassName(packageName, outerMostType) .parameterizedBy(params) .copy(nullable = isOuterMostTypeNullable) } else { val parameters = parametersString.substringBefore(ENDING_BRACKET).split(STARTING_BRACKET) .map { ClassName(packageName, it) } .toMutableList() return ClassName(packageName, outerMostType) .parameterizedBy(createNestedParameterizedTypes(parameters)) .copy(nullable = isOuterMostTypeNullable) } } /** * A recursive method that goes through the given list until completion and * creates a parameterized [TypeName] from it. * * @param classes a list of [ClassNames][ClassName] that will be parameterized, specifically in order * in which they should be parameterized. A list of (List, Foo, Bar) will output `List<Foo<Bar>>` */ private fun createNestedParameterizedTypes(classes: MutableList<ClassName>): TypeName = if (classes.size == 1) { classes.first() } else { val firstClass = classes.first() classes.remove(firstClass) firstClass.parameterizedBy(createNestedParameterizedTypes(classes)) }
mit
ddbe540a75f542405922916f8766b240
36.334601
134
0.622568
5.187005
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rustSlowTests/lang/resolve/CargoGeneratedItemsResolveTest.kt
2
37530
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rustSlowTests.lang.resolve import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.testFramework.fixtures.impl.TempDirTestFixtureImpl import org.intellij.lang.annotations.Language import org.rust.WithExperimentalFeatures import org.rust.fileTree import org.rust.ide.experiments.RsExperiments import org.rust.lang.core.psi.RsMethodCall import org.rust.lang.core.psi.RsPath import org.rustSlowTests.cargo.runconfig.RunConfigurationTestBase @WithExperimentalFeatures(RsExperiments.EVALUATE_BUILD_SCRIPTS) class CargoGeneratedItemsResolveTest : RunConfigurationTestBase() { private val tempDirFixture = TempDirTestFixtureImpl() override fun setUp() { super.setUp() tempDirFixture.setUp() } override fun tearDown() { tempDirFixture.tearDown() super.tearDown() } // Disable creation of temp directory with test name // because it leads to too long path and compilation of test rust project fails on Windows override fun shouldContainTempFiles(): Boolean = false fun `test include in workspace project`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) rust("build.rs", BUILD_RS) dir("src") { rust("main.rs", MAIN_RS) } }.checkReferenceIsResolved<RsPath>("src/main.rs") } // https://github.com/intellij-rust/intellij-rust/issues/4579 fun `test do not overflow stack 1`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) rust("build.rs", """ use std::env; use std::fs::File; use std::io::Write; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("main.rs"); let mut f = File::create(&dest_path).unwrap(); f.write_all(b" pub fn message() -> &'static str { \"Hello, World!\" }", ).unwrap(); } """) dir("src") { rust("main.rs", """ include!(concat!(env!("OUT_DIR"), "/main.rs")); fn main() { println!("{}", message()); //^ } """) } }.checkReferenceIsResolved<RsPath>("src/main.rs") } // https://github.com/intellij-rust/intellij-rust/issues/4579 fun `test do not overflow stack 2`() { buildProject { toml("Cargo.toml", """ [workspace] members = [ "intellij-rust-test-1", "intellij-rust-test-2" ] """) dir("intellij-rust-test-1") { toml("Cargo.toml", """ [package] name = "intellij-rust-test-1" version = "0.1.0" authors = [] """) rust("build.rs", """ use std::env; use std::fs::File; use std::io::Write; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("lib.rs"); let mut f = File::create(&dest_path).unwrap(); f.write_all(b" pub fn message() -> &'static str { \"Hello, World!\" }", ).unwrap(); } """) dir("src") { rust("lib.rs", """ include!(concat!(env!("OUT_DIR"), "/lib.rs")); fn main() { println!("{}", message()); //^ } """) } } dir("intellij-rust-test-2") { toml("Cargo.toml", """ [package] name = "intellij-rust-test-2" version = "0.1.0" authors = [] """) rust("build.rs", """ use std::env; use std::fs::File; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("lib.rs"); let mut f = File::create(&dest_path).unwrap(); } """) dir("src") { rust("lib.rs", """ include!(concat!(env!("OUT_DIR"), "/lib.rs")); """) } } }.checkReferenceIsResolved<RsPath>("intellij-rust-test-1/src/lib.rs") } fun `test include in dependency`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] [dependencies] code-generation-example = "0.1.0" """) dir("src") { rust("lib.rs", """ fn main() { println!("{}", code_generation_example::message()); //^ } """) } }.checkReferenceIsResolved<RsPath>("src/lib.rs") } fun `test include with build script info with invalid code`() { assertTrue(Registry.`is`("org.rust.cargo.evaluate.build.scripts.wrapper")) buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] [dependencies] code-generation-example = "0.1.0" """) dir("src") { rust("lib.rs", """ fn main() { println!("{}", code_generation_example::message()); //^ some syntax errors here } """) } }.checkReferenceIsResolved<RsPath>("src/lib.rs") } fun `test generated cfg option`() { val libraryDir = tempDirFixture.getFile(".")!! val library = fileTree { toml("Cargo.toml", """ [package] name = "foo" version = "0.1.0" authors = [] """) dir("src") { rust("lib.rs", """ #[cfg(not(has_generated_feature))] mod disabled; #[cfg(has_generated_feature)] mod enabled; #[cfg(not(has_generated_feature))] pub use disabled::function_under_cfg; #[cfg(has_generated_feature)] pub use enabled::function_under_cfg; """) rust("disabled.rs", """ pub fn function_under_cfg() { println!("'has_generated_feature' is disabled") } """) rust("enabled.rs", """ pub fn function_under_cfg() { println!("'has_generated_feature' is enabled") } """) } rust("build.rs", """ fn main() { println!("cargo:rustc-cfg=has_generated_feature"); } """) }.create(project, libraryDir) val libraryPath = FileUtil.toSystemIndependentName(library.root.path) .let { rustupFixture.toolchain?.toRemotePath(it) } buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] [dependencies] foo = { path = "$libraryPath" } """) dir("src") { rust("main.rs", """ extern crate foo; use foo::function_under_cfg; fn main() { function_under_cfg(); //^ } """) } }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../src/enabled.rs") } fun `test generated feature`() { val libraryDir = tempDirFixture.getFile(".")!! val library = fileTree { toml("Cargo.toml", """ [package] name = "foo" version = "0.1.0" authors = [] """) dir("src") { rust("lib.rs", """ #[cfg(not(feature = "generated_feature"))] mod disabled; #[cfg(feature = "generated_feature")] mod enabled; #[cfg(not(feature = "generated_feature"))] pub use disabled::function_under_feature; #[cfg(feature = "generated_feature")] pub use enabled::function_under_feature; """) rust("disabled.rs", """ pub fn function_under_feature() { println!("'generated_feature' is disabled") } """) rust("enabled.rs", """ pub fn function_under_feature() { println!("'generated_feature' is enabled") } """) } rust("build.rs", """ fn main() { println!("cargo:rustc-cfg=feature=\"generated_feature\""); } """) }.create(project, libraryDir) val libraryPath = FileUtil.toSystemIndependentName(library.root.path) .let { rustupFixture.toolchain?.toRemotePath(it) } buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] [dependencies] foo = { path = "$libraryPath" } """) dir("src") { rust("main.rs", """ extern crate foo; use foo::function_under_feature; fn main() { function_under_feature(); //^ } """) } }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../src/enabled.rs") } fun `test custom generated feature`() { val libraryDir = tempDirFixture.getFile(".")!! val library = fileTree { toml("Cargo.toml", """ [package] name = "foo" version = "0.1.0" authors = [] """) dir("src") { rust("lib.rs", """ #[cfg(not(generated_feature_key = "generated_feature_value"))] mod disabled; #[cfg(generated_feature_key = "generated_feature_value")] mod enabled; #[cfg(not(generated_feature_key = "generated_feature_value"))] pub use disabled::function_under_custom_feature; #[cfg(generated_feature_key = "generated_feature_value")] pub use enabled::function_under_custom_feature; """) rust("disabled.rs", """ pub fn function_under_custom_feature() { println!("custom generated feature is disabled") } """) rust("enabled.rs", """ pub fn function_under_custom_feature() { println!("custom generated feature is enabled") } """) } rust("build.rs", """ fn main() { println!("cargo:rustc-cfg=generated_feature_key=\"generated_feature_value\""); } """) }.create(project, libraryDir) val libraryPath = FileUtil.toSystemIndependentName(library.root.path) .let { rustupFixture.toolchain?.toRemotePath(it) } buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] [dependencies] foo = { path = "$libraryPath" } """) dir("src") { rust("main.rs", """ extern crate foo; use foo::function_under_custom_feature; fn main() { function_under_custom_feature(); //^ } """) } }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../src/enabled.rs") } fun `test generated cfg option with the same name as compiler one`() { val libraryDir = tempDirFixture.getFile(".")!! val library = fileTree { toml("Cargo.toml", """ [package] name = "foo" version = "0.1.0" authors = [] """) dir("src") { rust("lib.rs", """ #[cfg(not(windows))] mod disabled; #[cfg(windows)] mod enabled; #[cfg(not(windows))] pub use disabled::function_under_cfg; #[cfg(windows)] pub use enabled::function_under_cfg; """) rust("disabled.rs", """ pub fn function_under_cfg() { println!("custom generated cfg option is disabled") } """) rust("enabled.rs", """ pub fn function_under_cfg() { println!("custom generated cfg option is enabled") } """) } rust("build.rs", """ fn main() { println!("cargo:rustc-cfg=windows"); } """) }.create(project, libraryDir) val libraryPath = FileUtil.toSystemIndependentName(library.root.path) .let { rustupFixture.toolchain?.toRemotePath(it) } buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] [dependencies] foo = { path = "$libraryPath" } """) dir("src") { rust("main.rs", """ extern crate foo; use foo::function_under_cfg; fn main() { function_under_cfg(); //^ } """) } }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../src/enabled.rs") } fun `test generated custom feature with the same name as compiler one`() { val libraryDir = tempDirFixture.getFile(".")!! val library = fileTree { toml("Cargo.toml", """ [package] name = "foo" version = "0.1.0" authors = [] """) dir("src") { rust("lib.rs", """ #[cfg(not(target_family = "windows"))] mod disabled; #[cfg(target_family = "windows")] mod enabled; #[cfg(not(target_family = "windows"))] pub use disabled::function_under_cfg; #[cfg(target_family = "windows")] pub use enabled::function_under_cfg; """) rust("disabled.rs", """ pub fn function_under_cfg() { println!("custom generated cfg option is disabled") } """) rust("enabled.rs", """ pub fn function_under_cfg() { println!("custom generated cfg option is enabled") } """) } rust("build.rs", """ fn main() { println!("cargo:rustc-cfg=target_family=\"windows\""); } """) }.create(project, libraryDir) val libraryPath = FileUtil.toSystemIndependentName(library.root.path) .let { rustupFixture.toolchain?.toRemotePath(it) } buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] [dependencies] foo = { path = "$libraryPath" } """) dir("src") { rust("main.rs", """ extern crate foo; use foo::function_under_cfg; fn main() { function_under_cfg(); //^ } """) } }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../src/enabled.rs") } fun `test generated environment variables`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) dir("src") { rust("main.rs", """ include!(concat!("foo/", env!("GENERATED_ENV_DIR"), "/hello.rs")); fn main() { hello(); //^ } """) dir("foo") { dir("bar") { rust("hello.rs", """ fn hello() { println!("Hello!"); } """) } } } rust("build.rs", """ fn main() { println!("cargo:rustc-env=GENERATED_ENV_DIR=bar"); } """) }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../foo/bar/hello.rs") } fun `test generated environment variables 2`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) dir("src") { rust("main.rs", """ include!(concat!(env!("GENERATED_ENV_DIR"), "/hello.rs")); fn main() { println!("{}", message()); //^ } """) } rust("build.rs", """ use std::env; use std::fs; use std::fs::File; use std::io::Write; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let gen_dir = Path::new(&out_dir).join("gen"); if !gen_dir.exists() { fs::create_dir(&gen_dir).unwrap(); } let dest_path = gen_dir.join("hello.rs"); generate_file(&dest_path, b" pub fn message() -> &'static str { \"Hello, World!\" } "); println!("cargo:rustc-env=GENERATED_ENV_DIR={}", gen_dir.display()); } fn generate_file<P: AsRef<Path>>(path: P, text: &[u8]) { let mut f = File::create(path).unwrap(); f.write_all(text).unwrap() } """) }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../gen/hello.rs") } fun `test include without file name in literal`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) dir("src") { rust("main.rs", """ include!(env!("GENERATED_ENV_FILE")); fn main() { println!("{}", message()); //^ } """) } rust("build.rs", """ use std::env; use std::fs; use std::fs::File; use std::io::Write; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let gen_dir = Path::new(&out_dir).join("gen"); if !gen_dir.exists() { fs::create_dir(&gen_dir).unwrap(); } let dest_path = gen_dir.join("hello.rs"); generate_file(&dest_path, b" pub fn message() -> &'static str { \"Hello, World!\" } "); println!("cargo:rustc-env=GENERATED_ENV_FILE={}", dest_path.display()); } fn generate_file<P: AsRef<Path>>(path: P, text: &[u8]) { let mut f = File::create(path).unwrap(); f.write_all(text).unwrap() } """) }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../gen/hello.rs") } fun `test include without file name in literal 2`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) dir("src") { rust("main.rs", """ include!(concat!(env!("OUT_DIR"), "/hello", ".rs")); fn main() { println!("{}", message()); //^ } """) } rust("build.rs", """ use std::env; use std::fs::File; use std::io::Write; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("hello.rs"); let mut f = File::create(&dest_path).unwrap(); f.write_all(b" pub fn message() -> &'static str { \"Hello, World!\" }", ).unwrap(); } """) }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../hello.rs") } fun `test do not fail on compilation error`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) dir("src") { rust("main.rs", """ pub mod bar; fn main() { println!("{}", bar::message()); //^ } """) rust("bar.rs", """ pub fn message() -> String { } // compilation error """) } }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../src/bar.rs") } fun `test panic in workspace build script`() { buildProject { dir("local_dep") { toml("Cargo.toml", """ [package] name = "local_dep" version = "0.1.0" authors = [] """) rust("build.rs", BUILD_RS) dir("src") { rust("lib.rs", """ include!(concat!(env!("OUT_DIR"), "/hello.rs")); """) } } toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] # Build dependency is used here to commit compilation order # and make cargo compile `local_dep` strictly before `build.rs` [build-dependencies] local_dep = { path = "local_dep" } """) rust("build.rs", """ fn main() { panic!("Build script panic {}", local_dep::message()); //^ } """) dir("src") { rust("main.rs", """ fn main() {} """) } }.checkReferenceIsResolved<RsPath>("build.rs", toFile = ".../hello.rs") } fun `test custom target directory location`() { val customTargetDir = tempDirFixture.getFile(".")!!.path buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) dir("src") { rust("main.rs", MAIN_RS) } dir(".cargo") { toml("config", """ [build] target-dir = "$customTargetDir" """) } rust("build.rs", BUILD_RS) }.checkReferenceIsResolved<RsPath>("src/main.rs", toFile = ".../hello.rs") } fun `test workspace with package`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test-1" version = "0.1.0" authors = [] [workspace] members = ["intellij-rust-test-2"] """) dir("src") { rust("main.rs", "fn main() {}") } dir("intellij-rust-test-2") { toml("Cargo.toml", """ [package] name = "intellij-rust-test-2" version = "0.1.0" authors = [] """) dir("src") { rust("main.rs", MAIN_RS) } rust("build.rs", BUILD_RS) } }.checkReferenceIsResolved<RsPath>("intellij-rust-test-2/src/main.rs", toFile = ".../hello.rs") } // https://github.com/intellij-rust/intellij-rust/issues/8057 fun `test generated impl block`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) dir("src") { rust("main.rs", """ include!(concat!(env!("OUT_DIR"), "/hello.rs")); fn main() { Hello.hello(); } //^ """) } rust("build.rs", """ use std::{fs, path, env}; fn main() { let content = "\ pub struct Hello; impl Hello { pub fn hello(&self) { println!(\"Hello!\"); } } "; let out_dir = env::var_os("OUT_DIR").unwrap(); let path = path::Path::new(&out_dir).join("hello.rs"); fs::write(&path, content).unwrap(); } """) }.checkReferenceIsResolved<RsMethodCall>("src/main.rs", toFile = ".../hello.rs") } fun `test crate with examples only`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) dir("examples") { rust("foo.rs", MAIN_RS) } rust("build.rs", BUILD_RS) }.checkReferenceIsResolved<RsPath>("examples/foo.rs", toFile = ".../hello.rs") } fun `test include large generated file`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) rust("build.rs", """ use std::env; use std::fs::File; use std::io::{Seek, Write}; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("hello.rs"); let mut f = File::create(&dest_path).unwrap(); let payload = b" pub fn message() -> &'static str { \"Hello, World!\" }"; f.write_all(payload).unwrap(); let mut size = payload.len(); while size < 4 * 1024 * 1024 { let garbage = b"// Some comments that should bloat the file size\n"; f.write_all(garbage).unwrap(); size += garbage.len(); } } """) dir("src") { rust("main.rs", MAIN_RS) } }.checkReferenceIsResolved<RsPath>("src/main.rs") } fun `test include large generated file in a subdirectory`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) rust("build.rs", """ use std::env; use std::fs::{create_dir, File}; use std::io::{Seek, Write}; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("foo").join("hello.rs"); create_dir(dest_path.parent().unwrap()).unwrap(); let mut f = File::create(&dest_path).unwrap(); let payload = b" pub fn message() -> &'static str { \"Hello, World!\" }"; f.write_all(payload).unwrap(); let mut size = payload.len(); while size < 4 * 1024 * 1024 { let garbage = b"// Some comments that should bloat the file size\n"; f.write_all(garbage).unwrap(); size += garbage.len(); } } """) dir("src") { rust("main.rs", """ include!(concat!(env!("OUT_DIR"), "/foo/hello.rs")); fn main() { println!("{}", message()); //^ } """) } }.checkReferenceIsResolved<RsPath>("src/main.rs") } fun `test rustc invoked from a build script is not always succeed during sync`() { buildProject { toml("Cargo.toml", """ [package] name = "intellij-rust-test" version = "0.1.0" authors = [] """) rust("build.rs", """ use std::env; use std::fs; use std::fs::File; use std::io::Write; use std::path::Path; use std::process::{Command, ExitStatus, Stdio}; use std::str; const PROBE: &str = r#" pub fn foo() { There is a syntax error here. } "#; fn main() { match compile_probe() { Some(status) if status.success() => panic!("The probe must not succeed"), None => panic!("Unknown failure"), _ => {} } let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("hello.rs"); let mut f = File::create(&dest_path).unwrap(); f.write_all(b" pub fn message() -> &'static str { \"Hello, World!\" }", ).unwrap(); } fn compile_probe() -> Option<ExitStatus> { let rustc = env::var_os("RUSTC")?; let out_dir = env::var_os("OUT_DIR")?; let probefile = Path::new(&out_dir).join("probe.rs"); fs::write(&probefile, PROBE).ok()?; // Make sure to pick up Cargo rustc configuration. let mut cmd = if let Some(wrapper) = env::var_os("RUSTC_WRAPPER") { let mut cmd = Command::new(wrapper); // The wrapper's first argument is supposed to be the path to rustc. cmd.arg(rustc); cmd } else { Command::new(rustc) }; cmd.stderr(Stdio::null()) .arg("--crate-name=probe") .arg("--crate-type=lib") .arg("--emit=metadata") .arg("--out-dir") .arg(out_dir) .arg(probefile); if let Some(target) = env::var_os("TARGET") { cmd.arg("--target").arg(target); } // If Cargo wants to set RUSTFLAGS, use that. if let Ok(rustflags) = env::var("CARGO_ENCODED_RUSTFLAGS") { if !rustflags.is_empty() { for arg in rustflags.split('\x1f') { cmd.arg(arg); } } } cmd.status().ok() } """) dir("src") { rust("main.rs", MAIN_RS) } }.checkReferenceIsResolved<RsPath>("src/main.rs") } companion object { @Language("Rust") private const val MAIN_RS = """ include!(concat!(env!("OUT_DIR"), "/hello.rs")); fn main() { println!("{}", message()); //^ } """ @Language("Rust") private const val BUILD_RS = """ use std::env; use std::fs::File; use std::io::Write; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("hello.rs"); let mut f = File::create(&dest_path).unwrap(); f.write_all(b" pub fn message() -> &'static str { \"Hello, World!\" }", ).unwrap(); } """ } }
mit
97b0a7483c692849483ee49787c0b791
33.431193
103
0.375007
5.13828
false
true
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/lang/core/completion/RsStructPatRestCompletionTest.kt
3
1072
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion class RsStructPatRestCompletionTest : RsCompletionTestBase() { fun `test rest in let struct pat`() = checkContainsCompletion("..", """ struct S { a: i32 } fn foo() { let S { /*caret*/ } = S { a: 0 }; } """) fun `test rest in match struct pat`() = checkContainsCompletion("..", """ struct S { a: i32 } fn foo(s: S) { match s { S { /*caret*/ } => {} } } """) fun `test do not offer rest if it's already present`() = checkNotContainsCompletion("..", """ struct S { a: i32 } fn foo(s: S) { match s { S { a, /*caret*/, .. } => {} } } """) fun `test do not offer in struct constructor`() = checkNotContainsCompletion("..", """ struct S { a: i32 } fn foo() { let s = S { /*caret*/ }; } """) }
mit
a5bd8fc58d42b3f88fa01b15c7288fe7
23.363636
97
0.467351
4.1875
false
true
false
false
michael71/LanbahnPanel
app/src/main/java/de/blankedv/lanbahnpanel/elements/CompRoute.kt
1
2629
package de.blankedv.lanbahnpanel.elements import java.util.ArrayList import android.util.Log import de.blankedv.lanbahnpanel.model.* /** * composite route, i.e. a list of routes which build a new route, is only a * helper for ease of use, no more functionality than the "simple" Route which * it is comprised of * * @author mblank */ class CompRoute /** * constructs a composite route * * */ (internal var adr: Int // must be unique , internal var btn1: Int, internal var btn2: Int, sRoutes: String) { internal var routesString = "" // identical to config string // route is comprised of a list of routes private val myroutes = ArrayList<Route>() var isActive = false init { // this string written back to config file. this.routesString = sRoutes if (DEBUG) Log.d(TAG, "creating comproute adr=$adr") // routes = "12,13": these routes need to be activated. val iID = routesString.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (i in iID.indices) { val routeID = Integer.parseInt(iID[i]) for (rt in routes) { try { if (rt.adr == routeID) { myroutes.add(rt) } } catch (e: NumberFormatException) { } } } if (DEBUG) Log.d(TAG, myroutes.size.toString() + " routes in this route.") }// /* no clear for compound routes because the single routes are cleared automatically after X seconds public void clear() { } */ fun request() { if (DEBUG) Log.d(TAG, "requesting comproute adr=$adr") // request to set this route in central var cmd = "REQ $adr 1" // for other tablets sendQ.add(cmd) } fun clearRequest() { if (DEBUG) Log.d(TAG, "requesting CLEAR comproute adr=$adr") // request to set this route in central var cmd = "REQ $adr 0" // for other tablets sendQ.add(cmd) } companion object { /** * check if we need to update the comp route state "isActive = true" when * data = 1, and the depending "simple routes" * */ fun update ( addr : Int, data : Int) { for (crt in compRoutes) { if (crt.adr == addr) { crt.isActive = (data != 0) for (rt in crt.myroutes) { rt.isActive = (data != 0) } } } } } }
gpl-3.0
21120549b400fb3b25bac94e46cf4ce7
25.826531
103
0.535565
4.186306
false
false
false
false
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/mapper/BlacklistTopicModelMapper.kt
1
1128
package com.sedsoftware.yaptalker.presentation.mapper import com.sedsoftware.yaptalker.domain.entity.base.BlacklistedTopic import com.sedsoftware.yaptalker.presentation.mapper.util.DateTransformer import com.sedsoftware.yaptalker.presentation.mapper.util.TextTransformer import com.sedsoftware.yaptalker.presentation.model.base.BlacklistedTopicModel import io.reactivex.functions.Function import javax.inject.Inject class BlacklistTopicModelMapper @Inject constructor( private val textTransformer: TextTransformer, private val dateTransformer: DateTransformer ) : Function<List<BlacklistedTopic>, List<BlacklistedTopicModel>> { override fun apply(from: List<BlacklistedTopic>): List<BlacklistedTopicModel> = from.map { element -> BlacklistedTopicModel( topicName = element.topicName, topicId = element.topicId, dateAdded = element.dateAdded, dateAddedLabel = textTransformer.transformBlacklistDate( dateTransformer.transformLongToDateString(element.dateAdded.time) ) ) } }
apache-2.0
1a381981280c1fd60530013e3fea0958
42.384615
85
0.736702
4.99115
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/test/java/androidx/compose/ui/text/font/FontWeightTest.kt
3
3938
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.font import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class FontWeightTest { @Test fun `constructor accept 1000`() { assertThat(FontWeight(1000).weight).isEqualTo(1000) } @Test fun `constructor accept 1`() { assertThat(FontWeight(1).weight).isEqualTo(1) } @Test(expected = IllegalArgumentException::class) fun `constructor does not accept greater than 1000`() { FontWeight(1001) } @Test(expected = IllegalArgumentException::class) fun `constructor does not accept less than 1`() { FontWeight(0) } @Test fun `lerp at start returns start value`() { assertThat( lerp( FontWeight.W200, FontWeight.W400, 0.0f ) ).isEqualTo(FontWeight.W200) } @Test fun `lerp at start returns font weight 1`() { val start = FontWeight(1) assertThat(lerp(start, FontWeight.W400, 0.0f)).isEqualTo(start) } @Test fun `lerp at end returns end value`() { assertThat( lerp( FontWeight.W200, FontWeight.W400, 1.0f ) ).isEqualTo(FontWeight.W400) } @Test fun `lerp in the mid-time`() { assertThat( lerp( FontWeight.W200, FontWeight.W800, 0.5f ) ).isEqualTo(FontWeight.W500) } @Test fun `lerp in the mid-time with odd distance should be rounded to up`() { val start = FontWeight.W200 val stop = FontWeight.W900 assertThat( lerp( start, stop, 0.5f ) ).isEqualTo(FontWeight(((stop.weight + start.weight) * 0.5).toInt())) } @Test fun `values return all weights`() { val expectedValues = listOf( FontWeight.W100, FontWeight.W200, FontWeight.W300, FontWeight.W400, FontWeight.W500, FontWeight.W600, FontWeight.W700, FontWeight.W800, FontWeight.W900 ) assertThat(FontWeight.values).isEqualTo(expectedValues) } @Test fun `weight returns collect values`() { val fontWeights = mapOf( FontWeight.W100 to 100, FontWeight.W200 to 200, FontWeight.W300 to 300, FontWeight.W400 to 400, FontWeight.W500 to 500, FontWeight.W600 to 600, FontWeight.W700 to 700, FontWeight.W800 to 800, FontWeight.W900 to 900 ) // TODO(b/130795950): IR compiler bug was here for (weightPair in fontWeights) { val (fontWeight, expectedWeight) = weightPair assertThat(fontWeight.weight).isEqualTo(expectedWeight) } } @Test fun compareTo() { assertThat(FontWeight.W400.compareTo(FontWeight.W400)).isEqualTo(0) assertThat(FontWeight.W400.compareTo(FontWeight.W300)).isEqualTo(1) assertThat(FontWeight.W400.compareTo(FontWeight.W500)).isEqualTo(-1) } }
apache-2.0
65751af97c6a9f6bbf94f456fd93443a
27.135714
77
0.586592
4.404922
false
true
false
false
google-developer-training/basic-android-kotlin-compose-training-lunch-tray
app/src/main/java/com/example/lunchtray/ui/theme/Type.kt
1
1095
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.lunchtray.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) )
apache-2.0
1b4565b6accd1c014d42890185675998
34.322581
75
0.747032
4.147727
false
false
false
false
Adonai/Man-Man
app/src/main/java/com/adonai/manman/entities/ManPage.kt
1
1157
package com.adonai.manman.entities import com.j256.ormlite.field.DataType import com.j256.ormlite.field.DatabaseField import com.j256.ormlite.table.DatabaseTable import com.adonai.manman.ManPageDialogFragment import java.util.* /** * Holder for caching man-page contents to DB * Represents man page contents and provides relation to chapter page with description if possible * * The fields "url" and "name" are not foreign for [ManSectionItem] * as they can be retrieved from search page, not contents * * @see ManPageDialogFragment * @see ManCacheFragment * * @author Kanedias */ @DatabaseTable(tableName = "man_pages") class ManPage { constructor(name: String, url: String) { this.name = name this.url = url } @Suppress("unused") constructor() @DatabaseField(id = true, canBeNull = false) lateinit var url: String @DatabaseField(canBeNull = false) lateinit var name: String @DatabaseField(dataType = DataType.LONG_STRING, canBeNull = false) lateinit var webContent: String @DatabaseField(dataType = DataType.SERIALIZABLE, canBeNull = false) var links = TreeSet<String>() }
gpl-3.0
bbc91381a87662ef3b900532f9ca5222
25.930233
98
0.725151
3.962329
false
false
false
false
groupon/kmond
src/main/kotlin/com/groupon/aint/kmond/admin/HealthcheckHandler.kt
1
3382
/** * Copyright 2015 Groupon Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.groupon.aint.kmond.admin import com.groupon.aint.kmond.util.InstrumentedRouteHandler import com.groupon.vertx.utils.Logger import io.netty.handler.codec.http.HttpHeaders import io.netty.handler.codec.http.HttpResponseStatus import io.vertx.core.http.HttpMethod import io.vertx.core.http.HttpServerResponse import io.vertx.ext.web.RoutingContext /** * Simple heartbeat handler based on existence of a file. * * @author Gil Markham (gil at groupon dot com) */ class HealthcheckHandler(val filePath: String) : InstrumentedRouteHandler() { companion object { val log = Logger.getLogger(HealthcheckHandler::class.java) const val CONTENT_TYPE = "plain/text" const val CACHE_CONTROL = "private, no-cache, no-store, must-revalidate" } override fun internalHandle(context: RoutingContext) { context.vertx().fileSystem().exists(filePath) { if( it.succeeded()) { processHealthcheckResponse(it.result(), context) } else { processExceptionResponse(context, it.cause()) } } } fun processHealthcheckResponse(exists: Boolean, context: RoutingContext) { val response = context.response() val requestMethod = context.request().method() val includeBody = requestMethod == HttpMethod.GET val status = if(exists) { HttpResponseStatus.OK } else { HttpResponseStatus.SERVICE_UNAVAILABLE } setCommonHttpResponse(response, status) val responseBody = status.reasonPhrase() if (includeBody) { response.end(responseBody) } else { response.putHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseBody.length) response.end() } } fun processExceptionResponse(context: RoutingContext, ex: Throwable) { val status = HttpResponseStatus.SERVICE_UNAVAILABLE; val response = context.response() val requestMethod = context.request().method() val includeBody = requestMethod == HttpMethod.GET val responseBody = status.reasonPhrase() + ": " + ex.message setCommonHttpResponse(response, status) if (includeBody) { response.end(responseBody) } else { response.putHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseBody.length) response.end() } } private fun setCommonHttpResponse(response: HttpServerResponse, status: HttpResponseStatus) { response.putHeader(HttpHeaders.Names.CONTENT_TYPE, CONTENT_TYPE) response.putHeader(HttpHeaders.Names.CACHE_CONTROL, CACHE_CONTROL) response.setStatusCode(status.code()) response.setStatusMessage(status.reasonPhrase()) } }
apache-2.0
2ccd7cba4626a05d69e371b8a9bae487
35.365591
97
0.680367
4.57027
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/search/authors/SearchAuthorsPresenter.kt
2
2219
package ru.fantlab.android.ui.modules.search.authors import android.view.View import io.reactivex.Single import io.reactivex.functions.Consumer import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.SearchAuthor import ru.fantlab.android.data.dao.response.SearchAuthorsResponse import ru.fantlab.android.provider.rest.DataManager import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter class SearchAuthorsPresenter : BasePresenter<SearchAuthorsMvp.View>(), SearchAuthorsMvp.Presenter { private var page: Int = 1 private var previousTotal: Int = 0 private var lastPage: Int = Integer.MAX_VALUE override fun onCallApi(page: Int, parameter: String?): Boolean { if (page == 1) { lastPage = Integer.MAX_VALUE sendToView { it.getLoadMore().reset() } } setCurrentPage(page) if (page > lastPage || lastPage == 0 || parameter == null) { sendToView { it.hideProgress() } return false } if (previousTotal == 1000) { sendToView { it.hideProgress() it.showMessage(R.string.error, R.string.results_warning) } return false } makeRestCall( getAuthorsFromServer(parameter, page).toObservable(), Consumer { (authors, totalCount, lastPage) -> this.lastPage = lastPage sendToView { with (it) { onNotifyAdapter(authors, page) onSetTabCount(totalCount) } } } ) return true } private fun getAuthorsFromServer(query: String, page: Int): Single<Triple<ArrayList<SearchAuthor>, Int, Int>> = DataManager.searchAuthors(query, page) .map { getAuthors(it) } private fun getAuthors(response: SearchAuthorsResponse): Triple<ArrayList<SearchAuthor>, Int, Int> = Triple(response.authors.items, response.authors.totalCount, response.authors.last) override fun onItemClick(position: Int, v: View?, item: SearchAuthor) { sendToView { it.onItemClicked(item) } } override fun onItemLongClick(position: Int, v: View?, item: SearchAuthor) { } override fun getCurrentPage(): Int = page override fun getPreviousTotal(): Int = previousTotal override fun setCurrentPage(page: Int) { this.page = page } override fun setPreviousTotal(previousTotal: Int) { this.previousTotal = previousTotal } }
gpl-3.0
8e8be22f6f7e20102618d1bff23fb904
27.831169
101
0.727805
3.584814
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/editor/completion/KeywordInsertHandler.kt
2
3739
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.editor.completion import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.template.TemplateManager import com.intellij.codeInsight.template.impl.MacroCallNode import com.intellij.codeInsight.template.impl.TextExpression import com.intellij.openapi.editor.Document import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.tree.IElementType import com.intellij.psi.util.PsiTreeUtil import com.tang.intellij.lua.codeInsight.template.macro.SuggestLuaParametersMacro import com.tang.intellij.lua.psi.LuaClosureExpr import com.tang.intellij.lua.psi.LuaIndentRange import com.tang.intellij.lua.psi.LuaTypes.* /** * 关键字插入时缩进处理 * Created by TangZX on 2016/12/20. */ class KeywordInsertHandler internal constructor(private val keyWordToken: IElementType) : InsertHandler<LookupElement> { override fun handleInsert(insertionContext: InsertionContext, lookupElement: LookupElement) { val file = insertionContext.file val project = insertionContext.project val document = insertionContext.document val offset = insertionContext.tailOffset if (keyWordToken == FUNCTION) { val element = file.findElementAt(insertionContext.startOffset) if (element?.parent is LuaClosureExpr) { val templateManager = TemplateManager.getInstance(project) val template = templateManager.createTemplate("", "", "(\$PARAMETERS\$) \$END\$ end") template.addVariable("PARAMETERS", MacroCallNode(SuggestLuaParametersMacro(SuggestLuaParametersMacro.Position.KeywordInsertHandler)), TextExpression(""), false) templateManager.startTemplate(insertionContext.editor, template) } } else { val element = file.findElementAt(offset) if (element != null && element !is PsiWhiteSpace) { document.insertString(insertionContext.tailOffset, " ") insertionContext.editor.caretModel.moveToOffset(insertionContext.tailOffset) } } autoIndent(keyWordToken, file, project, document, offset) } companion object { fun autoIndent(keyWordToken: IElementType, file: PsiFile, project: Project, document: Document, offset: Int) { if (keyWordToken === END || keyWordToken === ELSE || keyWordToken === ELSEIF) { PsiDocumentManager.getInstance(project).commitDocument(document) val element = PsiTreeUtil.findElementOfClassAtOffset(file, offset, LuaIndentRange::class.java, false) if (element != null) { val styleManager = CodeStyleManager.getInstance(project) styleManager.adjustLineIndent(file, element.textRange) } } } } }
apache-2.0
56ace7a36faf81d666be273ccfd30528
45.4875
176
0.721699
4.719543
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/debugger/protocol/StepCommand.kt
1
1583
package org.jetbrains.haskell.debugger.protocol import org.jetbrains.haskell.debugger.parser.GHCiParser import java.util.Deque import org.jetbrains.haskell.debugger.parser.HsStackFrameInfo import org.json.simple.JSONObject import org.jetbrains.haskell.debugger.frames.HsHistoryFrame import org.jetbrains.haskell.debugger.parser.JSONConverter import org.jetbrains.haskell.debugger.procdebuggers.ProcessDebugger import org.jetbrains.haskell.debugger.procdebuggers.utils.DebugRespondent /** * Created by vlad on 7/17/14. */ public abstract class StepCommand(callback: CommandCallback<HsStackFrameInfo?>?) : AbstractCommand<HsStackFrameInfo?>(callback) { override fun parseGHCiOutput(output: Deque<String?>): HsStackFrameInfo? = GHCiParser.tryParseStoppedAt(output) override fun parseJSONOutput(output: JSONObject): HsStackFrameInfo? = JSONConverter.stoppedAtFromJSON(output) public class StandardStepCallback(val debugger: ProcessDebugger, val debugRespondent: DebugRespondent) : CommandCallback<HsStackFrameInfo?>() { override fun execBeforeSending() = debugRespondent.resetHistoryStack() override fun execAfterParsing(result: HsStackFrameInfo?) { if (result != null) { val frame = HsHistoryFrame(debugger, result) frame.obsolete = false debugger.history(HistoryCommand.DefaultHistoryCallback(debugger, debugRespondent, frame, null)) } else { debugRespondent.traceFinished() } } } }
apache-2.0
71c845070640bfe874e914b8a9b4a8a7
37.609756
116
0.7271
4.782477
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-basex/test/uk/co/reecedunn/intellij/plugin/basex/tests/query/session/BaseXQueryInfoTest.kt
1
16124
/* * Copyright (C) 2019-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.basex.tests.query.session import org.hamcrest.CoreMatchers.`is` import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import uk.co.reecedunn.intellij.plugin.basex.query.session.toBaseXInfo import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat import uk.co.reecedunn.intellij.plugin.xdm.types.impl.values.XsDuration @Suppress("UNCHECKED_CAST", "RedundantInnerClassModifier") @DisplayName("IntelliJ - Base Platform - Run Configuration - XQuery Processor - BaseX info text") class BaseXQueryInfoTest { @Nested @DisplayName("BaseX 7.0 info") inner class BaseX70 { private val responseEn = listOf( "Results: 4 Items", "Updated: 0 Items", "Total Time: 413.16 ms", "" ) @Test @DisplayName("Windows line endings") fun windows() { val info = responseEn.joinToString("\r\n").toBaseXInfo() assertThat(info.size, `is`(4)) assertThat(info["Results"], `is`("4 Items")) assertThat(info["Updated"], `is`("0 Items")) assertThat(info["Total Time"], `is`(XsDuration.ns(413160000))) val profile = info["Profile"] as HashMap<String, XsDuration> assertThat(profile["Total Time"], `is`(XsDuration.ns(413160000))) assertThat(profile.size, `is`(1)) } @Test @DisplayName("Linux line endings") fun linux() { val info = responseEn.joinToString("\n").toBaseXInfo() assertThat(info.size, `is`(4)) assertThat(info["Results"], `is`("4 Items")) assertThat(info["Updated"], `is`("0 Items")) assertThat(info["Total Time"], `is`(XsDuration.ns(413160000))) val profile = info["Profile"] as HashMap<String, XsDuration> assertThat(profile["Total Time"], `is`(XsDuration.ns(413160000))) assertThat(profile.size, `is`(1)) } @Test @DisplayName("Mac line endings") fun mac() { val info = responseEn.joinToString("\r").toBaseXInfo() assertThat(info.size, `is`(4)) assertThat(info["Results"], `is`("4 Items")) assertThat(info["Updated"], `is`("0 Items")) assertThat(info["Total Time"], `is`(XsDuration.ns(413160000))) val profile = info["Profile"] as HashMap<String, XsDuration> assertThat(profile["Total Time"], `is`(XsDuration.ns(413160000))) assertThat(profile.size, `is`(1)) } } @Nested @DisplayName("BaseX 8.0 info") inner class BaseX80 { private val responseEn = listOf( "", "Query executed in 448.43 ms." ) private val responseFr = listOf( "", "Requête executée en 448.43 ms." ) private val responseJa = listOf( "", "448.43 ms のクエリーが実行されました。" ) @Test @DisplayName("English; Windows line endings") fun windows() { val info = responseEn.joinToString("\r\n").toBaseXInfo() assertThat(info.size, `is`(1)) assertThat(info["Total Time"], `is`(XsDuration.ns(448430000))) } @Test @DisplayName("English; Windows line endings") fun linux() { val info = responseEn.joinToString("\n").toBaseXInfo() assertThat(info.size, `is`(1)) assertThat(info["Total Time"], `is`(XsDuration.ns(448430000))) } @Test @DisplayName("English; Mac line endings") fun mac() { val info = responseEn.joinToString("\r").toBaseXInfo() assertThat(info.size, `is`(1)) assertThat(info["Total Time"], `is`(XsDuration.ns(448430000))) } @Test @DisplayName("French") fun french() { val info = responseFr.joinToString("\r").toBaseXInfo() assertThat(info.size, `is`(1)) assertThat(info["Total Time"], `is`(XsDuration.ns(448430000))) } @Test @DisplayName("Japanese") fun japanese() { val info = responseJa.joinToString("\r").toBaseXInfo() assertThat(info.size, `is`(1)) assertThat(info["Total Time"], `is`(XsDuration.ns(448430000))) } } @Nested @DisplayName("BaseX 8.0 queryinfo") inner class BaseX80QueryInfo { private val responseEn = listOf( "", "Query:", "for \$n in 1 to 10 let \$v := fn:sum(1 to \$n) return 2 * \$v", "", "Compiling:", "- pre-evaluate range expression to range sequence: (1 to 10)", "- inline \$v_1", "", "Optimized Query:", "for \$n_0 in (1 to 10) return (2 * sum((1 to \$n_0)))", "", "Parsing: 0.44 ms", "Compiling: 0.34 ms", "Evaluating: 0.01 ms", "Printing: 0.93 ms", "Total Time: 1.71 ms", "", "Hit(s): 10 Items", "Updated: 0 Items", "Printed: 29 b", "Read Locking: (none)", "Write Locking: (none)", "", "Query executed in 1.71 ms." ).joinToString("\r\n") private val responseFr = listOf( "", "Requête:", "for \$n in 1 to 10 let \$v := fn:sum(1 to \$n) return 2 * \$v", "", "Compilation:", "- pre-evaluate range expression to range sequence: (1 to 10)", "- inline \$v_1", "", "Requête Optimisée:", "for \$n_0 in (1 to 10) return (2 * sum((1 to \$n_0)))", "", "Analyse: 0.44 ms", "Compilation: 0.34 ms", "Évaluation: 0.01 ms", "Impression: 0.93 ms", "Temps total: 1.71 ms", "", "Hit(s): 10 Items", "Mis à jour: 0 Items", "Imprimé: 29 b", "Blocage en lecture: (none)", "Blocage en écriture: (none)", "", "Requête executée en 1.71 ms." ).joinToString("\r\n") @Test @DisplayName("toBaseXInfo; English") fun english() { val info = responseEn.toBaseXInfo() val compiling = listOf( "pre-evaluate range expression to range sequence: (1 to 10)", "inline \$v_1" ) assertThat(info.size, `is`(9)) assertThat(info["Compilation"], `is`(compiling)) assertThat(info["Optimized Query"], `is`("for \$n_0 in (1 to 10) return (2 * sum((1 to \$n_0)))")) assertThat(info["Total Time"], `is`(XsDuration.ns(1710000))) assertThat(info["Hit(s)"], `is`("10 Items")) assertThat(info["Updated"], `is`("0 Items")) assertThat(info["Printed"], `is`("29 b")) assertThat(info["Read Locking"], `is`("(none)")) assertThat(info["Write Locking"], `is`("(none)")) val profile = info["Profile"] as HashMap<String, XsDuration> assertThat(profile["Total Time"], `is`(XsDuration.ns(1710000))) assertThat(profile["Parsing"], `is`(XsDuration.ns(440000))) assertThat(profile["Compiling"], `is`(XsDuration.ns(340000))) assertThat(profile["Evaluating"], `is`(XsDuration.ns(10000))) assertThat(profile["Printing"], `is`(XsDuration.ns(930000))) assertThat(profile.size, `is`(5)) } @Test @DisplayName("toBaseXInfo; French") fun french() { val info = responseFr.toBaseXInfo() assertThat(info.size, `is`(7)) assertThat(info["Total Time"], `is`(XsDuration.ns(1710000))) assertThat(info["Hit(s)"], `is`("10 Items")) assertThat(info["Mis à jour"], `is`("0 Items")) assertThat(info["Imprimé"], `is`("29 b")) assertThat(info["Blocage en lecture"], `is`("(none)")) assertThat(info["Blocage en écriture"], `is`("(none)")) val profile = info["Profile"] as HashMap<String, XsDuration> assertThat(profile["Temps total"], `is`(XsDuration.ns(1710000))) assertThat(profile["Analyse"], `is`(XsDuration.ns(440000))) assertThat(profile["Compilation"], `is`(XsDuration.ns(340000))) assertThat(profile["Évaluation"], `is`(XsDuration.ns(10000))) assertThat(profile["Impression"], `is`(XsDuration.ns(930000))) assertThat(profile.size, `is`(5)) } } @Nested @DisplayName("BaseX 8.0 xmlplan") inner class BaseX80XmlPlan { private val responseEn = listOf( "", "Query Plan:", "<QueryPlan compiled=\"true\" updating=\"false\">", " <GFLWOR type=\"xs:anyAtomicType*\">", " <For type=\"xs:integer\" size=\"1\" name=\"\$n\" id=\"0\">", " <RangeSeq from=\"1\" to=\"10\" type=\"xs:integer+\" size=\"10\"/>", " </For>", " <Arith op=\"*\" type=\"xs:anyAtomicType?\">", " <Int type=\"xs:integer\" size=\"1\">2</Int>", " <FnSum name=\"sum\" type=\"xs:anyAtomicType?\">", " <Range type=\"xs:integer*\">", " <Int type=\"xs:integer\" size=\"1\">1</Int>", " <VarRef type=\"xs:integer\" size=\"1\" name=\"\$n\" id=\"0\"/>", " </Range>", " </FnSum>", " </Arith>", " </GFLWOR>", "</QueryPlan>", "", "Query executed in 110.41 ms." ).joinToString("\r\n") @Test @DisplayName("toBaseXInfo") fun info() { val info = responseEn.toBaseXInfo() val queryPlan = listOf( "<QueryPlan compiled=\"true\" updating=\"false\">", " <GFLWOR type=\"xs:anyAtomicType*\">", " <For type=\"xs:integer\" size=\"1\" name=\"\$n\" id=\"0\">", " <RangeSeq from=\"1\" to=\"10\" type=\"xs:integer+\" size=\"10\"/>", " </For>", " <Arith op=\"*\" type=\"xs:anyAtomicType?\">", " <Int type=\"xs:integer\" size=\"1\">2</Int>", " <FnSum name=\"sum\" type=\"xs:anyAtomicType?\">", " <Range type=\"xs:integer*\">", " <Int type=\"xs:integer\" size=\"1\">1</Int>", " <VarRef type=\"xs:integer\" size=\"1\" name=\"\$n\" id=\"0\"/>", " </Range>", " </FnSum>", " </Arith>", " </GFLWOR>", "</QueryPlan>" ).joinToString("\n") assertThat(info.size, `is`(2)) assertThat(info["Query Plan"], `is`(queryPlan)) assertThat(info["Total Time"], `is`(XsDuration.ns(110410000))) } } @Nested @DisplayName("BaseX 8.0 queryinfo and xmlplan") inner class BaseX80QueryInfoAndXmlPlan { private val responseEn = listOf( "", "Query Plan:", "<QueryPlan compiled=\"true\" updating=\"false\">", " <GFLWOR type=\"xs:anyAtomicType*\">", " <For type=\"xs:integer\" size=\"1\" name=\"\$n\" id=\"0\">", " <RangeSeq from=\"1\" to=\"10\" type=\"xs:integer+\" size=\"10\"/>", " </For>", " <Arith op=\"*\" type=\"xs:anyAtomicType?\">", " <Int type=\"xs:integer\" size=\"1\">2</Int>", " <FnSum name=\"sum\" type=\"xs:anyAtomicType?\">", " <Range type=\"xs:integer*\">", " <Int type=\"xs:integer\" size=\"1\">1</Int>", " <VarRef type=\"xs:integer\" size=\"1\" name=\"\$n\" id=\"0\"/>", " </Range>", " </FnSum>", " </Arith>", " </GFLWOR>", "</QueryPlan>", "", "Query:", "for \$n in 1 to 10 let \$v := fn:sum(1 to \$n) return 2 * \$v", "", "Compiling:", "- pre-evaluate range expression to range sequence: (1 to 10)", "- inline \$v_1", "", "Optimized Query:", "for \$n_0 in (1 to 10) return (2 * sum((1 to \$n_0)))", "", "Parsing: 788.89 ms", "Compiling: 63.72 ms", "Evaluating: 0.74 ms", "Printing: 1.59 ms", "Total Time: 854.94 ms", "", "Hit(s): 10 Items", "Updated: 0 Items", "Printed: 29 b", "Read Locking: (none)", "Write Locking: (none)", "", "Query executed in 854.94 ms." ).joinToString("\r\n") @Test @DisplayName("toBaseXInfo") fun info() { val info = responseEn.toBaseXInfo() val queryPlan = listOf( "<QueryPlan compiled=\"true\" updating=\"false\">", " <GFLWOR type=\"xs:anyAtomicType*\">", " <For type=\"xs:integer\" size=\"1\" name=\"\$n\" id=\"0\">", " <RangeSeq from=\"1\" to=\"10\" type=\"xs:integer+\" size=\"10\"/>", " </For>", " <Arith op=\"*\" type=\"xs:anyAtomicType?\">", " <Int type=\"xs:integer\" size=\"1\">2</Int>", " <FnSum name=\"sum\" type=\"xs:anyAtomicType?\">", " <Range type=\"xs:integer*\">", " <Int type=\"xs:integer\" size=\"1\">1</Int>", " <VarRef type=\"xs:integer\" size=\"1\" name=\"\$n\" id=\"0\"/>", " </Range>", " </FnSum>", " </Arith>", " </GFLWOR>", "</QueryPlan>" ).joinToString("\n") val compiling = listOf( "pre-evaluate range expression to range sequence: (1 to 10)", "inline \$v_1" ) assertThat(info.size, `is`(10)) assertThat(info["Query Plan"], `is`(queryPlan)) assertThat(info["Compilation"], `is`(compiling)) assertThat(info["Optimized Query"], `is`("for \$n_0 in (1 to 10) return (2 * sum((1 to \$n_0)))")) assertThat(info["Total Time"], `is`(XsDuration.ns(854940000))) assertThat(info["Hit(s)"], `is`("10 Items")) assertThat(info["Updated"], `is`("0 Items")) assertThat(info["Printed"], `is`("29 b")) assertThat(info["Read Locking"], `is`("(none)")) assertThat(info["Write Locking"], `is`("(none)")) val profile = info["Profile"] as HashMap<String, XsDuration> assertThat(profile["Total Time"], `is`(XsDuration.ns(854940000))) assertThat(profile["Parsing"], `is`(XsDuration.ns(788890000))) assertThat(profile["Compiling"], `is`(XsDuration.ns(63720000))) assertThat(profile["Evaluating"], `is`(XsDuration.ns(740000))) assertThat(profile["Printing"], `is`(XsDuration.ns(1590000))) assertThat(profile.size, `is`(5)) } } }
apache-2.0
2e35feea31e871d455c32daa16697616
38.511057
110
0.489771
3.994287
false
false
false
false
dhleong/ideavim
src/com/maddyhome/idea/vim/handler/MotionActionHandler.kt
1
7396
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * 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, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.handler import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.event.CaretEvent import com.intellij.openapi.editor.event.CaretListener import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.group.MotionGroup import com.maddyhome.idea.vim.helper.* /** * @author Alex Plate * * Base class for motion handlers. * @see [MotionActionHandler.SingleExecution] and [MotionActionHandler.ForEachCaret] */ sealed class MotionActionHandler : EditorActionHandlerBase.SingleExecution() { /** * Base class for motion handlers. * This handler executes an action for each caret. That means that if you have 5 carets, [getOffset] will be * called 5 times. * @see [MotionActionHandler.SingleExecution] for only one execution */ abstract class ForEachCaret : MotionActionHandler() { /** * This method should return new offset for [caret] * It executes once for each [caret]. That means that if you have 5 carets, [getOffset] will be * called 5 times. * The method executes only once it there is block selection. */ abstract fun getOffset(editor: Editor, caret: Caret, context: DataContext, count: Int, rawCount: Int, argument: Argument?): Int /** * This method is called before [getOffset] once for each [caret]. * The method executes only once it there is block selection. */ open fun preOffsetComputation(editor: Editor, caret: Caret, context: DataContext, cmd: Command): Boolean = true /** * This method is called after [getOffset], but before caret motion. * * The method executes for each caret, but only once it there is block selection. */ open fun preMove(editor: Editor, caret: Caret, context: DataContext, cmd: Command) {} /** * This method is called after [getOffset] and after caret motion. * * The method executes for each caret, but only once it there is block selection. */ open fun postMove(editor: Editor, caret: Caret, context: DataContext, cmd: Command) {} } /** * Base class for motion handlers. * This handler executes an action only once for all carets. That means that if you have 5 carets, * [getOffset] will be called 1 time. * @see [MotionActionHandler.ForEachCaret] for per-caret execution */ abstract class SingleExecution : MotionActionHandler() { /** * This method should return new offset for primary caret * It executes once for all carets. That means that if you have 5 carets, [getOffset] will be * called 1 time. */ abstract fun getOffset(editor: Editor, context: DataContext, count: Int, rawCount: Int, argument: Argument?): Int /** * This method is called before [getOffset]. * The method executes only once. */ open fun preOffsetComputation(editor: Editor, context: DataContext, cmd: Command): Boolean = true /** * This method is called after [getOffset], but before caret motion. * * The method executes only once. */ open fun preMove(editor: Editor, context: DataContext, cmd: Command) = Unit /** * This method is called after [getOffset] and after caret motion. * * The method executes only once it there is block selection. */ open fun postMove(editor: Editor, context: DataContext, cmd: Command) = Unit } final override fun execute(editor: Editor, context: DataContext, cmd: Command): Boolean { val blockSubmodeActive = editor.inBlockSubMode when (this) { is SingleExecution -> run { if (!preOffsetComputation(editor, context, cmd)) return@run var offset = getOffset(editor, context, cmd.count, cmd.rawCount, cmd.argument) if (offset >= 0) { if (CommandFlags.FLAG_SAVE_JUMP in cmd.flags) { VimPlugin.getMark().saveJumpLocation(editor) } if (!editor.mode.isEndAllowed) { offset = EditorHelper.normalizeOffset(editor, offset, false) } preMove(editor, context, cmd) MotionGroup.moveCaret(editor, editor.caretModel.primaryCaret, offset) postMove(editor, context, cmd) } } is ForEachCaret -> run { when { blockSubmodeActive || editor.caretModel.caretCount == 1 -> { val primaryCaret = editor.caretModel.primaryCaret doExecuteForEach(editor, primaryCaret, context, cmd) } else -> { try { editor.caretModel.addCaretListener(CaretMergingWatcher) editor.caretModel.runForEachCaret { caret -> doExecuteForEach(editor, caret, context, cmd) } } finally { editor.caretModel.removeCaretListener(CaretMergingWatcher) } } } } } return true } private fun doExecuteForEach(editor: Editor, caret: Caret, context: DataContext, cmd: Command) { this as ForEachCaret if (!preOffsetComputation(editor, caret, context, cmd)) return var offset = getOffset(editor, caret, context, cmd.count, cmd.rawCount, cmd.argument) if (offset >= 0) { if (CommandFlags.FLAG_SAVE_JUMP in cmd.flags) { VimPlugin.getMark().saveJumpLocation(editor) } if (!editor.mode.isEndAllowed) { offset = EditorHelper.normalizeOffset(editor, offset, false) } preMove(editor, caret, context, cmd) MotionGroup.moveCaret(editor, caret, offset) val postMoveCaret = if (editor.inBlockSubMode) editor.caretModel.primaryCaret else caret postMove(editor, postMoveCaret, context, cmd) } } private object CaretMergingWatcher : CaretListener { override fun caretRemoved(event: CaretEvent) { val editor = event.editor val caretToDelete = event.caret ?: return if (editor.inVisualMode) { for (caret in editor.caretModel.allCarets) { if (caretToDelete.selectionStart < caret.selectionEnd && caretToDelete.selectionStart >= caret.selectionStart || caretToDelete.selectionEnd <= caret.selectionEnd && caretToDelete.selectionEnd > caret.selectionStart) { // Okay, caret is being removed because of merging val vimSelectionStart = caretToDelete.vimSelectionStart caret.vimSelectionStart = vimSelectionStart } } } } } }
gpl-2.0
f8a4ce8a718ddfe1737644e0d2715d83
37.321244
131
0.680638
4.493317
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/exh/eh/EHentaiUpdateHelper.kt
1
7926
package exh.eh import android.content.Context import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.ChapterImpl import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaCategory import exh.metadata.metadata.EHentaiSearchMetadata import exh.metadata.metadata.base.getFlatMetadataForManga import rx.Observable import rx.Single import uy.kohesive.injekt.injectLazy import java.io.File data class ChapterChain(val manga: Manga, val chapters: List<Chapter>) class EHentaiUpdateHelper(context: Context) { val parentLookupTable = MemAutoFlushingLookupTable( File(context.filesDir, "exh-plt.maftable"), GalleryEntry.Serializer() ) private val db: DatabaseHelper by injectLazy() /** * @param chapters Cannot be an empty list! * * @return Triple<Accepted, Discarded, HasNew> */ fun findAcceptedRootAndDiscardOthers(sourceId: Long, chapters: List<Chapter>): Single<Triple<ChapterChain, List<ChapterChain>, Boolean>> { // Find other chains val chainsObservable = Observable.merge(chapters.map { chapter -> db.getChapters(chapter.url).asRxSingle().toObservable() }).toList().map { allChapters -> allChapters.flatMap { innerChapters -> innerChapters.map { it.manga_id!! } }.distinct() }.flatMap { mangaIds -> Observable.merge( mangaIds.map { mangaId -> Single.zip( db.getManga(mangaId).asRxSingle(), db.getChaptersByMangaId(mangaId).asRxSingle() ) { manga, chapters -> ChapterChain(manga, chapters) }.toObservable().filter { it.manga.source == sourceId } } ) }.toList() // Accept oldest chain val chainsWithAccepted = chainsObservable.map { chains -> val acceptedChain = chains.minBy { it.manga.id!! }!! acceptedChain to chains } return chainsWithAccepted.map { (accepted, chains) -> val toDiscard = chains.filter { it.manga.favorite && it.manga.id != accepted.manga.id } val chainsAsChapters = chains.flatMap { it.chapters } if(toDiscard.isNotEmpty()) { var new = false // Copy chain chapters to curChapters val newChapters = toDiscard .flatMap { chain -> val meta by lazy { db.getFlatMetadataForManga(chain.manga.id!!) .executeAsBlocking() ?.raise<EHentaiSearchMetadata>() } chain.chapters.map { chapter -> // Convert old style chapters to new style chapters if possible if(chapter.date_upload <= 0 && meta?.datePosted != null && meta?.title != null) { chapter.name = meta!!.title!! chapter.date_upload = meta!!.datePosted!! } chapter } } .fold(accepted.chapters) { curChapters, chapter -> val existing = curChapters.find { it.url == chapter.url } val newLastPageRead = chainsAsChapters.maxBy { it.last_page_read }?.last_page_read if (existing != null) { existing.read = existing.read || chapter.read existing.last_page_read = existing.last_page_read.coerceAtLeast(chapter.last_page_read) if(newLastPageRead != null && existing.last_page_read <= 0) { existing.last_page_read = newLastPageRead } existing.bookmark = existing.bookmark || chapter.bookmark curChapters } else if (chapter.date_upload > 0) { // Ignore chapters using the old system new = true curChapters + ChapterImpl().apply { manga_id = accepted.manga.id url = chapter.url name = chapter.name read = chapter.read bookmark = chapter.bookmark last_page_read = chapter.last_page_read if(newLastPageRead != null && last_page_read <= 0) { last_page_read = newLastPageRead } date_fetch = chapter.date_fetch date_upload = chapter.date_upload } } else curChapters } .filter { it.date_upload > 0 } // Ignore chapters using the old system (filter after to prevent dupes from insert) .sortedBy { it.date_upload } .apply { mapIndexed { index, chapter -> chapter.name = "v${index + 1}: " + chapter.name.substringAfter(" ") chapter.chapter_number = index + 1f chapter.source_order = lastIndex - index } } toDiscard.forEach { it.manga.favorite = false } accepted.manga.favorite = true val newAccepted = ChapterChain(accepted.manga, newChapters) val rootsToMutate = toDiscard + newAccepted db.inTransaction { // Apply changes to all manga db.insertMangas(rootsToMutate.map { it.manga }).executeAsBlocking() // Insert new chapters for accepted manga db.insertChapters(newAccepted.chapters).executeAsBlocking() // Copy categories from all chains to accepted manga val newCategories = rootsToMutate.flatMap { db.getCategoriesForManga(it.manga).executeAsBlocking() }.distinctBy { it.id }.map { MangaCategory.create(newAccepted.manga, it) } db.setMangaCategories(newCategories, rootsToMutate.map { it.manga }) } Triple(newAccepted, toDiscard, new) } else Triple(accepted, emptyList(), false) }.toSingle() } } data class GalleryEntry(val gId: String, val gToken: String) { class Serializer: MemAutoFlushingLookupTable.EntrySerializer<GalleryEntry> { /** * Serialize an entry as a String. */ override fun write(entry: GalleryEntry) = with(entry) { "$gId:$gToken" } /** * Read an entry from a String. */ override fun read(string: String): GalleryEntry { val colonIndex = string.indexOf(':') return GalleryEntry( string.substring(0, colonIndex), string.substring(colonIndex + 1, string.length) ) } } }
apache-2.0
862e0ed980d02c27d07c34b8da47e4e0
44.815029
142
0.489276
5.593507
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/util/Materials.kt
1
4010
package nl.sugcube.dirtyarrows.util import org.bukkit.Bukkit import org.bukkit.Material import org.bukkit.block.Block import org.bukkit.inventory.FurnaceRecipe import org.bukkit.inventory.ItemStack import kotlin.math.min import kotlin.random.Random /** * Maps each material to the item stack obtained when smelting this item. */ private val SMELT_RESULTS: Map<Material, ItemStack> = Bukkit.recipeIterator().asSequence() .mapNotNull { it as? FurnaceRecipe } .map { it.input.type to it.result } .toMap() /** * Get the item that is obtained when smelting this material. */ val Material.smeltedItem: ItemStack? get() = SMELT_RESULTS[this] /** * Whether the block can be broken by shears an drop their original block. * `false` in cases like wool, where the wool block can also be properly broken without shears. */ val Material.isShearable: Boolean get() = when (this) { Material.COBWEB, Material.DEAD_BUSH, Material.TALL_GRASS, Material.LILAC, Material.ROSE_BUSH, Material.SUNFLOWER, Material.LARGE_FERN, Material.PEONY, Material.OAK_LEAVES, Material.SPRUCE_LEAVES, Material.BIRCH_LEAVES, Material.JUNGLE_LEAVES, Material.ACACIA_LEAVES, Material.DARK_OAK_LEAVES, Material.TRIPWIRE, Material.VINE -> true else -> false } /** * Checks if this material is a log. */ fun Material.isLog(): Boolean = when (this) { Material.OAK_LOG, Material.SPRUCE_LOG, Material.BIRCH_LOG, Material.JUNGLE_LOG, Material.ACACIA_LOG, Material.DARK_OAK_LOG -> true else -> false } /** * Checks if this block is a log. */ fun Block.isLog() = type.isLog() /** * Get the items that should drop from this material, considering the fortune level. */ fun Material.fortuneDrops(level: Int = 0): Collection<ItemStack> { val amount = when (this) { Material.COAL_ORE, Material.DIAMOND_ORE, Material.EMERALD_ORE, Material.NETHER_QUARTZ_ORE -> oreFortuneCount(fortuneLevel = level, dropAmount = 1..1) Material.LAPIS_ORE -> oreFortuneCount(fortuneLevel = level, dropAmount = 4..9) Material.REDSTONE_ORE -> redstoneFortuneCount(fortuneLevel = level) Material.MELON -> melonFortuneCount(fortuneLevel = level) else -> 1 } val dropMaterial = when (this) { Material.IRON_ORE, Material.GOLD_ORE -> this Material.MELON -> Material.MELON else -> smeltedItem?.type ?: this } return if (this == Material.LAPIS_ORE) { listOf(ItemStack(Material.LAPIS_LAZULI, amount)) } else listOf(ItemStack(dropMaterial, amount)) } /** * Calculates a random amount of drops for coal, diamond, emerald, nether quartz, lapis lazuli ore inclding * the effects of fortune. * * @param fortuneLevel * The level of the fortune enchantment to consider (0 for no fortune). * @param dropAmount * The range containing the possible amount of base drops. */ fun oreFortuneCount(fortuneLevel: Int = 0, dropAmount: IntRange = 1..1): Int { val base = dropAmount.random() return when (fortuneLevel) { 1 -> if (Random.nextDouble() > 0.33) base else base * 2 2 -> if (Random.nextBoolean()) base else base * Random.nextInt(2, 4) 3 -> if (Random.nextDouble() > 0.6) base else base * Random.nextInt(2, 5) else -> base } } /** * Calculates a random amount of drops for redstone ore, including the effects of fortune. * * @param fortuneLevel * The level of the fortune enchantment to consider (0 for no fortune). */ fun redstoneFortuneCount(fortuneLevel: Int = 0) = 4 + Random.nextInt(0, fortuneLevel + 2) /** * Calculates a random amount of melon slices to drop from a melon block. * * @param fortuneLevel * The level of the fortune enchantment to consider (0 for no fortune). */ fun melonFortuneCount(fortuneLevel: Int = 0) = min(9, 3 + Random.nextInt(0, fortuneLevel + 4))
gpl-3.0
6d9f2d3f1b6eccaaa505945ad2cfbc49
31.609756
134
0.667581
3.655424
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/domain/chapter/interactor/SetDefaultChapterSettings.kt
1
1359
package eu.kanade.domain.chapter.interactor import eu.kanade.domain.library.service.LibraryPreferences import eu.kanade.domain.manga.interactor.GetFavorites import eu.kanade.domain.manga.interactor.SetMangaChapterFlags import eu.kanade.domain.manga.model.Manga import eu.kanade.tachiyomi.util.lang.withNonCancellableContext class SetMangaDefaultChapterFlags( private val libraryPreferences: LibraryPreferences, private val setMangaChapterFlags: SetMangaChapterFlags, private val getFavorites: GetFavorites, ) { suspend fun await(manga: Manga) { withNonCancellableContext { with(libraryPreferences) { setMangaChapterFlags.awaitSetAllFlags( mangaId = manga.id, unreadFilter = filterChapterByRead().get(), downloadedFilter = filterChapterByDownloaded().get(), bookmarkedFilter = filterChapterByBookmarked().get(), sortingMode = sortChapterBySourceOrNumber().get(), sortingDirection = sortChapterByAscendingOrDescending().get(), displayMode = displayChapterByNameOrNumber().get(), ) } } } suspend fun awaitAll() { withNonCancellableContext { getFavorites.await().forEach { await(it) } } } }
apache-2.0
d0be74ec13334431acf8a8786c926ff2
36.75
82
0.661516
4.978022
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseStepSize.kt
1
2150
package info.nightscout.androidaps.plugins.pump.common.defs import java.util.* enum class DoseStepSize(private val entries: Array<DoseStepSizeEntry>) { ComboBasal(arrayOf( DoseStepSizeEntry(0.0, 1.0, 0.01), DoseStepSizeEntry(1.0, 10.0, 0.05), DoseStepSizeEntry(10.0, Double.MAX_VALUE, 0.1))), InsightBolus(arrayOf( DoseStepSizeEntry(0.0, 2.0, 0.05), DoseStepSizeEntry(2.0, 5.0, 0.1), DoseStepSizeEntry(5.0, 10.0, 0.2), DoseStepSizeEntry(10.0, Double.MAX_VALUE, 0.5))), InsightBasal(arrayOf( DoseStepSizeEntry(0.0, 5.0, 0.01), DoseStepSizeEntry(5.0, Double.MAX_VALUE, 0.1))), MedtronicVeoBasal(arrayOf( DoseStepSizeEntry(0.0, 1.0, 0.025), DoseStepSizeEntry(1.0, 10.0, 0.05), DoseStepSizeEntry(10.0, Double.MAX_VALUE, 0.1))), YpsopumpBasal(arrayOf( DoseStepSizeEntry(0.0, 1.0, 0.01), DoseStepSizeEntry(1.0, 2.0, 0.02), DoseStepSizeEntry(2.0, 15.0, 0.1), DoseStepSizeEntry(15.0, 40.0, 0.5)) ); fun getStepSizeForAmount(amount: Double): Double { for (entry in entries) if (entry.from <= amount && entry.to > amount) return entry.value // should never come to this return entries[entries.size - 1].value } val description: String get() = StringBuilder().also { sb -> var first = true for (entry in entries) { if (first) first = false else sb.append(", ") sb.append(String.format(Locale.ENGLISH, "%.3f", entry.value)) .append(" {") .append(String.format(Locale.ENGLISH, "%.3f", entry.from)) .append("-") if (entry.to == Double.MAX_VALUE) sb.append("~}") else sb.append(String.format(Locale.ENGLISH, "%.3f", entry.to)).append("}") } }.toString() // to = this value is not included, but would actually mean <, so for rates between 0.025-0.975 u/h, we would have [from=0, to=10] internal class DoseStepSizeEntry(var from: Double, var to: Double, var value: Double) }
agpl-3.0
0df569491aa74a86959bed4f10ac8f5b
37.410714
134
0.587442
3.338509
false
false
false
false
Heiner1/AndroidAPS
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BolusWizardDTO.kt
1
1673
package info.nightscout.androidaps.plugins.pump.medtronic.data.dto import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil import java.util.* /** * Created by andy on 18.05.15. */ class BolusWizardDTO : PumpTimeStampedRecord() { // bloodGlucose and bgTarets are in mg/dL var bloodGlucose = 0 // mg/dL var carbs = 0 var chUnit = "g" var carbRatio = 0.0f var insulinSensitivity = 0.0f var bgTargetLow = 0 var bgTargetHigh = 0 var bolusTotal = 0.0f var correctionEstimate = 0.0f var foodEstimate = 0.0f var unabsorbedInsulin = 0.0f// val value: String get() = String.format(Locale.ENGLISH, "BG=%d;CH=%d;CH_UNIT=%s;CH_INS_RATIO=%5.3f;BG_INS_RATIO=%5.3f;" + "BG_TARGET_LOW=%d;BG_TARGET_HIGH=%d;BOLUS_TOTAL=%5.3f;" + "BOLUS_CORRECTION=%5.3f;BOLUS_FOOD=%5.3f;UNABSORBED_INSULIN=%5.3f", // bloodGlucose, carbs, chUnit, carbRatio, insulinSensitivity, bgTargetLow, // bgTargetHigh, bolusTotal, correctionEstimate, foodEstimate, unabsorbedInsulin) // // val displayableValue: String get() = String.format(Locale.ENGLISH, "Bg=%d, CH=%d %s, Ch/Ins Ratio=%5.3f, Bg/Ins Ratio=%5.3f;" + "Bg Target(L/H)=%d/%d, Bolus: Total=%5.3f, " + "Correction=%5.3f, Food=%5.3f, IOB=%5.3f", // bloodGlucose, carbs, chUnit, carbRatio, insulinSensitivity, bgTargetLow, // bgTargetHigh, bolusTotal, correctionEstimate, foodEstimate, unabsorbedInsulin) override fun toString(): String { return "BolusWizardDTO [dateTime=" + DateTimeUtil.toString(atechDateTime) + ", " + value + "]" } }
agpl-3.0
646c8737b1379268e99686645719e1bf
37.906977
109
0.643156
3.144737
false
false
false
false
square/wire
wire-library/wire-grpc-server-generator/src/test/golden/MethodDescriptor.kt
1
1067
package routeguide import io.grpc.MethodDescriptor import kotlin.jvm.Volatile public class RouteGuideWireGrpc { @Volatile private var getGetFeatureMethod: MethodDescriptor<Point, Feature>? = null public fun getGetFeatureMethod(): MethodDescriptor<Point, Feature> { var result: MethodDescriptor<Point, Feature>? = getGetFeatureMethod if (result == null) { synchronized(RouteGuideWireGrpc::class) { result = getGetFeatureMethod if (result == null) { getGetFeatureMethod = MethodDescriptor.newBuilder<Point, Feature>() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( MethodDescriptor.generateFullMethodName( "routeguide.RouteGuide", "GetFeature" ) ) .setSampledToLocalTracing(true) .setRequestMarshaller(RouteGuideImplBase.PointMarshaller()) .setResponseMarshaller(RouteGuideImplBase.FeatureMarshaller()) .build() } } } return getGetFeatureMethod!! } }
apache-2.0
b0bc48b9e7beb6954212851f16c7bfae
32.34375
77
0.66448
5.416244
false
false
false
false
realm/realm-java
realm-transformer/src/main/kotlin/io/realm/transformer/ext/CtClassExt.kt
1
2628
/* * Copyright 2018 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm.transformer.ext import javassist.CtClass import javassist.NotFoundException import javassist.bytecode.ClassFile /** * Returns {@code true} if 'clazz' is considered a subtype of 'superType'. * * This function is different than {@link CtClass#subtypeOf(CtClass)} in the sense * that it will never crash even if classes are missing from the class pool, instead * it will just return {@code false}. * * This e.g. happens with RxJava classes which are optional, but JavaAssist will try * to load them and then crash. * * @param typeToCheckAgainst the type we want to check against * @return `true` if `clazz` is a subtype of `typeToCheckAgainst`, `false` otherwise. */ fun CtClass.safeSubtypeOf(typeToCheckAgainst: CtClass): Boolean { val typeToCheckAgainstQualifiedName: String = typeToCheckAgainst.name if (this == typeToCheckAgainst || this.name.equals(typeToCheckAgainstQualifiedName)) { return true } val file: ClassFile = this.classFile2 // Check direct super class val superName: String? = file.superclass if (superName.equals(typeToCheckAgainstQualifiedName)) { return true } // Check direct interfaces val ifs: Array<String> = file.interfaces ifs.forEach { if (it == typeToCheckAgainstQualifiedName) { return true } } // Check other inherited super classes if (superName != null) { var nextSuper: CtClass try { nextSuper = classPool.get(superName) if (nextSuper.safeSubtypeOf(typeToCheckAgainst)) { return true } } catch (ignored: NotFoundException) { } } // Check other inherited interfaces ifs.forEach { interfaceName -> try { val interfaceClass: CtClass = classPool.get(interfaceName) if (interfaceClass.safeSubtypeOf(typeToCheckAgainst)) { return true } } catch (ignored: NotFoundException) { } } return false }
apache-2.0
17b3f7142fe175a86f5a5d516c47f242
31.04878
90
0.678082
4.477002
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/syntax/test/TestSyntaxLexer.kt
1
940
package com.bajdcc.LALR1.syntax.test import com.bajdcc.LALR1.syntax.lexer.SyntaxLexer import com.bajdcc.LALR1.syntax.token.Token import com.bajdcc.LALR1.syntax.token.TokenType import com.bajdcc.util.lexer.error.RegexException import java.util.* object TestSyntaxLexer { @JvmStatic fun main(args: Array<String>) { try { val scanner = Scanner(System.`in`) val str = scanner.nextLine() val lexer = SyntaxLexer() lexer.context = str var token: Token? while (true) { token = lexer.nextToken() if (token!!.type === TokenType.EOF) { break } println(token!!.toString()) } scanner.close() } catch (e: RegexException) { System.err.println(e.position.toString() + "," + e.message) e.printStackTrace() } } }
mit
5ffcbf57a7bae459549b98d733592147
27.484848
71
0.552128
4.292237
false
true
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/export/SettingsExportViewModel.kt
2
7861
package com.fsck.k9.ui.settings.export import android.content.Context import android.net.Uri import android.os.Bundle import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.fsck.k9.Preferences import com.fsck.k9.helper.SingleLiveEvent import com.fsck.k9.helper.measureRealtimeMillis import com.fsck.k9.preferences.SettingsExporter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext private typealias AccountUuid = String private typealias AccountNumber = Int class SettingsExportViewModel( val context: Context, val preferences: Preferences, val settingsExporter: SettingsExporter ) : ViewModel() { private val uiModelLiveData = MutableLiveData<SettingsExportUiModel>() private val actionLiveData = SingleLiveEvent<Action>() private val uiModel = SettingsExportUiModel() private var accountsMap: Map<AccountNumber, AccountUuid> = emptyMap() private var savedSelection: SavedListItemSelection? = null private var contentUri: Uri? = null private val includeGeneralSettings: Boolean get() { return savedSelection?.includeGeneralSettings ?: uiModel.settingsList.first { it is SettingsListItem.GeneralSettings }.selected } private val selectedAccounts: Set<AccountUuid> get() { return savedSelection?.selectedAccountUuids ?: uiModel.settingsList.asSequence() .filterIsInstance<SettingsListItem.Account>() .filter { it.selected } .map { accountsMap[it.accountNumber] ?: error("Unknown account number: ${it.accountNumber}") } .toSet() } fun getActionEvents(): LiveData<Action> = actionLiveData fun getUiModel(): LiveData<SettingsExportUiModel> { if (uiModelLiveData.value == null) { uiModelLiveData.value = uiModel viewModelScope.launch { val accounts = withContext(Dispatchers.IO) { preferences.accounts } accountsMap = accounts.map { it.accountNumber to it.uuid }.toMap() val listItems = savedSelection.let { savedState -> val generalSettings = SettingsListItem.GeneralSettings.apply { selected = savedState == null || savedState.includeGeneralSettings } val accountListItems = accounts.map { account -> SettingsListItem.Account(account.accountNumber, account.displayName, account.email).apply { selected = savedState == null || account.uuid in savedState.selectedAccountUuids } } listOf(generalSettings) + accountListItems } updateUiModel { initializeSettingsList(listItems) } } } return uiModelLiveData } fun initializeFromSavedState(savedInstanceState: Bundle) { savedSelection = SavedListItemSelection( includeGeneralSettings = savedInstanceState.getBoolean(STATE_INCLUDE_GENERAL_SETTINGS), selectedAccountUuids = savedInstanceState.getStringArray(STATE_SELECTED_ACCOUNTS)?.toSet() ?: emptySet() ) uiModel.apply { isSettingsListEnabled = savedInstanceState.getBoolean(STATE_SETTINGS_LIST_ENABLED) exportButton = ButtonState.valueOf( savedInstanceState.getString(STATE_EXPORT_BUTTON, ButtonState.DISABLED.name) ) isShareButtonVisible = savedInstanceState.getBoolean(STATE_SHARE_BUTTON_VISIBLE) isProgressVisible = savedInstanceState.getBoolean(STATE_PROGRESS_VISIBLE) statusText = StatusText.valueOf(savedInstanceState.getString(STATE_STATUS_TEXT, StatusText.HIDDEN.name)) } contentUri = savedInstanceState.getParcelable(STATE_CONTENT_URI) } fun onExportButtonClicked() { updateUiModel { disableExportButton() } startExportSettings() } fun onShareButtonClicked() { sendActionEvent(Action.ShareDocument(contentUri!!, SETTINGS_MIME_TYPE)) } private fun startExportSettings() { val exportFileName = settingsExporter.generateDatedExportFileName() sendActionEvent(Action.PickDocument(exportFileName, SETTINGS_MIME_TYPE)) } fun onDocumentPicked(contentUri: Uri) { this.contentUri = contentUri updateUiModel { showProgress() } val includeGeneralSettings = this.includeGeneralSettings val selectedAccounts = this.selectedAccounts viewModelScope.launch { try { val elapsed = measureRealtimeMillis { withContext(Dispatchers.IO) { settingsExporter.exportToUri(includeGeneralSettings, selectedAccounts, contentUri) } } if (elapsed < MIN_PROGRESS_DURATION) { delay(MIN_PROGRESS_DURATION - elapsed) } updateUiModel { showSuccessText() } } catch (e: Exception) { updateUiModel { showFailureText() } } } } fun onDocumentPickCanceled() { updateUiModel { enableExportButton() } } fun saveInstanceState(outState: Bundle) { outState.putBoolean(STATE_SETTINGS_LIST_ENABLED, uiModel.isSettingsListEnabled) outState.putString(STATE_EXPORT_BUTTON, uiModel.exportButton.name) outState.putBoolean(STATE_SHARE_BUTTON_VISIBLE, uiModel.isShareButtonVisible) outState.putBoolean(STATE_PROGRESS_VISIBLE, uiModel.isProgressVisible) outState.putString(STATE_STATUS_TEXT, uiModel.statusText.name) outState.putBoolean(STATE_INCLUDE_GENERAL_SETTINGS, includeGeneralSettings) outState.putStringArray(STATE_SELECTED_ACCOUNTS, selectedAccounts.toTypedArray()) outState.putParcelable(STATE_CONTENT_URI, contentUri) } fun onSettingsListItemSelected(position: Int, isSelected: Boolean) { savedSelection = null updateUiModel { setSettingsListItemSelection(position, isSelected) } } private fun updateUiModel(block: SettingsExportUiModel.() -> Unit) { uiModel.block() uiModelLiveData.value = uiModel } private fun sendActionEvent(action: Action) { actionLiveData.value = action } companion object { private const val MIN_PROGRESS_DURATION = 1000L private const val SETTINGS_MIME_TYPE = "application/octet-stream" private const val STATE_SETTINGS_LIST_ENABLED = "settingsListEnabled" private const val STATE_EXPORT_BUTTON = "exportButton" private const val STATE_SHARE_BUTTON_VISIBLE = "shareButtonVisible" private const val STATE_PROGRESS_VISIBLE = "progressVisible" private const val STATE_STATUS_TEXT = "statusText" private const val STATE_INCLUDE_GENERAL_SETTINGS = "includeGeneralSettings" private const val STATE_SELECTED_ACCOUNTS = "selectedAccounts" private const val STATE_CONTENT_URI = "contentUri" } } sealed class Action { class PickDocument(val fileNameSuggestion: String, val mimeType: String) : Action() class ShareDocument(val contentUri: Uri, val mimeType: String) : Action() } private data class SavedListItemSelection( val includeGeneralSettings: Boolean, val selectedAccountUuids: Set<AccountUuid> )
apache-2.0
0cdd96dbb1f3cb3b46e1eb83968adb61
35.562791
116
0.656151
5.358555
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/base/fir/analysis-api-providers/test/org/jetbrains/kotlin/idea/fir/analysis/providers/trackers/AbstractProjectWideOutOfBlockKotlinModificationTrackerTest.kt
4
1775
// 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.fir.analysis.providers.trackers import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiDocumentManager import junit.framework.Assert import org.jetbrains.kotlin.analysis.providers.createProjectWideOutOfBlockModificationTracker import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import java.io.File abstract class AbstractProjectWideOutOfBlockKotlinModificationTrackerTest : KotlinLightCodeInsightFixtureTestCase() { override fun isFirPlugin(): Boolean = true fun doTest(path: String) { val testDataFile = File(path) val fileText = FileUtil.loadFile(testDataFile) myFixture.configureByText(testDataFile.name, fileText) val textToType = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// TYPE:") ?: DEFAULT_TEXT_TO_TYPE val outOfBlock = InTextDirectivesUtils.getPrefixedBoolean(fileText, "// OUT_OF_BLOCK:") ?: error("Please, specify should out of block change happen or not by `// OUT_OF_BLOCK:` directive") val tracker = project.createProjectWideOutOfBlockModificationTracker() val initialModificationCount = tracker.modificationCount myFixture.type(textToType) PsiDocumentManager.getInstance(project).commitAllDocuments() val afterTypingModificationCount = tracker.modificationCount Assert.assertEquals(outOfBlock, initialModificationCount != afterTypingModificationCount) } companion object { const val DEFAULT_TEXT_TO_TYPE = "hello" } }
apache-2.0
df275eff03d791f1ba28cc8888192316
51.235294
158
0.774648
5.174927
false
true
false
false
fitermay/intellij-community
plugins/settings-repository/src/IcsUrlBuilder.kt
2
1622
/* * 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 org.jetbrains.settingsRepository import com.intellij.openapi.components.RoamingType import com.intellij.openapi.util.SystemInfo internal const val PROJECTS_DIR_NAME: String = "_projects/" private val osPrefixes = arrayOf("_mac/", "_windows/", "_linux/", "_freebsd/", "_unix/") internal fun getOsFolderName() = when { SystemInfo.isMac -> "_mac" SystemInfo.isWindows -> "_windows" SystemInfo.isLinux -> "_linux" SystemInfo.isFreeBSD -> "_freebsd" SystemInfo.isUnix -> "_unix" else -> "_unknown" } internal fun toRepositoryPath(path: String, roamingType: RoamingType, projectKey: String? = null): String { fun String.osIfNeed() = if (roamingType == RoamingType.PER_OS) "${getOsFolderName()}/$this" else this return if (projectKey == null) path.osIfNeed() else "$PROJECTS_DIR_NAME$projectKey/$path" } internal fun toIdeaPath(path: String): String { for (prefix in osPrefixes) { val result = path.removePrefix(prefix) if (result !== path) { return result } } return path }
apache-2.0
7bfd5d2bb997458fa33227b6f2f8c48a
33.531915
107
0.717633
3.995074
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/ide/inspections/ApproxConstantInspection.kt
1
2964
package org.rust.ide.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import org.rust.lang.core.psi.RustLitExpr import org.rust.lang.core.psi.RustVisitor class ApproxConstantInspection : LocalInspectionTool() { override fun getGroupDisplayName() = "Rust" override fun getDisplayName() = "Approximate Constants" override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : RustVisitor() { override fun visitLitExpr(o: RustLitExpr) { analyzeLiteral(o.floatLiteral ?: return, holder) } } } private fun analyzeLiteral(psiElement: PsiElement, holder: ProblemsHolder) { val text = psiElement.text .filter { it != '_' } .removeSuffix("f32") .removeSuffix("f64") // Parse the float literal and skip inspection on failure val value = try { text.toDouble() } catch (e: NumberFormatException) { return } val constant = KNOWN_CONSTS.find { it.matches(value) } ?: return val type = if (psiElement.text.endsWith("f32")) "f32" else "f64" holder.registerProblem(psiElement, type, constant) } companion object { val KNOWN_CONSTS = listOf( PredefinedConstant("E", Math.E, 4), PredefinedConstant("FRAC_1_PI", 1.0 / Math.PI, 4), PredefinedConstant("FRAC_1_SQRT_2", 1.0 / Math.sqrt(2.0), 5), PredefinedConstant("FRAC_2_PI", 2.0 / Math.PI, 5), PredefinedConstant("FRAC_2_SQRT_PI", 2.0 / Math.sqrt(Math.PI), 5), PredefinedConstant("FRAC_PI_2", Math.PI / 2.0, 5), PredefinedConstant("FRAC_PI_3", Math.PI / 3.0, 5), PredefinedConstant("FRAC_PI_4", Math.PI / 4.0, 5), PredefinedConstant("FRAC_PI_6", Math.PI / 6.0, 5), PredefinedConstant("FRAC_PI_8", Math.PI / 8.0, 5), PredefinedConstant("LN_10", Math.log(10.0), 5), PredefinedConstant("LN_2", Math.log(2.0), 5), PredefinedConstant("LOG10_E", Math.log10(Math.E), 5), PredefinedConstant("LOG2_E", Math.log(Math.E) / Math.log(2.0), 5), PredefinedConstant("PI", Math.PI, 3), PredefinedConstant("SQRT_2", Math.sqrt(2.0), 5) ) } } data class PredefinedConstant(val name: String, val value: Double, val minDigits: Int) { val accuracy = Math.pow(0.1, minDigits.toDouble()) fun matches(value: Double): Boolean { return Math.abs(value - this.value) < accuracy } } private fun ProblemsHolder.registerProblem(element: PsiElement, type: String, constant: PredefinedConstant) { registerProblem(element, "Approximate value of `std::$type::consts::${constant.name}` found. Consider using it directly.") }
mit
b5d38a6fd1afd931ff26cc6ac482bd99
38.52
126
0.629892
3.869452
false
false
false
false
mdaniel/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/data/MiniDetailsGetter.kt
1
7218
// 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.vcs.log.data import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Consumer import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.VcsLogObjectsFactory import com.intellij.vcs.log.VcsLogProvider import com.intellij.vcs.log.data.index.IndexedDetails import com.intellij.vcs.log.data.index.VcsLogIndex import com.intellij.vcs.log.runInEdt import com.intellij.vcs.log.util.SequentialLimitedLifoExecutor import it.unimi.dsi.fastutil.ints.* import java.awt.EventQueue class MiniDetailsGetter internal constructor(project: Project, storage: VcsLogStorage, logProviders: Map<VirtualFile, VcsLogProvider>, private val topCommitsDetailsCache: TopCommitsCache, private val index: VcsLogIndex, parentDisposable: Disposable) : AbstractDataGetter<VcsCommitMetadata>(storage, logProviders, parentDisposable) { private val factory = project.getService(VcsLogObjectsFactory::class.java) private val cache = Caffeine.newBuilder().maximumSize(10000).build<Int, VcsCommitMetadata>() private val loader = SequentialLimitedLifoExecutor(this, MAX_LOADING_TASKS) { task: TaskDescriptor -> doLoadCommitsData(task.commits, this::saveInCache) notifyLoaded() } /** * The sequence number of the current "loading" task. */ private var currentTaskIndex: Long = 0 private val loadingFinishedListeners = ArrayList<Runnable>() override fun getCommitData(commit: Int): VcsCommitMetadata { return getCommitData(commit, emptySet()) } fun getCommitData(commit: Int, commitsToLoad: Iterable<Int>): VcsCommitMetadata { if (!EventQueue.isDispatchThread()) { thisLogger().assertTrue(commitsToLoad.none(), "Requesting loading commits in background thread is not supported.") return cache.getIfPresent(commit) ?: return createPlaceholderCommit(commit, 0 /*not used as this commit is not cached*/) } val details = getCommitDataIfAvailable(commit) if (details != null) return details val toLoad = IntOpenHashSet(commitsToLoad.iterator()) val taskNumber = currentTaskIndex++ toLoad.forEach(IntConsumer { cacheCommit(it, taskNumber) }) loader.queue(TaskDescriptor(toLoad)) return cache.getIfPresent(commit) ?: createPlaceholderCommit(commit, taskNumber) } override fun getCommitDataIfAvailable(commit: Int): VcsCommitMetadata? { if (!EventQueue.isDispatchThread()) { return cache.getIfPresent(commit) ?: topCommitsDetailsCache[commit] } val details = cache.getIfPresent(commit) if (details != null) { if (details is LoadingDetailsImpl) { if (details.loadingTaskIndex <= currentTaskIndex - MAX_LOADING_TASKS) { // don't let old "loading" requests stay in the cache forever cache.asMap().remove(commit, details) return null } } return details } return topCommitsDetailsCache[commit] } override fun getCommitDataIfAvailable(commits: List<Int>): Int2ObjectMap<VcsCommitMetadata> { val detailsFromCache = commits.associateNotNull { val details = getCommitDataIfAvailable(it) if (details is LoadingDetails) { return@associateNotNull null } details } return detailsFromCache } override fun saveInCache(commit: Int, details: VcsCommitMetadata) = cache.put(commit, details) @RequiresEdt private fun cacheCommit(commitId: Int, taskNumber: Long) { // fill the cache with temporary "Loading" values to avoid producing queries for each commit that has not been cached yet, // even if it will be loaded within a previous query if (cache.getIfPresent(commitId) == null) { cache.put(commitId, createPlaceholderCommit(commitId, taskNumber)) } } @RequiresEdt override fun cacheCommits(commits: IntOpenHashSet) { val taskNumber = currentTaskIndex++ commits.forEach(IntConsumer { commit -> cacheCommit(commit, taskNumber) }) } @RequiresBackgroundThread @Throws(VcsException::class) override fun doLoadCommitsData(commits: IntSet, consumer: Consumer<in VcsCommitMetadata>) { val dataGetter = index.dataGetter if (dataGetter == null) { super.doLoadCommitsData(commits, consumer) return } val notIndexed = IntOpenHashSet() commits.forEach(IntConsumer { commit: Int -> val metadata = IndexedDetails.createMetadata(commit, dataGetter, storage, factory) if (metadata == null) { notIndexed.add(commit) } else { consumer.consume(metadata) } }) if (!notIndexed.isEmpty()) { super.doLoadCommitsData(notIndexed, consumer) } } @RequiresBackgroundThread @Throws(VcsException::class) override fun doLoadCommitsDataFromProvider(logProvider: VcsLogProvider, root: VirtualFile, hashes: List<String>, consumer: Consumer<in VcsCommitMetadata>) { logProvider.readMetadata(root, hashes, consumer) } private fun createPlaceholderCommit(commit: Int, taskNumber: Long): VcsCommitMetadata { val dataGetter = index.dataGetter return if (dataGetter != null && Registry.`is`("vcs.log.use.indexed.details")) { IndexedDetails(dataGetter, storage, commit, taskNumber) } else { LoadingDetailsImpl(storage, commit, taskNumber) } } /** * This listener will be notified when any details loading process finishes. * The notification will happen in the EDT. */ fun addDetailsLoadedListener(runnable: Runnable) { loadingFinishedListeners.add(runnable) } fun removeDetailsLoadedListener(runnable: Runnable) { loadingFinishedListeners.remove(runnable) } override fun notifyLoaded() { runInEdt(disposableFlag) { for (loadingFinishedListener in loadingFinishedListeners) { loadingFinishedListener.run() } } } override fun dispose() { loadingFinishedListeners.clear() } private class TaskDescriptor(val commits: IntSet) companion object { private const val MAX_LOADING_TASKS = 10 private inline fun <V> Iterable<Int>.associateNotNull(transform: (Int) -> V?): Int2ObjectMap<V> { val result = Int2ObjectOpenHashMap<V>() for (element in this) { val value = transform(element) ?: continue result[element] = value } return result } } }
apache-2.0
ab310bbd57f5cbc5ad2b36fdded56d99
36.598958
126
0.699086
4.75181
false
false
false
false
mdaniel/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/WorkspaceModelTopics.kt
1
7074
// 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.ide import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.EDT import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.util.containers.ContainerUtil import com.intellij.util.messages.MessageBus import com.intellij.util.messages.MessageBusConnection import com.intellij.util.messages.Topic import com.intellij.workspaceModel.storage.VersionedStorageChange import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.util.* interface WorkspaceModelChangeListener : EventListener { @JvmDefault fun beforeChanged(event: VersionedStorageChange) {} @JvmDefault fun changed(event: VersionedStorageChange) {} } /** * Topics to subscribe to Workspace changes * * Please use [subscribeImmediately] and [subscribeAfterModuleLoading] to subscribe to changes */ class WorkspaceModelTopics : Disposable { companion object { /** Please use [subscribeImmediately] and [subscribeAfterModuleLoading] to subscribe to changes */ @Topic.ProjectLevel private val CHANGED = Topic(WorkspaceModelChangeListener::class.java, Topic.BroadcastDirection.NONE, true) @Topic.ProjectLevel private val MODULE_BRIDGE_INITIALIZER = Topic(WorkspaceModelChangeListener::class.java, Topic.BroadcastDirection.NONE, true) @Topic.ProjectLevel private val PROJECT_LIBS_INITIALIZER = Topic(WorkspaceModelChangeListener::class.java, Topic.BroadcastDirection.NONE, true) @JvmStatic fun getInstance(project: Project): WorkspaceModelTopics = project.service() } private val allEventsForModuleBridge = ContainerUtil.createConcurrentList<EventsDispatcher>() private val allEvents = ContainerUtil.createConcurrentList<EventsDispatcher>() private var sendToQueue = true var modulesAreLoaded = false /** * Subscribe to topic and start to receive changes immediately. * * Topic is project-level only without broadcasting - connection expected to be to project message bus only. */ fun subscribeImmediately(connection: MessageBusConnection, listener: WorkspaceModelChangeListener) { connection.subscribe(CHANGED, listener) } /** * Subscribe to the topic and start to receive changes only *after* all the modules get loaded. * All the events that will be fired before the modules loading, will be collected to the queue. After the modules are loaded, all events * from the queue will be dispatched to listener under the write action and the further events will be dispatched to listener * without passing to event queue. * * Topic is project-level only without broadcasting - connection expected to be to project message bus only. */ fun subscribeAfterModuleLoading(connection: MessageBusConnection, listener: WorkspaceModelChangeListener) { if (!sendToQueue) { subscribeImmediately(connection, listener) } else { val queue = EventsDispatcher(listener) allEvents += queue subscribeImmediately(connection, queue) } } /** * For internal use only */ fun subscribeProjectLibsInitializer(connection: MessageBusConnection, listener: WorkspaceModelChangeListener) { connection.subscribe(PROJECT_LIBS_INITIALIZER, listener) } /** * Internal use only */ fun subscribeModuleBridgeInitializer(connection: MessageBusConnection, listener: WorkspaceModelChangeListener) { if (!sendToQueue) { connection.subscribe(MODULE_BRIDGE_INITIALIZER, listener) } else { val queue = EventsDispatcher(listener) allEventsForModuleBridge += queue connection.subscribe(MODULE_BRIDGE_INITIALIZER, queue) } } fun syncProjectLibs(messageBus: MessageBus): WorkspaceModelChangeListener = messageBus.syncPublisher(PROJECT_LIBS_INITIALIZER) fun syncModuleBridge(messageBus: MessageBus): WorkspaceModelChangeListener = messageBus.syncPublisher(MODULE_BRIDGE_INITIALIZER) fun syncPublisher(messageBus: MessageBus): WorkspaceModelChangeListener = messageBus.syncPublisher(CHANGED) suspend fun notifyModulesAreLoaded() { val activity = StartUpMeasurer.startActivity("postponed events sending", ActivityCategory.DEFAULT) sendToQueue = false if (allEvents.isNotEmpty() && allEvents.any { it.events.isNotEmpty() }) { val activityInQueue = activity.startChild("events sending (in queue)") val application = ApplicationManager.getApplication() withContext(Dispatchers.EDT) { application.runWriteAction { val innerActivity = activityInQueue.endAndStart("events sending") allEvents.forEach { queue -> queue.collectToQueue = false queue.events.forEach { (isBefore, event) -> if (isBefore) queue.originalListener.beforeChanged(event) else queue.originalListener.changed(event) } queue.events.clear() } innerActivity.end() } } } else { allEvents.forEach { queue -> queue.collectToQueue = false } } allEvents.clear() if (allEventsForModuleBridge.isNotEmpty() && allEventsForModuleBridge.any { it.events.isNotEmpty() }) { val activityInQueue = activity.startChild("events sending (in queue first)") val application = ApplicationManager.getApplication() withContext(Dispatchers.EDT) { application.runWriteAction { val innerActivity = activityInQueue.endAndStart("events sending first") allEventsForModuleBridge.forEach { queue -> queue.collectToQueue = false queue.events.forEach { (isBefore, event) -> if (isBefore) queue.originalListener.beforeChanged(event) else queue.originalListener.changed(event) } queue.events.clear() } innerActivity.end() } } } else { allEventsForModuleBridge.forEach { queue -> queue.collectToQueue = false } } allEventsForModuleBridge.clear() modulesAreLoaded = true activity.end() } private class EventsDispatcher(val originalListener: WorkspaceModelChangeListener) : WorkspaceModelChangeListener { val events = mutableListOf<Pair<Boolean, VersionedStorageChange>>() var collectToQueue = true override fun beforeChanged(event: VersionedStorageChange) { if (collectToQueue) { events += true to event } else { originalListener.beforeChanged(event) } } override fun changed(event: VersionedStorageChange) { if (collectToQueue) { events += false to event } else { originalListener.changed(event) } } } override fun dispose() { allEvents.forEach { it.events.clear() } allEvents.clear() } }
apache-2.0
a938e137f52b1b83f2ddf5350550d268
36.828877
139
0.729149
5.056469
false
false
false
false
MarcBob/StickMan
StickMan/app/src/main/kotlin/marmor/com/stickman/StickMan.kt
1
6230
package marmor.com.stickman import android.graphics.Color import android.graphics.Paint import android.graphics.PointF import android.util.Log import android.view.MotionEvent import android.view.SurfaceHolder import android.view.View import java.util.* public class StickMan(var surfaceHolder: SurfaceHolder) : View.OnTouchListener { private val SELECTION_DISTANCE: Float = 100f private val position = PointF(0f, 0f) public var scaleFactor: Float = 1f public lateinit var leftForeArm: Limb public lateinit var leftUpperArm: Limb public lateinit var rightForeArm: Limb public lateinit var rightUpperArm: Limb public lateinit var torso: Limb public lateinit var head: Limb public lateinit var leftUpperLeg: Limb public lateinit var leftLowerLeg: Limb public lateinit var rightUpperLeg: Limb public lateinit var rightLowerLeg: Limb public lateinit var limbs: Array<Limb> public var joints: ArrayList<Joint> = ArrayList() public val rightElbow: Joint get() = rightUpperArm.endJoint public val rightKnee: Joint get() = rightUpperLeg.endJoint public val leftElbow: Joint get() = leftUpperArm.endJoint public val leftKnee: Joint get() = leftUpperLeg.endJoint private var selectedJoint: Joint? = null public fun addJoints(vararg joints: Joint) { for (newJoint in joints) this.joints.add(newJoint) } public fun turnDirection(direction: Direction) { when(direction){ Direction.FRONT -> { rightKnee.angleSwitcher = 1 rightElbow.angleSwitcher = -1 leftKnee.angleSwitcher = -1 leftElbow.angleSwitcher = 1 } Direction.LEFT -> { rightKnee.angleSwitcher = -1 rightElbow.angleSwitcher = 1 leftKnee.angleSwitcher = -1 leftElbow.angleSwitcher = 1 } Direction.RIGHT -> { rightKnee.angleSwitcher = 1 rightElbow.angleSwitcher = -1 leftKnee.angleSwitcher = 1 leftElbow.angleSwitcher = -1 } } } public fun moveTo(x: Float, y: Float) { val deltaX = x - position.x val deltaY = y - position.y createLimbArray() for(joint in joints){ joint.position.x += deltaX joint.position.y += deltaY } } override fun onTouch(v: View?, event: MotionEvent): Boolean { val x = event.x val y = event.y when(event.action) { MotionEvent.ACTION_DOWN -> { var minDistance = Double.MAX_VALUE for (joint in joints) { var distance = joint.distanceTo(x.toDouble(), y.toDouble()) if(distance <= SELECTION_DISTANCE && minDistance > distance){ minDistance = distance selectedJoint = joint } } } MotionEvent.ACTION_UP -> { selectedJoint = null } MotionEvent.ACTION_MOVE -> { moveSelectedJointTo(x, y) } } draw() return true } private fun moveSelectedJointTo(x: Float, y: Float) { selectedJoint?.pull(PointF(x, y)) } public fun draw() { val canvas = this.surfaceHolder.lockCanvas() val line = Paint(Paint.ANTI_ALIAS_FLAG) line.color = Color.BLUE line.strokeWidth = 4f * scaleFactor canvas.drawColor(Color.WHITE) for (limb in limbs) { canvas.drawLine(limb.start.x, limb.start.y, limb.end.x, limb.end.y, line) Log.d("StickMan", limb.start.toString() + " " + limb.end.toString()) } val dot = Paint(Paint.ANTI_ALIAS_FLAG) dot.color = Color.RED val selectedDot = Paint(Paint.ANTI_ALIAS_FLAG) selectedDot.color = Color.YELLOW for (joint in joints){ canvas.drawCircle(joint.position.x, joint.position.y, 3f * scaleFactor, if(joint.equals(selectedJoint)) selectedDot else dot) } val neck = torso.end val forehead = head.end val radius = HEAD_RADIUS * scaleFactor val posHeadX = neck.x + (forehead.x - neck.x) / 2; val posHeadY = neck.y + (forehead.y - neck.y) / 2; canvas.drawCircle(posHeadX, posHeadY, radius, line) this.surfaceHolder.unlockCanvasAndPost(canvas) } private fun createLimbArray() { val newLimbs = arrayOf(torso, head, leftUpperArm, leftForeArm, leftUpperLeg, leftLowerLeg, rightUpperArm, rightForeArm, rightUpperLeg, rightLowerLeg) limbs = newLimbs } companion object { public val HEAD_RADIUS: Float = 20f public val LENGTH_FORE_ARM: Float = 40f public val LENGTH_UPPER_ARM: Float = 50f public val LENGTH_UPPER_LEG: Float = 60f public val LENGTH_LOWER_LEG: Float = 50f public val LENGTH_TORSO: Float = 70f } public enum class Direction { LEFT, RIGHT, FRONT } public fun playRecordings() { var player = Thread(Runnable() { run { var angles: LinkedList<RecordedAngle> = LinkedList() var angles2: LinkedList<RecordedAngle> = LinkedList() angles.addAll(rightUpperArm.recordedAngles) angles2.addAll(rightForeArm.recordedAngles) var time: Long var waitTime: Long = 16 for (i: Int in 0..angles.size-1) { time = System.currentTimeMillis() + waitTime rightUpperArm.angle += angles[i].angle rightForeArm.angle += angles2[i].angle draw() time = time - System.currentTimeMillis() if (time < 0) time = 0; Thread.sleep(time); } rightUpperArm.recordedAngles.clear() rightForeArm.recordedAngles.clear() } }) player.start() } }
apache-2.0
b9ebcf3a5285db54014386b49d4d414e
29.096618
157
0.573515
4.311419
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertVariableAssignmentToExpressionIntention.kt
4
1304
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern class ConvertVariableAssignmentToExpressionIntention : SelfTargetingIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("convert.to.assignment.expression"), ) { override fun isApplicableTo(element: KtBinaryExpression, caretOffset: Int): Boolean { if (element.operationToken == KtTokens.EQ) return true return false } override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val left = element.left ?: return val right = element.right ?: return val newElement = KtPsiFactory(element.project).createExpressionByPattern("$0.also { $1 = it }", right, left) element.replace(newElement) } }
apache-2.0
ec4c259eff760073d14c1e830cfbf544
45.571429
158
0.77454
4.673835
false
false
false
false
GunoH/intellij-community
plugins/kotlin/plugin-updater/src/org/jetbrains/kotlin/idea/update/PluginVerifyResult.kt
4
758
// 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.update class PluginVerifyResult { var verified: Boolean = true /** * Short sentence explaining why plugin is available in JetBrains repository but can't be installed. * Unapproved result should have a not-null declined message. */ var declineMessage: String? = null companion object { @JvmOverloads fun decline(reason: String? = null): PluginVerifyResult = PluginVerifyResult().apply { declineMessage = reason verified = false } fun accept() = PluginVerifyResult() } }
apache-2.0
bf0d5295f5739af5aff8623323a44716
31.956522
158
0.67942
4.538922
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/exception/TransactionException.kt
1
1195
package com.onyx.exception import com.onyx.interactors.transaction.data.Transaction /** * Created by Tim Osborn on 3/25/16. * * This error denotes a failure to interact with a transaction WAL file */ class TransactionException @JvmOverloads constructor(message: String? = "") : OnyxException(message) { private var transaction: Transaction? = null /** * Constructor with Transaction * * @param message message * @param transaction transaction */ constructor(message: String, transaction: Transaction?, cause: Throwable) : this(message) { this.transaction = transaction this.rootCause = cause } companion object { const val TRANSACTION_FAILED_TO_OPEN_FILE = "Failed to open transaction file" const val TRANSACTION_FAILED_TO_WRITE_FILE = "Failed to write to transaction file" const val TRANSACTION_FAILED_TO_READ_FILE = "Failed to read from a transaction file" const val TRANSACTION_FAILED_TO_RECOVER_FROM_DIRECTORY = "Failed to recover database. The WAL directory does not exist or is not a directory" const val TRANSACTION_FAILED_TO_EXECUTE = "Failed to execute transaction." } }
agpl-3.0
d49fc09fd22e40ce1b7e396f840325d7
36.34375
150
0.705439
4.492481
false
false
false
false
GunoH/intellij-community
plugins/kotlin/scripting-support/test/org/jetbrains/kotlin/idea/script/AbstractScriptTemplatesFromDependenciesTest.kt
1
6330
// 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.script import com.intellij.ide.projectView.actions.MarkRootActionBase import com.intellij.openapi.module.JavaModuleType import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.testFramework.HeavyPlatformTestCase import com.intellij.testFramework.PsiTestUtil import com.intellij.util.io.ZipUtil import com.intellij.util.io.systemIndependentPath import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionContributor import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.jetbrains.kotlin.test.util.addDependency import org.jetbrains.kotlin.test.util.jarRoot import org.jetbrains.kotlin.test.util.projectLibrary import org.junit.runner.RunWith import java.io.File import java.io.FileOutputStream import java.nio.file.Path import java.util.zip.ZipOutputStream @RunWith(JUnit3RunnerWithInners::class) abstract class AbstractScriptTemplatesFromDependenciesTest : HeavyPlatformTestCase() { companion object { private const val testFileName = "test.kts" } fun doTest(path: String) { val projectRoot = project.guessProjectDir() ?: return val testDataDir = File(path) copyDirContentsTo( LocalFileSystem.getInstance().findFileByIoFile(testDataDir)!!, projectRoot ) testDataDir .listFiles { f -> f.name.startsWith("module") } ?.filter { it.exists() } ?.forEach { createTestModule(it) } ModuleManager.getInstance(project).modules.forEach { module -> testDataDir .listFiles { f -> f.name.startsWith("jar") } ?.map { folder -> ModuleRootManager.getInstance(module).modifiableModel.apply { val vFile = VfsUtil.findFileByIoFile(folder, true)!! MarkRootActionBase.findContentEntry(this, vFile)?.addExcludeFolder(vFile) runWriteAction { [email protected]() } } packJar(folder) } ?.forEach { jar -> module.addDependency( projectLibrary( libraryName = "script-library", classesRoot = jar.jarRoot ) ) } } val roots: Collection<VirtualFile> = FileTypeIndex.getFiles(ScriptDefinitionMarkerFileType, GlobalSearchScope.allScope(project)) val testFile = File(path, testFileName) val fileText = testFile.readText() checkRoots(fileText, roots) val provider = ScriptDefinitionContributor.find<ScriptTemplatesFromDependenciesProvider>(project) ?: error("Cannot find ScriptTemplatesFromDependenciesProvider") val (templates, classpath) = provider.getTemplateClassPath(roots.toList(), EmptyProgressIndicator()) checkTemplateNames(fileText, templates) checkTemplateClasspath(fileText, classpath) } private fun String.removeTestDirPrefix(): String = this.substringAfterLast(getTestName(true)) private fun checkRoots(fileText: String, roots: Collection<VirtualFile>) { val actual = roots.map { it.path.removeTestDirPrefix() } val expected = InTextDirectivesUtils.findListWithPrefixes(fileText, "// ROOT:") assertOrderedEquals("Roots are different", actual.sorted(), expected.sorted()) } private fun checkTemplateNames(fileText: String, names: Collection<String>) { val expected = InTextDirectivesUtils.findListWithPrefixes(fileText, "// NAME:") assertOrderedEquals("Template names are different", names.sorted(), expected.sorted()) } private fun checkTemplateClasspath(fileText: String, classpath: Collection<Path>) { val actual = classpath.map { it.systemIndependentPath.removeTestDirPrefix() } val expected = InTextDirectivesUtils.findListWithPrefixes(fileText, "// CLASSPATH:") assertOrderedEquals("Roots are different", actual.sorted(), expected.sorted()) } private fun createTestModule(dir: File): Module { val newModule = createModuleAt(name, project, JavaModuleType.getModuleType(), dir.toPath()) dir.listFiles()?.forEach { val root = VfsUtil.findFileByIoFile(it, true) ?: return@forEach when (it.name) { "src" -> PsiTestUtil.addSourceRoot(newModule, root) "test" -> PsiTestUtil.addSourceRoot(newModule, root, true) "resources" -> PsiTestUtil.addSourceRoot(newModule, root, JavaResourceRootType.RESOURCE) } } return newModule } private fun packJar(dir: File): File { val contentDir = KotlinTestUtils.tmpDirForReusableFolder("folderForLibrary-${getTestName(true)}") return createJarFile(contentDir, dir, "templates") } // Copied from `MockLibraryUtil.createJarFile` of old repo private fun createJarFile(contentDir: File, dirToAdd: File, jarName: String, sourcesPath: String? = null): File { val jarFile = File(contentDir, jarName + ".jar") ZipOutputStream(FileOutputStream(jarFile)).use { zip -> ZipUtil.addDirToZipRecursively(zip, jarFile, dirToAdd, "", null, null) if (sourcesPath != null) { ZipUtil.addDirToZipRecursively(zip, jarFile, File(sourcesPath), "src", null, null) } } return jarFile } }
apache-2.0
9decb97f657dccb31d45a8e737093aa0
40.927152
158
0.686098
5.072115
false
true
false
false
jk1/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/syncIcons.kt
1
1518
// 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.intellij.build.images.sync import java.io.File internal fun syncAdded(added: Collection<String>, sourceRepoMap: Map<String, GitObject>, targetDir: File, targetRepo: (File) -> File) { val unversioned = mutableMapOf<File, MutableList<String>>() added.forEach { val target = File(targetDir, it) if (target.exists()) log("$it already exists in target repo!") val source = sourceRepoMap[it]!!.getFile() source.copyTo(target, overwrite = true) val repo = targetRepo(target) if (!unversioned.containsKey(repo)) unversioned[repo] = mutableListOf() unversioned[repo]!!.add(target.relativeTo(repo).path) } unversioned.forEach { repo, add -> addChangesToGit(add, repo) } } internal fun syncModified(modified: Collection<String>, targetRepoMap: Map<String, GitObject>, sourceRepoMap: Map<String, GitObject>) { modified.forEach { val target = targetRepoMap[it]!!.getFile() val source = sourceRepoMap[it]!!.getFile() source.copyTo(target, overwrite = true) } } internal fun syncRemoved(removed: Collection<String>, targetRepoMap: Map<String, GitObject>) { removed.map { targetRepoMap[it]!!.getFile() }.forEach { if (!it.delete()) log("Failed to delete ${it.absolutePath}") } }
apache-2.0
8f1cacf11f779e21954858de0c2ed41b
37.948718
140
0.658103
4.13624
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-jetty/jvm/test/io/ktor/tests/server/jetty/JettyAsyncServletContainerTest.kt
1
1583
/* * 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.tests.server.jetty import io.ktor.server.jetty.* import io.ktor.server.testing.suites.* import kotlin.test.* class JettyAsyncServletContainerCompressionTest : CompressionTestSuite<JettyApplicationEngineBase, JettyApplicationEngineBase.Configuration>(Servlet(async = true)) class JettyAsyncServletContainerContentTest : ContentTestSuite<JettyApplicationEngineBase, JettyApplicationEngineBase.Configuration>(Servlet(async = true)) class JettyAsyncServletContainerHttpServerCommonTest : HttpServerCommonTestSuite<JettyApplicationEngineBase, JettyApplicationEngineBase.Configuration>( Servlet(async = true) ) { override fun testFlushingHeaders() { // no op } } class JettyAsyncServletContainerHttpServerJvmTest : HttpServerJvmTestSuite<JettyApplicationEngineBase, JettyApplicationEngineBase.Configuration>( Servlet(async = true) ) { @Ignore override fun testPipelining() { } @Ignore override fun testPipeliningWithFlushingHeaders() { } } class JettyAsyncServletContainerSustainabilityTest : SustainabilityTestSuite<JettyApplicationEngineBase, JettyApplicationEngineBase.Configuration>(Servlet(async = true)) class JettyAsyncServerPluginsTest : ServerPluginsTestSuite<JettyApplicationEngineBase, JettyApplicationEngineBase.Configuration>( Servlet(async = true) ) { init { enableHttp2 = false enableSsl = false } }
apache-2.0
59c5a44838e97c1d2ff50cd112c1877b
30.66
120
0.772584
4.669617
false
true
false
false
RF-Buerky/energy-model
src/main/kotlin/org/codefx/demo/bingen/bank/Bank.kt
1
3716
package org.codefx.demo.bingen.bank class Bank { /* * TODO #4: improve [Bank] * * Currently the bank hands out accounts (e.g. [openAccount] returns an [Account]). * That's weird because it allows customers to interact directly with the account * without going through the bank. * * Instead of acting on [Account] entities all methods should receive and return * [AccountNumber] values (i.e. data classes). Before starting to write any code * consider carefully: * * - what should the [AccountNumber] value class have as fields * (think about what your account number looks like but keep it simple) * - who needs to know about the account numbers? the account? the customer? the bank? * - given an account number how does the bank get the corresponding account * (two ideas: collect all accounts in a map[1] or put them all in the list * and search through that) * - if you have any problems, open a PR with what you have * * [1] https://www.youtube.com/watch?v=FUqD6srpuPY */ val customers: MutableList<Customer> = mutableListOf() fun openAccount(customer: Customer, openingDeposit: Money = Money(0), limit: Balance = Balance(0)): Account { if (!customers.contains(customer)) { println("!! CUSTOMER DOES NOT BELONG TO THIS BANK") } val newAccount = Account() customer.accounts.add(newAccount) // The following line needet to be added in order to solve TODO #1 deposit (newAccount , openingDeposit) // The following line needet to be added in order to solve TODO #1 bank_setNewLimit(newAccount , limit) return newAccount } fun closeAccount(customer: Customer, account: Account): Money { if (!customers.contains(customer)) { println("!! CUSTOMER DOES NOT BELONG TO THIS BANK") return Money(0) } else if (account.balance.isOverdrawn()) { println("!! OVERDRAWN ACCOUNT CAN NOT BE CLOSED") return Money(0) } else { customer.accounts.remove(account) if (customer.accounts.isEmpty()) { customers.remove(customer) } return account.withdrawRemaining() } } fun newCustomer(name: String): Customer { val newAccount = Account() val newCustomer = Customer(name, newAccount) customers.add(newCustomer) return newCustomer } fun balance(account: Account): Balance { return account.balance } fun deposit(account: Account, amount: Money): Money { return account.deposit(amount) } fun withdraw(account: Account, amount: Money): Money { // The following code was wrong and has been corrected in order solve TODO #1 // return account.deposit(amount) return account.withdraw(amount) } fun transferBetweenAccounts(from: Account, to: Account, amount: Money): Money { val withdrawnAmount = from.withdraw(amount) to.deposit(withdrawnAmount) // TODO: reporting return withdrawnAmount } fun transferBetweenCustomers(from: Customer, to: Customer, amount: Money): Money { val fromAccount = from.defaultAccount // There has been a mistake corrected by solving TODO #2 val toAccount = to.defaultAccount return transferBetweenAccounts(fromAccount, toAccount, amount) } // The following function needet to be added in order to solve TODO #1 fun bank_setNewLimit (account: Account , newLimit : Balance): Balance { return account.setNewLimit(newLimit) } }
cc0-1.0
d723bf45280722cec73012f20d55c5fb
34.390476
113
0.640743
4.455635
false
false
false
false
colriot/talk-kotlin-vs-java
src/builder/Builder.kt
1
516
package builder /** * @author Sergey Chistyakov <[email protected]> * 21.06.2017 */ fun main(args: Array<String>) { // If our object is mutable. val jFacts = JNutritionFacts().apply { servingSize = 100 servings = 2 calories = 200 fat = 80 sodium = 25 carbohydrate = 12 } // If object is immutable. val kFacts = KNutritionFacts( servingSize = 100, servings = 2, calories = 200, fat = 80, sodium = 25, carbohydrate = 12 ) }
apache-2.0
6f243c3226ab93c95b00d08030d00a1f
18.111111
57
0.587209
3.329032
false
false
false
false
sharkspeed/dororis
languages/kotlin/programming-kotlin/5-chapter/0-HigherOrderFunc.kt
1
909
fun main(args: Array<String>) { first("Cool", {it.reversed()}) /*val counter = AtomicInteger(0)*/ /*val cores = Runtime.getRuntime().availableProcessors()*/ /*val threadPool = Excutors.newFixedThreadPool(cores)*/ /*threadPool.submit {*/ /*println("I am task number ${counter.incrementAndGet()}")*/ /*}*/ // anonymous functions val ints = listOf(1,2,3) val evens = ints.filter(fun(k:Int) = k % 2 == 0) println(evens) // function reference /*val isEven = {k:Int -> k%2 == 0}*/ fun isEven(k:Int):Boolean = k % 2 == 0 // filter {isEven(it)} println(ints.filter(::isEven)) /*println(ints.filter {it.isOdd()})*/ println(ints.filter(Int::isOdd)) } fun first(str: String, fn: (String)->String):Unit { val applied = fn(str) println(applied) } fun concatWho(str: String) = str + " Who" fun Int.isOdd():Boolean = this % 2 != 0
bsd-2-clause
9d93dcf380c575f0601dec38a829679b
24.971429
68
0.59626
3.456274
false
false
false
false
bonepeople/SDCardCleaner
app/src/main/java/com/bonepeople/android/sdcardcleaner/fragment/HomeFragment.kt
1
4548
package com.bonepeople.android.sdcardcleaner.fragment import android.Manifest import android.os.Bundle import android.view.View import android.widget.Button import com.bonepeople.android.base.ViewBindingFragment import com.bonepeople.android.base.activity.StandardActivity import com.bonepeople.android.base.databinding.ViewTitleBinding import com.bonepeople.android.sdcardcleaner.R import com.bonepeople.android.sdcardcleaner.databinding.FragmentHomeBinding import com.bonepeople.android.sdcardcleaner.global.FileTreeManager import com.bonepeople.android.widget.util.AppPermission import com.bonepeople.android.widget.util.AppToast import com.bonepeople.android.widget.util.singleClick import kotlinx.coroutines.delay import kotlinx.coroutines.launch class HomeFragment : ViewBindingFragment<FragmentHomeBinding>() { private var state = -1 override fun initView() { ViewTitleBinding.bind(views.titleView).run { imageViewTitleAction.setImageResource(R.drawable.icon_set) imageViewTitleAction.visibility = View.VISIBLE imageViewTitleAction.singleClick { StandardActivity.open(SettingFragment()) } } } override fun initData(savedInstanceState: Bundle?) { updateView() } private fun updateView() { if (state != FileTreeManager.currentState) { updateState() } val time = when (state) { FileTreeManager.STATE.READY -> "" else -> FileTreeManager.getProgressTimeString() } views.textViewTime.text = time views.storageSummary.updateView() } private fun updateState() { state = FileTreeManager.currentState when (state) { FileTreeManager.STATE.READY -> { views.textViewState.setText(R.string.state_ready) views.buttonTop.setText(R.string.caption_button_startScan) views.buttonTop.singleClick { startScan() } views.buttonTop.visibility = Button.VISIBLE views.buttonLeft.visibility = Button.GONE views.buttonRight.visibility = Button.GONE } FileTreeManager.STATE.SCAN_EXECUTING -> { views.textViewState.setText(R.string.state_scan_executing) views.buttonTop.setText(R.string.caption_button_stopScan) views.buttonTop.singleClick { stopScan() } views.buttonTop.visibility = Button.VISIBLE views.buttonLeft.visibility = Button.GONE views.buttonRight.visibility = Button.GONE } FileTreeManager.STATE.SCAN_STOPPING -> { views.textViewState.setText(R.string.state_scan_stopping) views.buttonTop.visibility = Button.GONE views.buttonLeft.visibility = Button.GONE views.buttonRight.visibility = Button.GONE } FileTreeManager.STATE.SCAN_FINISH -> { views.textViewState.setText(R.string.state_scan_finish) views.buttonTop.setText(R.string.caption_button_reScan) views.buttonLeft.setText(R.string.caption_button_startClean) views.buttonRight.setText(R.string.caption_button_viewFiles) views.buttonTop.singleClick { startScan() } views.buttonLeft.singleClick { startClean() } views.buttonRight.singleClick { viewFile() } views.buttonTop.visibility = Button.VISIBLE views.buttonLeft.visibility = Button.VISIBLE views.buttonRight.visibility = Button.VISIBLE } } } private fun startScan() { AppPermission.request(Manifest.permission.WRITE_EXTERNAL_STORAGE) .onResult { allGranted, _ -> if (allGranted) { FileTreeManager.startScan() autoFresh() } else { AppToast.show("需要存储空间的权限才能扫描文件") } } } private fun stopScan() { FileTreeManager.stopScan() } private fun startClean() { } private fun stopClean() { } private fun viewFile() { } private fun autoFresh() { launch { updateView() while (FileTreeManager.currentState != FileTreeManager.STATE.SCAN_FINISH) { delay(500) updateView() } delay(500) updateView() } } }
gpl-3.0
c5a96376010aff6799e78bf14cd182f6
35.152
89
0.626383
4.70625
false
false
false
false
fyookball/electrum
android/app/src/main/java/org/electroncash/electroncash3/Daemon.kt
1
3120
package org.electroncash.electroncash3 import androidx.lifecycle.MutableLiveData import android.widget.Toast import com.chaquo.python.PyException import com.chaquo.python.PyObject val guiDaemon by lazy { guiMod("daemon") } val WATCHDOG_INTERVAL = 1000L lateinit var daemonModel: DaemonModel val daemonUpdate = MutableLiveData<Unit>().apply { value = Unit } fun initDaemon() { guiDaemon.callAttr("set_excepthook", mainHandler) daemonModel = DaemonModel() } class DaemonModel { val commands = guiConsole.callAttr("AndroidCommands", app)!! val config = commands.get("config")!! val daemon = commands.get("daemon")!! val network = commands.get("network")!! val wallet: PyObject? get() = commands.get("wallet") val walletName: String? get() { val wallet = this.wallet return if (wallet == null) null else wallet.callAttr("basename").toString() } lateinit var watchdog: Runnable init { network.callAttr("register_callback", guiDaemon.callAttr("make_callback", this), guiConsole.get("CALLBACKS")) commands.callAttr("start") // This is still necessary even with the excepthook, in case a thread exits // non-exceptionally. watchdog = Runnable { for (thread in listOf(daemon, network)) { if (! thread.callAttr("is_alive").toBoolean()) { throw RuntimeException("$thread unexpectedly stopped") } } mainHandler.postDelayed(watchdog, WATCHDOG_INTERVAL) } watchdog.run() } // This function is called from src/main/python/electroncash_gui/android/daemon.py. // It will sometimes be called on the main thread and sometimes on the network thread. @Suppress("unused") fun onCallback(event: String) { if (EXCHANGE_CALLBACKS.contains(event)) { fiatUpdate.postValue(Unit) } else { daemonUpdate.postValue(Unit) } } fun isConnected() = network.callAttr("is_connected").toBoolean() fun listWallets(): List<String> { return commands.callAttr("list_wallets").asList().map { it.toString() } } /** If the password is wrong, throws PyException with the type InvalidPassword. */ fun loadWallet(name: String, password: String) { val prevName = walletName commands.callAttr("load_wallet", name, password) if (prevName != null && prevName != name) { commands.callAttr("close_wallet", prevName) } } } fun makeAddress(addrStr: String): PyObject { try { return clsAddress.callAttr("from_string", addrStr) } catch (e: PyException) { throw if (e.message!!.startsWith("AddressError")) ToastException(R.string.Invalid_address, Toast.LENGTH_SHORT) else e } } fun setDescription(key: String, description: String) { val wallet = daemonModel.wallet!! wallet.callAttr("set_label", key, description) wallet.get("storage")!!.callAttr("write") daemonUpdate.postValue(Unit) }
mit
13b2456ce9ced44ca036a5a0d6124c39
30.2
90
0.637821
4.333333
false
false
false
false
dhis2/dhis2-android-sdk
core/src/androidTest/java/org/hisp/dhis/android/core/data/database/ObjectStoreAbstractIntegrationShould.kt
1
3777
/* * 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.data.database import com.google.common.truth.Truth.assertThat import java.io.IOException import kotlin.jvm.Throws import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectStore import org.hisp.dhis.android.core.arch.db.tableinfos.TableInfo import org.hisp.dhis.android.core.common.CoreObject import org.junit.Before import org.junit.Test abstract class ObjectStoreAbstractIntegrationShould<M : CoreObject> internal constructor( private val store: ObjectStore<M>, tableInfo: TableInfo, databaseAdapter: DatabaseAdapter ) { val `object`: M private val tableInfo: TableInfo private val databaseAdapter: DatabaseAdapter protected abstract fun buildObject(): M @Before @Throws(IOException::class) open fun setUp() { store.delete() } @Test fun insert_and_select_first_object() { store.insert(`object`) val objectFromDb = store.selectFirst() assertEqualsIgnoreId(objectFromDb) } @Test fun insert_as_content_values_and_select_first_object() { databaseAdapter.insert(tableInfo.name(), null, `object`.toContentValues()) val objectFromDb = store.selectFirst() assertEqualsIgnoreId(objectFromDb) } @Test fun insert_and_select_all_objects() { store.insert(`object`) val objectsFromDb = store.selectAll() assertEqualsIgnoreId(objectsFromDb.iterator().next()) } @Test fun delete_inserted_object_by_id() { store.insert(`object`) val m = store.selectFirst()!! store.deleteById(m) assertThat(store.selectFirst()).isEqualTo(null) } fun assertEqualsIgnoreId(localObject: M?) { assertEqualsIgnoreId(localObject, `object`) } fun assertEqualsIgnoreId(m1: M?, m2: M) { val cv1 = m1!!.toContentValues() cv1.remove("_id") val cv2 = m2.toContentValues() cv2.remove("_id") assertThat(cv1).isEqualTo(cv2) } init { `object` = buildObject() this.tableInfo = tableInfo this.databaseAdapter = databaseAdapter } }
bsd-3-clause
cce9a82d2d23d304c7c341316b077766
35.669903
89
0.715912
4.301822
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeTypeParameterReifiedAndFunctionInlineFix.kt
3
2191
// 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.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.search.usagesSearch.descriptor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtTypeParameter import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class MakeTypeParameterReifiedAndFunctionInlineFix( typeReference: KtTypeReference, function: KtNamedFunction, private val typeParameter: KtTypeParameter ) : KotlinQuickFixAction<KtTypeReference>(typeReference) { private val inlineFix = AddInlineToFunctionWithReifiedFix(function) override fun getText() = KotlinBundle.message("make.type.parameter.reified.and.function.inline") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { inlineFix.invoke(project, editor, file) AddModifierFixFE10(typeParameter, KtTokens.REIFIED_KEYWORD).invoke(project, editor, file) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtTypeReference>? { val element = Errors.CANNOT_CHECK_FOR_ERASED.cast(diagnostic) val typeReference = element.psiElement as? KtTypeReference ?: return null val function = typeReference.getStrictParentOfType<KtNamedFunction>() ?: return null val typeParameter = function.typeParameterList?.parameters?.firstOrNull { it.descriptor == element.a.constructor.declarationDescriptor } ?: return null return MakeTypeParameterReifiedAndFunctionInlineFix(typeReference, function, typeParameter) } } }
apache-2.0
9beb75fc48c9fedd7e1760bdc3c8dcf7
45.617021
158
0.773619
4.912556
false
false
false
false
zeapo/Android-Password-Store
app/src/main/java/com/zeapo/pwdstore/git/ResetToRemoteOperation.kt
1
2027
package com.zeapo.pwdstore.git import android.app.Activity import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.zeapo.pwdstore.R import org.eclipse.jgit.api.AddCommand import org.eclipse.jgit.api.FetchCommand import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.ResetCommand import java.io.File /** * Creates a new git operation * * @param fileDir the git working tree directory * @param callingActivity the calling activity */ class ResetToRemoteOperation(fileDir: File, callingActivity: Activity) : GitOperation(fileDir, callingActivity) { private var addCommand: AddCommand? = null private var fetchCommand: FetchCommand? = null private var resetCommand: ResetCommand? = null /** * Sets the command * * @return the current object */ fun setCommands(): ResetToRemoteOperation { val git = Git(repository) this.addCommand = git.add().addFilepattern(".") this.fetchCommand = git.fetch().setRemote("origin") this.resetCommand = git.reset().setRef("origin/master").setMode(ResetCommand.ResetType.HARD) return this } override fun execute() { this.fetchCommand?.setCredentialsProvider(this.provider) GitAsyncTask(callingActivity, true, false, this) .execute(this.addCommand, this.fetchCommand, this.resetCommand) } override fun onError(errorMessage: String) { MaterialAlertDialogBuilder(callingActivity) .setTitle(callingActivity.resources.getString(R.string.jgit_error_dialog_title)) .setMessage("Error occured during the sync operation, " + "\nPlease check the FAQ for possible reasons why this error might occur." + callingActivity.resources.getString(R.string.jgit_error_dialog_text) + errorMessage) .setPositiveButton(callingActivity.resources.getString(R.string.dialog_ok)) { _, _ -> } .show() } }
gpl-3.0
460c4b0c49e702b82bd5d5d38dd2b249
37.980769
113
0.680809
4.454945
false
false
false
false
google/intellij-community
platform/build-scripts/dev-server/src/DevIdeaBuildServer.kt
1
8011
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment") package org.jetbrains.intellij.build.devServer import com.intellij.openapi.util.io.NioFiles import com.sun.net.httpserver.HttpContext import com.sun.net.httpserver.HttpExchange import com.sun.net.httpserver.HttpServer import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import org.jetbrains.intellij.build.IdeaProjectLoaderUtil import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.PrintWriter import java.io.StringWriter import java.net.HttpURLConnection import java.net.InetAddress import java.net.InetSocketAddress import java.net.URI import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.Semaphore import java.util.logging.ConsoleHandler import java.util.logging.Formatter import java.util.logging.Level import java.util.logging.LogRecord import kotlin.io.path.createDirectories import kotlin.system.exitProcess @Suppress("GrazieInspection") internal val skippedPluginModules = hashSetOf( "intellij.cwm.plugin", // quiche downloading should be implemented as a maven lib ) internal val LOG: Logger = LoggerFactory.getLogger(DevIdeaBuildServer::class.java) enum class DevIdeaBuildServerStatus { OK, FAILED, IN_PROGRESS, UNDEFINED } object DevIdeaBuildServer { private const val SERVER_PORT = 20854 private val buildQueueLock = Semaphore(1, true) private val doneSignal = CountDownLatch(1) // <product / DevIdeaBuildServerStatus> private var productBuildStatus = HashMap<String, DevIdeaBuildServerStatus>() @JvmStatic fun main(args: Array<String>) { initLog() try { start() } catch (e: ConfigurationException) { LOG.error(e.message) exitProcess(1) } } private fun initLog() { val root = java.util.logging.Logger.getLogger("") root.level = Level.INFO val handlers = root.handlers for (handler in handlers) { root.removeHandler(handler) } root.addHandler(ConsoleHandler().apply { formatter = object : Formatter() { override fun format(record: LogRecord): String { val timestamp = String.format("%1\$tT,%1\$tL", record.millis) return "$timestamp ${record.message}\n" + (record.thrown?.let { thrown -> StringWriter().also { thrown.printStackTrace(PrintWriter(it)) }.toString() } ?: "") } } }) } private fun start() { val buildServer = BuildServer(homePath = getHomePath()) val httpServer = createHttpServer(buildServer) LOG.info("Listening on ${httpServer.address.hostString}:${httpServer.address.port}") LOG.info( "Custom plugins: ${getAdditionalModules()?.joinToString() ?: "not set (use VM property `additional.modules` to specify additional module ids)"}") LOG.info( "Run IDE on module intellij.platform.bootstrap with VM properties -Didea.use.dev.build.server=true -Djava.system.class.loader=com.intellij.util.lang.PathClassLoader") httpServer.start() // wait for ctrl-c Runtime.getRuntime().addShutdownHook(Thread { doneSignal.countDown() }) try { doneSignal.await() } catch (ignore: InterruptedException) { } LOG.info("Server stopping...") httpServer.stop(10) exitProcess(0) } private fun HttpExchange.getPlatformPrefix() = parseQuery(this.requestURI).get("platformPrefix")?.first() ?: "idea" private fun createBuildEndpoint(httpServer: HttpServer, buildServer: BuildServer): HttpContext? { return httpServer.createContext("/build") { exchange -> val platformPrefix = exchange.getPlatformPrefix() var statusMessage: String var statusCode = HttpURLConnection.HTTP_OK productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.UNDEFINED) try { productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.IN_PROGRESS) buildQueueLock.acquire() exchange.responseHeaders.add("Content-Type", "text/plain") runBlocking(Dispatchers.Default) { val ideBuilder = buildServer.checkOrCreateIdeBuilder(platformPrefix) statusMessage = ideBuilder.pluginBuilder.buildChanged() } LOG.info(statusMessage) } catch (e: ConfigurationException) { statusCode = HttpURLConnection.HTTP_BAD_REQUEST productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.FAILED) statusMessage = e.message!! } catch (e: Throwable) { productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.FAILED) exchange.sendResponseHeaders(HttpURLConnection.HTTP_UNAVAILABLE, -1) LOG.error("Cannot handle build request", e) return@createContext } finally { buildQueueLock.release() } productBuildStatus.put(platformPrefix, if (statusCode == HttpURLConnection.HTTP_OK) { DevIdeaBuildServerStatus.OK } else { DevIdeaBuildServerStatus.FAILED }) val response = statusMessage.encodeToByteArray() exchange.sendResponseHeaders(statusCode, response.size.toLong()) exchange.responseBody.apply { this.write(response) this.flush() this.close() } } } private fun createStatusEndpoint(httpServer: HttpServer): HttpContext? { return httpServer.createContext("/status") { exchange -> val platformPrefix = exchange.getPlatformPrefix() val buildStatus = productBuildStatus.getOrDefault(platformPrefix, DevIdeaBuildServerStatus.UNDEFINED) exchange.responseHeaders.add("Content-Type", "text/plain") val response = buildStatus.toString().encodeToByteArray() exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size.toLong()) exchange.responseBody.apply { this.write(response) this.flush() this.close() } } } private fun createStopEndpoint(httpServer: HttpServer): HttpContext? { return httpServer.createContext("/stop") { exchange -> exchange.responseHeaders.add("Content-Type", "text/plain") val response = "".encodeToByteArray() exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size.toLong()) exchange.responseBody.apply { this.write(response) this.flush() this.close() } doneSignal.countDown() } } private fun createHttpServer(buildServer: BuildServer): HttpServer { val httpServer = HttpServer.create() httpServer.bind(InetSocketAddress(InetAddress.getLoopbackAddress(), SERVER_PORT), 2) createBuildEndpoint(httpServer, buildServer) createStatusEndpoint(httpServer) createStopEndpoint(httpServer) // Serve requests in parallel. Though, there is no guarantee, that 2 requests will be served for different endpoints httpServer.executor = Executors.newFixedThreadPool(2) return httpServer } private fun getHomePath(): Path { return IdeaProjectLoaderUtil.guessUltimateHome(DevIdeaBuildServer::class.java) } } private fun parseQuery(url: URI): Map<String, List<String?>> { val query = url.query ?: return emptyMap() return query.splitToSequence("&") .map { val index = it.indexOf('=') val key = if (index > 0) it.substring(0, index) else it val value = if (index > 0 && it.length > index + 1) it.substring(index + 1) else null java.util.Map.entry(key, value) } .groupBy(keySelector = { it.key }, valueTransform = { it.value }) } internal fun clearDirContent(dir: Path) { if (Files.isDirectory(dir)) { // because of problem on Windows https://stackoverflow.com/a/55198379/2467248 NioFiles.deleteRecursively(dir) dir.createDirectories() } } internal class ConfigurationException(message: String) : RuntimeException(message)
apache-2.0
57e0a802093a6aba725bfc48de815471
32.523013
172
0.710398
4.585575
false
false
false
false
JetBrains/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/CreateFieldAction.kt
1
6164
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.groovy.annotator.intentions.elements import com.intellij.codeInsight.CodeInsightUtil.positionCursor import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.startTemplate import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.codeInsight.template.Template import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.lang.jvm.JvmLong import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.* import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiType import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.GroovyFileType import org.jetbrains.plugins.groovy.annotator.intentions.GroovyCreateFieldFromUsageHelper import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames internal class CreateFieldAction( target: GrTypeDefinition, request: CreateFieldRequest, private val constantField: Boolean ) : CreateFieldActionBase(target, request), JvmGroupIntentionAction { override fun getActionGroup(): JvmActionGroup = if (constantField) CreateConstantActionGroup else CreateFieldActionGroup override fun getText(): String { val what = request.fieldName val where = getNameForClass(target, false) val message = if (constantField) "intention.name.create.constant.field.in.class" else "intention.name.create.field.in.class" return GroovyBundle.message(message, what, where) } override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo { val field = GroovyFieldRenderer(project, constantField, target, request).renderField() val className = myTargetPointer.element?.name return IntentionPreviewInfo.CustomDiff(GroovyFileType.GROOVY_FILE_TYPE, className, "", field.text) } override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { GroovyFieldRenderer(project, constantField, target, request).doRender() } } internal val constantModifiers = setOf( JvmModifier.STATIC, JvmModifier.FINAL ) private class GroovyFieldRenderer( val project: Project, val constantField: Boolean, val targetClass: GrTypeDefinition, val request: CreateFieldRequest ) { val helper = GroovyCreateFieldFromUsageHelper() val typeConstraints = createConstraints(project, request.fieldType).toTypedArray() private val modifiersToRender: Collection<JvmModifier> get() { return if (constantField) { if (targetClass.isInterface) { // interface fields are public static final implicitly, so modifiers don't have to be rendered request.modifiers - constantModifiers - visibilityModifiers } else { // render static final explicitly request.modifiers + constantModifiers } } else { // render as is request.modifiers } } fun doRender() { var field = renderField() field = insertField(field) startTemplate(field) } fun renderField(): GrField { val elementFactory = GroovyPsiElementFactory.getInstance(project) val field = elementFactory.createField(request.fieldName, PsiType.INT) // clean template modifiers field.modifierList?.let { list -> list.firstChild?.let { list.deleteChildRange(it, list.lastChild) } } for (annotation in request.annotations) { field.modifierList?.addAnnotation(annotation.qualifiedName) } // setup actual modifiers for (modifier in modifiersToRender.map(JvmModifier::toPsiModifier)) { PsiUtil.setModifierProperty(field, modifier, true) } if (targetClass is GroovyScriptClass) field.modifierList?.addAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_FIELD) if (constantField) { field.initializerGroovy = elementFactory.createExpressionFromText("0", null) } val requestInitializer = request.initializer if (requestInitializer is JvmLong) { field.initializerGroovy = elementFactory.createExpressionFromText("${requestInitializer.longValue}L", null) } return field } private fun insertField(field: GrField): GrField { return helper.insertFieldImpl(targetClass, field, null) } private fun startTemplate(field: GrField) { val targetFile = targetClass.containingFile ?: return val newEditor = positionCursor(field.project, targetFile, field) ?: return val substitutor = request.targetSubstitutor.toPsiSubstitutor(project) val template = helper.setupTemplateImpl(field, typeConstraints, targetClass, newEditor, null, constantField, substitutor) val listener = MyTemplateListener(project, newEditor, targetFile) startTemplate(newEditor, template, project, listener, null) } } private class MyTemplateListener(val project: Project, val editor: Editor, val file: PsiFile) : TemplateEditingAdapter() { override fun templateFinished(template: Template, brokenOff: Boolean) { PsiDocumentManager.getInstance(project).commitDocument(editor.document) val offset = editor.caretModel.offset val psiField = PsiTreeUtil.findElementOfClassAtOffset(file, offset, GrField::class.java, false) ?: return runWriteAction { CodeStyleManager.getInstance(project).reformat(psiField) } editor.caretModel.moveToOffset(psiField.textRange.endOffset - 1) } }
apache-2.0
7294599dac65d50fa107b625b93f30fd
38.512821
128
0.77255
4.694593
false
false
false
false
apollographql/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/helpers/NamedType.kt
1
2539
package com.apollographql.apollo3.compiler.codegen.kotlin.helpers import com.apollographql.apollo3.compiler.applyIf import com.apollographql.apollo3.compiler.codegen.Identifier import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinSymbols import com.apollographql.apollo3.compiler.ir.IrInputField import com.apollographql.apollo3.compiler.ir.IrType import com.apollographql.apollo3.compiler.ir.IrVariable import com.apollographql.apollo3.compiler.ir.isOptional import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.ParameterSpec class NamedType( val graphQlName: String, val description: String?, val deprecationReason: String?, val type: IrType, ) internal fun NamedType.toParameterSpec(context: KotlinContext): ParameterSpec { return ParameterSpec .builder( // we use property for parameters as these are ultimately data classes name = context.layout.propertyName(graphQlName), type = context.resolver.resolveIrType(type) ) .applyIf(description?.isNotBlank() == true) { addKdoc("%L\n", description!!) } .applyIf(type.isOptional()) { defaultValue("%T", KotlinSymbols.Absent) } .build() } fun IrInputField.toNamedType() = NamedType( graphQlName = name, type = type, description = description, deprecationReason = deprecationReason, ) fun IrVariable.toNamedType() = NamedType( graphQlName = name, type = type, description = null, deprecationReason = null, ) internal fun List<NamedType>.writeToResponseCodeBlock(context: KotlinContext): CodeBlock { val builder = CodeBlock.builder() forEach { builder.add(it.writeToResponseCodeBlock(context)) } return builder.build() } internal fun NamedType.writeToResponseCodeBlock(context: KotlinContext): CodeBlock { val adapterInitializer = context.resolver.adapterInitializer(type, false) val builder = CodeBlock.builder() val propertyName = context.layout.propertyName(graphQlName) if (type.isOptional()) { builder.beginControlFlow("if (${Identifier.value}.%N is %T)", propertyName, KotlinSymbols.Present) } builder.addStatement("${Identifier.writer}.name(%S)", graphQlName) builder.addStatement( "%L.${Identifier.toJson}(${Identifier.writer}, ${Identifier.customScalarAdapters}, ${Identifier.value}.%N)", adapterInitializer, propertyName, ) if (type.isOptional()) { builder.endControlFlow() } return builder.build() }
mit
78016f4250df0e916cd5478cb0c7d10b
31.974026
114
0.747538
4.347603
false
false
false
false
JetBrains/intellij-community
plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/filters/GitLabMergeRequestsFiltersValue.kt
1
2925
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gitlab.mergerequest.ui.filters import com.intellij.collaboration.ui.codereview.list.search.ReviewListSearchValue import com.intellij.openapi.util.NlsSafe import kotlinx.serialization.Serializable import kotlinx.serialization.Transient @Serializable data class GitLabMergeRequestsFiltersValue( override val searchQuery: String? = null, val state: MergeRequestStateFilterValue? = null, val author: MergeRequestsMemberFilterValue? = null, val assignee: MergeRequestsMemberFilterValue? = null, val reviewer: MergeRequestsMemberFilterValue? = null, val label: LabelFilterValue? = null, ) : ReviewListSearchValue { private val filters: List<FilterValue?> = listOf(state, author, assignee, reviewer, label) @Transient override val filterCount: Int = calcFilterCount() fun toSearchQuery(): String = filters.mapNotNull { it }.joinToString(separator = "&") { filter -> "${filter.queryField()}=${filter.queryValue()}" } private fun calcFilterCount(): Int { var count = 0 if (searchQuery != null) count++ if (state != null) count++ if (author != null) count++ if (assignee != null) count++ if (reviewer != null) count++ if (label != null) count++ return count } private interface FilterValue { fun queryField(): String fun queryValue(): String } @Serializable enum class MergeRequestStateFilterValue : FilterValue { OPENED, MERGED, CLOSED; override fun queryField(): String = "state" override fun queryValue(): String = when (this) { OPENED -> "opened" CLOSED -> "closed" MERGED -> "merged" } } @Serializable sealed class MergeRequestsMemberFilterValue(val username: @NlsSafe String, val fullname: @NlsSafe String) : FilterValue { override fun queryValue(): String = username } internal class MergeRequestsAuthorFilterValue(username: String, fullname: String) : MergeRequestsMemberFilterValue(username, fullname) { override fun queryField(): String = "author_username" } internal class MergeRequestsAssigneeFilterValue(username: String, fullname: String) : MergeRequestsMemberFilterValue(username, fullname) { override fun queryField(): String = "assignee_username" } internal class MergeRequestsReviewerFilterValue(username: String, fullname: String) : MergeRequestsMemberFilterValue(username, fullname) { override fun queryField(): String = "reviewer_username" } @Serializable class LabelFilterValue(val title: String) : FilterValue { override fun queryField(): String = "labels" override fun queryValue(): String = title } companion object { val EMPTY = GitLabMergeRequestsFiltersValue() val DEFAULT = GitLabMergeRequestsFiltersValue(state = MergeRequestStateFilterValue.OPENED) } }
apache-2.0
11ed4c9f5f6a839478d2774d37f390ad
33.023256
123
0.731966
4.438543
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/service/CantusService.kt
1
4481
package no.skatteetaten.aurora.boober.service import org.springframework.beans.factory.annotation.Value import org.springframework.http.ResponseEntity import org.springframework.stereotype.Component import org.springframework.stereotype.Service import org.springframework.web.client.RestTemplate import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.module.kotlin.convertValue import mu.KotlinLogging import no.skatteetaten.aurora.boober.ServiceTypes.CANTUS import no.skatteetaten.aurora.boober.TargetService import no.skatteetaten.aurora.boober.utils.RetryingRestTemplateWrapper import no.skatteetaten.aurora.boober.utils.jsonMapper private val logger = KotlinLogging.logger {} data class TagResult(val cmd: TagCommand, val response: JsonNode?, val success: Boolean) data class TagCommand( val name: String, val from: String, val to: String, val fromRegistry: String, val toRegistry: String = fromRegistry ) data class CantusTagCommand( val from: String, val to: String ) data class CantusManifestCommand( val tagUrls: List<String> ) data class CantusFailure( val url: String, val errorMessage: String ) data class ImageMetadata( val imagePath: String, val imageTag: String, val dockerDigest: String? ) { fun getFullImagePath(): String = if (dockerDigest != null) "$imagePath@$dockerDigest" else "$imagePath:$imageTag" } @JsonIgnoreProperties(ignoreUnknown = true) data class AuroraResponse<T : Any>( val items: List<T> = emptyList(), val failure: List<CantusFailure> = emptyList(), val success: Boolean = true, val message: String = "OK", val failureCount: Int = failure.size, val successCount: Int = items.size, val count: Int = failureCount + successCount ) @JsonIgnoreProperties(ignoreUnknown = true) data class ImageTagResource( val auroraVersion: String? = null, val appVersion: String? = null, val dockerVersion: String, val dockerDigest: String, val requestUrl: String ) @Component class CantusRestTemplateWrapper(@TargetService(CANTUS) restTemplate: RestTemplate, retries: Int = 3) : RetryingRestTemplateWrapper(restTemplate, retries) @Service class CantusService( val client: CantusRestTemplateWrapper, @Value("\${integrations.docker.registry}") val dockerRegistry: String ) { fun getImageMetadata(repo: String, name: String, tag: String): ImageMetadata { val dockerDigest = getImageInformation(repo, name, tag)?.dockerDigest return ImageMetadata( imagePath = "$dockerRegistry/$repo/$name", imageTag = tag, dockerDigest = dockerDigest ) } fun getImageInformation(repo: String, name: String, tag: String): ImageTagResource? { val cantusManifestCommand = CantusManifestCommand( listOf( "$dockerRegistry/$repo/$name/$tag" ) ) val response = runCatching { client.post( body = cantusManifestCommand, type = AuroraResponse::class, url = "/manifest" ) }.also(::logResult) .getOrNull() ?.body return if (response?.success != true) { logger.warn("Unable to receive manifest. cause=${response.messageOrDefault}") null } else { val imageTagResource = response.items.single() runCatching { jsonMapper().convertValue<ImageTagResource>(imageTagResource) }.getOrNull() } } fun tag(cmd: TagCommand): TagResult { val cantusCmd = CantusTagCommand( "${cmd.fromRegistry}/${cmd.name}:${cmd.from}", "${cmd.toRegistry}/${cmd.name}:${cmd.to}" ) val response = runCatching { client.post(body = cantusCmd, type = JsonNode::class, url = "/tag") }.also(::logResult) .getOrNull() val success = response != null return TagResult(cmd, response?.body, success) } } private fun logResult(result: Result<ResponseEntity<*>>) { result.onFailure { logger.warn(it) { "Received error from Cantus. Caused by ${it.cause}" } } .onSuccess { logger.info("Response from Cantus code=${it.statusCode} body=${it.body}") } } private val AuroraResponse<*>?.messageOrDefault: String get() = this?.message ?: "empty body"
apache-2.0
9041c6d37d48a877d5d77115de96a10e
30.556338
102
0.672618
4.32529
false
false
false
false
derkork/spek
spek-core/src/main/kotlin/org/jetbrains/spek/api/Spek.kt
1
1394
package org.jetbrains.spek.api import org.junit.runner.RunWith import org.jetbrains.spek.junit.* import org.jetbrains.spek.api.* @RunWith(JUnitClassRunner::class) public abstract class Spek : org.jetbrains.spek.api.Specification { private val recordedActions = linkedListOf<org.jetbrains.spek.api.TestGivenAction>() public override fun given(description: String, givenExpression: org.jetbrains.spek.api.Given.() -> Unit) { recordedActions.add( object : org.jetbrains.spek.api.TestGivenAction { public override fun description() = "given " + description public override fun iterateOn(it: (org.jetbrains.spek.api.TestOnAction) -> Unit) { val given = org.jetbrains.spek.api.GivenImpl() given.givenExpression() given.iterateOn(it) } }) } public fun iterateGiven(it: (org.jetbrains.spek.api.TestGivenAction) -> Unit): Unit = org.jetbrains.spek.api.removingIterator(recordedActions, it) public fun allGiven(): List<org.jetbrains.spek.api.TestGivenAction> = recordedActions } public fun <T> Spek.givenData(data: Iterable<T>, givenExpression: org.jetbrains.spek.api.Given.(T) -> Unit) { for (entry in data) { given(entry.toString()) { givenExpression(entry) } } }
bsd-3-clause
4f18243008f02876881d54cea551e644
35.684211
150
0.643472
4.112094
false
true
false
false
allotria/intellij-community
platform/diff-impl/src/com/intellij/diff/actions/ShowBlankDiffWindowAction.kt
2
19136
// 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.diff.actions import com.intellij.diff.* import com.intellij.diff.FrameDiffTool.DiffViewer import com.intellij.diff.actions.impl.MutableDiffRequestChain import com.intellij.diff.contents.DiffContent import com.intellij.diff.contents.DocumentContent import com.intellij.diff.contents.FileContent import com.intellij.diff.requests.ContentDiffRequest import com.intellij.diff.requests.DiffRequest import com.intellij.diff.tools.simple.SimpleDiffTool import com.intellij.diff.tools.util.DiffDataKeys import com.intellij.diff.tools.util.DiffNotifications import com.intellij.diff.tools.util.base.DiffViewerBase import com.intellij.diff.tools.util.base.DiffViewerListener import com.intellij.diff.tools.util.side.ThreesideTextDiffViewer import com.intellij.diff.tools.util.side.TwosideTextDiffViewer import com.intellij.diff.util.* import com.intellij.icons.AllIcons import com.intellij.ide.CopyPasteManagerEx import com.intellij.ide.IdeEventQueue import com.intellij.ide.dnd.FileCopyPasteUtil import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.* import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorDropHandler import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileEditor.impl.EditorWindow import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.JBPopupMenu import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.UIBundle import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.containers.LinkedListWithSum import com.intellij.util.containers.map2Array import com.intellij.util.text.DateFormatUtil import java.awt.datatransfer.DataFlavor import java.awt.datatransfer.Transferable import java.awt.event.MouseEvent import java.io.File import javax.swing.JComponent import kotlin.math.max class ShowBlankDiffWindowAction : DumbAwareAction() { init { isEnabledInModalContext = true } override fun actionPerformed(e: AnActionEvent) { val project = e.project val editor = e.getData(CommonDataKeys.EDITOR) val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) val content1: DocumentContent val content2: DocumentContent var baseContent: DocumentContent? = null if (files != null && files.size == 3) { content1 = createFileContent(project, files[0]) ?: createEditableContent(project) baseContent = createFileContent(project, files[1]) ?: createEditableContent(project) content2 = createFileContent(project, files[2]) ?: createEditableContent(project) } else if (files != null && files.size == 2) { content1 = createFileContent(project, files[0]) ?: createEditableContent(project) content2 = createFileContent(project, files[1]) ?: createEditableContent(project) } else if (editor != null && editor.selectionModel.hasSelection()) { val defaultText = editor.selectionModel.selectedText ?: "" content1 = createEditableContent(project, defaultText) content2 = createEditableContent(project) } else { content1 = createEditableContent(project) content2 = createEditableContent(project) } val chain = BlankDiffWindowUtil.createBlankDiffRequestChain(content1, content2, baseContent) chain.putUserData(DiffUserDataKeys.PLACE, "BlankDiffWindow") chain.putUserData(DiffUserDataKeysEx.FORCE_DIFF_TOOL, SimpleDiffTool.INSTANCE) chain.putUserData(DiffUserDataKeysEx.PREFERRED_FOCUS_SIDE, Side.LEFT) chain.putUserData(DiffUserDataKeysEx.DISABLE_CONTENTS_EQUALS_NOTIFICATION, true) DiffManager.getInstance().showDiff(project, chain, DiffDialogHints.DEFAULT) } } internal class SwitchToBlankEditorAction : BlankSwitchContentActionBase() { override fun isEnabled(currentContent: DiffContent): Boolean = currentContent is FileContent override fun createNewContent(project: Project?, contextComponent: JComponent): DiffContent { return createEditableContent(project, "") } } internal class SwitchToFileEditorAction : BlankSwitchContentActionBase() { override fun isEnabled(currentContent: DiffContent): Boolean = true override fun createNewContent(project: Project?, contextComponent: JComponent): DiffContent? { val descriptor = FileChooserDescriptor(true, false, false, false, false, false) descriptor.title = DiffBundle.message("select.file.to.compare") descriptor.description = "" val file = FileChooser.chooseFile(descriptor, contextComponent, project, null) ?: return null return createFileContent(project, file) } } internal class SwitchToRecentEditorActionGroup : ActionGroup(), DumbAware { override fun update(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext) if (helper == null) { e.presentation.isEnabledAndVisible = false return } if (helper.chain.getUserData(BlankDiffWindowUtil.BLANK_KEY) != true) { e.presentation.isEnabledAndVisible = false return } e.presentation.isEnabledAndVisible = true } override fun getChildren(e: AnActionEvent?): Array<AnAction> { return BlankDiffWindowUtil.getRecentFiles().map2Array { MySwitchAction(it) } } @Suppress("DialogTitleCapitalization") private class MySwitchAction(val content: RecentBlankContent) : BlankSwitchContentActionBase() { init { val text = content.text val dateAppendix = DateFormatUtil.formatPrettyDateTime(content.timestamp) val presentable = when { text.length < 40 -> DiffBundle.message("blank.diff.recent.content.summary.text.date", text.trim(), dateAppendix) else -> { val shortenedText = StringUtil.shortenTextWithEllipsis(text.trim(), 30, 0) DiffBundle.message("blank.diff.recent.content.summary.text.length.date", shortenedText, text.length, dateAppendix) } } templatePresentation.text = presentable } override fun isEnabled(currentContent: DiffContent): Boolean = true override fun createNewContent(project: Project?, contextComponent: JComponent): DiffContent { return createEditableContent(project, content.text) } } } internal abstract class BlankSwitchContentActionBase : DumbAwareAction() { override fun update(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext) if (helper == null) { e.presentation.isEnabledAndVisible = false return } if (helper.chain.getUserData(BlankDiffWindowUtil.BLANK_KEY) != true) { e.presentation.isEnabledAndVisible = false return } val editor = e.getData(CommonDataKeys.EDITOR) val viewer = e.getData(DiffDataKeys.DIFF_VIEWER) if (viewer is TwosideTextDiffViewer) { val side = Side.fromValue(viewer.editors, editor) val currentContent = side?.select(helper.chain.content1, helper.chain.content2) e.presentation.isEnabledAndVisible = currentContent != null && isEnabled(currentContent) } else if (viewer is ThreesideTextDiffViewer) { val side = ThreeSide.fromValue(viewer.editors, editor) val currentContent = side?.select(helper.chain.content1, helper.chain.baseContent, helper.chain.content2) e.presentation.isEnabledAndVisible = currentContent != null && isEnabled(currentContent) } else { e.presentation.isEnabledAndVisible = false } } override fun actionPerformed(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext)!! val editor = e.getRequiredData(CommonDataKeys.EDITOR) val viewer = e.getRequiredData(DiffDataKeys.DIFF_VIEWER) perform(editor, viewer, helper) } fun perform(editor: Editor, viewer: DiffViewer, helper: MutableDiffRequestChain.Helper) { if (viewer is TwosideTextDiffViewer) { val side = Side.fromValue(viewer.editors, editor) ?: return val newContent = createNewContent(viewer.project, viewer.component) ?: return helper.setContent(newContent, side) } else if (viewer is ThreesideTextDiffViewer) { val side = ThreeSide.fromValue(viewer.editors, editor) ?: return val newContent = createNewContent(viewer.project, viewer.component) ?: return helper.setContent(newContent, side) } helper.fireRequestUpdated() } abstract fun isEnabled(currentContent: DiffContent): Boolean protected abstract fun createNewContent(project: Project?, contextComponent: JComponent): DiffContent? } internal class BlankToggleThreeSideModeAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext) val viewer = e.getData(DiffDataKeys.DIFF_VIEWER) as? DiffViewerBase if (helper == null || viewer == null) { e.presentation.isEnabledAndVisible = false return } if (helper.chain.getUserData(BlankDiffWindowUtil.BLANK_KEY) != true) { e.presentation.isEnabledAndVisible = false return } e.presentation.text = if (helper.chain.baseContent != null) { ActionsBundle.message("action.ToggleThreeSideInBlankDiffWindow.text.disable") } else { ActionsBundle.message("action.ToggleThreeSideInBlankDiffWindow.text.enable") } e.presentation.isEnabledAndVisible = true } override fun actionPerformed(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext)!! val viewer = e.getRequiredData(DiffDataKeys.DIFF_VIEWER) as DiffViewerBase if (helper.chain.baseContent != null) { helper.chain.baseContent = null helper.chain.baseTitle = null } else { helper.setContent(createEditableContent(viewer.project), ThreeSide.BASE) } helper.fireRequestUpdated() } } class ShowBlankDiffWindowDiffExtension : DiffExtension() { override fun onViewerCreated(viewer: DiffViewer, context: DiffContext, request: DiffRequest) { val helper = MutableDiffRequestChain.createHelper(context, request) ?: return if (helper.chain.getUserData(BlankDiffWindowUtil.BLANK_KEY) != true) return if (viewer is TwosideTextDiffViewer) { DnDHandler2(viewer, helper, Side.LEFT).install() DnDHandler2(viewer, helper, Side.RIGHT).install() } else if (viewer is ThreesideTextDiffViewer) { DnDHandler3(viewer, helper, ThreeSide.LEFT).install() DnDHandler3(viewer, helper, ThreeSide.BASE).install() DnDHandler3(viewer, helper, ThreeSide.RIGHT).install() } if (viewer is DiffViewerBase) { RecentContentHandler(viewer, helper).install() } } } private class DnDHandler2(val viewer: TwosideTextDiffViewer, val helper: MutableDiffRequestChain.Helper, val side: Side) : EditorDropHandler { fun install() { val editor = viewer.getEditor(side) as? EditorImpl ?: return editor.setDropHandler(this) } override fun canHandleDrop(transferFlavors: Array<out DataFlavor>): Boolean { return FileCopyPasteUtil.isFileListFlavorAvailable(transferFlavors) } override fun handleDrop(t: Transferable, project: Project?, editorWindow: EditorWindow?) { val success = doHandleDnD(t) if (success) helper.fireRequestUpdated() } private fun doHandleDnD(transferable: Transferable): Boolean { val files = FileCopyPasteUtil.getFileList(transferable) if (files != null) { if (files.size == 1) { val newContent = createFileContent(viewer.project, files[0]) ?: return false helper.setContent(newContent, side) return true } if (files.size >= 2) { val newContent1 = createFileContent(viewer.project, files[0]) ?: return false val newContent2 = createFileContent(viewer.project, files[1]) ?: return false helper.setContent(newContent1, Side.LEFT) helper.setContent(newContent2, Side.RIGHT) return true } } return false } } private class DnDHandler3(val viewer: ThreesideTextDiffViewer, val helper: MutableDiffRequestChain.Helper, val side: ThreeSide) : EditorDropHandler { fun install() { val editor = viewer.getEditor(side) as? EditorImpl ?: return editor.setDropHandler(this) } override fun canHandleDrop(transferFlavors: Array<out DataFlavor>): Boolean { return FileCopyPasteUtil.isFileListFlavorAvailable(transferFlavors) } override fun handleDrop(t: Transferable, project: Project?, editorWindow: EditorWindow?) { val success = doHandleDnD(t) if (success) helper.fireRequestUpdated() } private fun doHandleDnD(transferable: Transferable): Boolean { val files = FileCopyPasteUtil.getFileList(transferable) if (files != null) { if (files.size == 1) { val newContent = createFileContent(viewer.project, files[0]) ?: return false helper.setContent(newContent, side) return true } if (files.size == 3) { val newContent1 = createFileContent(viewer.project, files[0]) ?: return false val newBaseContent = createFileContent(viewer.project, files[1]) ?: return false val newContent2 = createFileContent(viewer.project, files[2]) ?: return false helper.setContent(newContent1, ThreeSide.LEFT) helper.setContent(newBaseContent, ThreeSide.BASE) helper.setContent(newContent2, ThreeSide.RIGHT) return true } } return false } } private class RecentContentHandler(val viewer: DiffViewerBase, val helper: MutableDiffRequestChain.Helper) { fun install() { viewer.addListener(MyListener()) } private inner class MyListener : DiffViewerListener() { override fun onDispose() { BlankDiffWindowUtil.saveRecentContents(viewer.request) } } } internal data class RecentBlankContent(val text: @NlsSafe String, val timestamp: Long) object BlankDiffWindowUtil { val BLANK_KEY = Key.create<Boolean>("Diff.BlankWindow") @JvmField val REMEMBER_CONTENT_KEY = Key.create<Boolean>("Diff.BlankWindow.BlankContent") @JvmStatic fun createBlankDiffRequestChain(content1: DocumentContent, content2: DocumentContent, baseContent: DocumentContent? = null): MutableDiffRequestChain { val chain = MutableDiffRequestChain(content1, baseContent, content2) chain.putUserData(BLANK_KEY, true) return chain } private val ourRecentFiles = LinkedListWithSum<RecentBlankContent> { it.text.length } internal fun getRecentFiles(): List<RecentBlankContent> = ourRecentFiles.toList() @RequiresEdt fun saveRecentContents(request: DiffRequest) { if (request is ContentDiffRequest) { for (content in request.contents) { saveRecentContent(content) } } } @RequiresEdt fun saveRecentContent(content: DiffContent) { if (content !is DocumentContent) return if (!DiffUtil.isUserDataFlagSet(REMEMBER_CONTENT_KEY, content)) return val text = content.document.text if (text.isBlank()) return val oldValue = ourRecentFiles.find { it.text == text } if (oldValue != null) { ourRecentFiles.remove(oldValue) ourRecentFiles.add(0, oldValue) } else { ourRecentFiles.add(0, RecentBlankContent(text, System.currentTimeMillis())) deleteAfterAllowedMaximum() } } private fun deleteAfterAllowedMaximum() { val maxCount = max(1, Registry.intValue("blank.diff.history.max.items")) val maxMemory = max(0, Registry.intValue("blank.diff.history.max.memory")) CopyPasteManagerEx.deleteAfterAllowedMaximum(ourRecentFiles, maxCount, maxMemory) { item -> RecentBlankContent(UIBundle.message("clipboard.history.purged.item"), item.timestamp) } } } private fun createEditableContent(project: Project?, text: String = ""): DocumentContent { val content = DiffContentFactoryEx.getInstanceEx().documentContent(project, false).buildFromText(text, false) content.putUserData(BlankDiffWindowUtil.REMEMBER_CONTENT_KEY, true) DiffUtil.addNotification(DiffNotificationProvider { viewer -> createBlankNotificationProvider(viewer, content) }, content) return content } private fun createFileContent(project: Project?, file: File): DocumentContent? { val virtualFile = VfsUtil.findFileByIoFile(file, true) ?: return null return createFileContent(project, virtualFile) } private fun createFileContent(project: Project?, file: VirtualFile): DocumentContent? { return DiffContentFactory.getInstance().createDocument(project, file) } private fun createBlankNotificationProvider(viewer: DiffViewer?, content: DocumentContent): JComponent? { if (viewer !is DiffViewerBase) return null val helper = MutableDiffRequestChain.createHelper(viewer.context, viewer.request) ?: return null val editor = when (viewer) { is TwosideTextDiffViewer -> { val index = viewer.contents.indexOf(content) if (index == -1) return null viewer.editors[index] } is ThreesideTextDiffViewer -> { val index = viewer.contents.indexOf(content) if (index == -1) return null viewer.editors[index] } else -> return null } if (editor.document.textLength != 0) return null val panel = EditorNotificationPanel{ editor.colorsScheme } panel.createActionLabel(DiffBundle.message("notification.action.text.blank.diff.select.file")) { SwitchToFileEditorAction().perform(editor, viewer, helper) } if (BlankDiffWindowUtil.getRecentFiles().isNotEmpty()) { panel.createActionLabel(DiffBundle.message("notification.action.text.blank.diff.recent")) { val menu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, SwitchToRecentEditorActionGroup()) menu.setTargetComponent(editor.component) val event = IdeEventQueue.getInstance().trueCurrentEvent if (event is MouseEvent) { JBPopupMenu.showByEvent(event, menu.component) } else { JBPopupMenu.showByEditor(editor, menu.component) } }.apply { setIcon(AllIcons.General.LinkDropTriangle) isIconAtRight = true setUseIconAsLink(true) } } editor.document.addDocumentListener(object : DocumentListener { override fun documentChanged(event: DocumentEvent) { editor.document.removeDocumentListener(this) DiffNotifications.hideNotification(panel) } }, viewer) return panel }
apache-2.0
dd40500880db329d1ad13523c9b090f0
37.580645
140
0.738033
4.434762
false
false
false
false
allotria/intellij-community
uast/uast-common/src/org/jetbrains/uast/declarations/UMethod.kt
2
3687
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.internal.log import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor /** * A method visitor to be used in [UastVisitor]. */ interface UMethod : UDeclaration, PsiMethod { @Deprecated("see the base property description", ReplaceWith("javaPsi")) override val psi: PsiMethod override val javaPsi: PsiMethod /** * Returns the body expression (which can be also a [UBlockExpression]). */ val uastBody: UExpression? /** * Returns the method parameters. */ val uastParameters: List<UParameter> override fun getName(): String override fun getReturnType(): PsiType? override fun isConstructor(): Boolean @Deprecated("Use uastBody instead.", ReplaceWith("uastBody")) override fun getBody(): PsiCodeBlock? = javaPsi.body override fun accept(visitor: UastVisitor) { if (visitor.visitMethod(this)) return uAnnotations.acceptList(visitor) uastParameters.acceptList(visitor) uastBody?.accept(visitor) visitor.afterVisitMethod(this) } override fun asRenderString(): String = buildString { if (uAnnotations.isNotEmpty()) { uAnnotations.joinTo(buffer = this, separator = "\n", postfix = "\n", transform = UAnnotation::asRenderString) } append(javaPsi.renderModifiers()) append("fun ").append(name) uastParameters.joinTo(this, prefix = "(", postfix = ")") { parameter -> val annotationsText = if (parameter.uAnnotations.isNotEmpty()) parameter.uAnnotations.joinToString(separator = " ", postfix = " ") { it.asRenderString() } else "" annotationsText + parameter.name + ": " + parameter.type.canonicalText } javaPsi.returnType?.let { append(" : " + it.canonicalText) } val body = uastBody append(when (body) { is UBlockExpression -> " " + body.asRenderString() else -> " = " + ((body ?: UastEmptyExpression(this@UMethod)).asRenderString()) }) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitMethod(this, data) override fun asLogString(): String = log("name = $name") @JvmDefault val returnTypeReference: UTypeReferenceExpression? get() { val sourcePsi = sourcePsi ?: return null for (child in sourcePsi.children) { val expression = child.toUElement(UTypeReferenceExpression::class.java) if (expression != null) { return expression } } return null } } interface UAnnotationMethod : UMethod, PsiAnnotationMethod { @Deprecated("see the base property description", ReplaceWith("javaPsi")) override val psi: PsiAnnotationMethod /** * Returns the default value of this annotation method. */ val uastDefaultValue: UExpression? override fun getDefaultValue(): PsiAnnotationMemberValue? = (javaPsi as? PsiAnnotationMethod)?.defaultValue override fun accept(visitor: UastVisitor) { if (visitor.visitMethod(this)) return uAnnotations.acceptList(visitor) uastParameters.acceptList(visitor) uastBody?.accept(visitor) uastDefaultValue?.accept(visitor) visitor.afterVisitMethod(this) } override fun asLogString(): String = log("name = $name") } @Deprecated("no more needed, use UMethod", ReplaceWith("UMethod")) @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") interface UMethodTypeSpecific : UMethod
apache-2.0
3cb253680d20fe1e8472d5a9c6034ae8
30.521368
140
0.701654
4.69084
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-query/src/main/kotlin/slatekit/query/QueryEncoder.kt
1
2996
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.query import slatekit.common.ext.toStringMySql // import java.time.* import org.threeten.bp.* import slatekit.common.ext.toNumeric import java.util.* object QueryEncoder { @JvmStatic fun convertVal(value: Any?): String { /* ktlint-disable */ return when (value) { Const.Null -> "null" null -> "null" is String -> toString(value) is Int -> value.toString() is Long -> value.toString() is Double -> value.toString() is UUID -> "'" + value.toString() + "'" is Boolean -> if (value) "1" else "0" is LocalDate -> value.toNumeric().toString() is LocalTime -> value.toNumeric().toString() is LocalDateTime -> "'" + value.toStringMySql() + "'" is ZonedDateTime -> "'" + value.toStringMySql() + "'" is List<*> -> "(" + value.joinToString(",", transform = { it -> convertVal(it) }) + ")" is Array<*> -> "(" + value.joinToString(",", transform = { it -> convertVal(it) }) + ")" is Enum<*> -> value.ordinal.toString() else -> value.toString() } /* ktlint-enable */ } /** * ensures the text value supplied be escaping single quotes for sql. * * @param text * @return */ @JvmStatic fun ensureValue(text: String): String = if (text.isNullOrEmpty()) { "" } else { text.replace("'", "''") } @JvmStatic fun ensureField(text: String): String = if (text.isNullOrEmpty()) { "" } else { text.trim().filter { c -> c.isDigit() || c.isLetter() || c == '_' || c == '.' } } /** * ensures the comparison operator to be any of ( = > >= < <= != is), other wise * defaults to "=" * * @param compare * @return */ @JvmStatic fun ensureCompare(compare: String): String = when (compare) { "=" -> "=" ">" -> ">" ">=" -> ">=" "<" -> "<" "<=" -> "<=" "!=" -> "<>" "is" -> "is" "is not" -> "is not" "in" -> "in" else -> ensureField(compare) } @JvmStatic fun toString(value: String): String { val s = ensureValue(value) val res = if (s.isNullOrEmpty()) "''" else "'$s'" return res } }
apache-2.0
2161fc3be6d62fc3226c34e73626784f
29.571429
105
0.461949
4.373723
false
false
false
false
leafclick/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/util.kt
1
4045
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.dataFlow import com.intellij.psi.PsiElement import com.intellij.psi.PsiRecursiveElementWalkingVisitor import com.intellij.psi.util.CachedValueProvider.Result import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.psi.util.PsiTreeUtil import gnu.trove.TObjectIntHashMap import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrBinaryExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrInstanceOfExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction import org.jetbrains.plugins.groovy.lang.psi.controlFlow.MixinTypeInstruction import org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction import org.jetbrains.plugins.groovy.lang.psi.controlFlow.VariableDescriptor import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ArgumentsInstruction import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isExpressionStatement internal fun GrControlFlowOwner.getVarIndexes(): TObjectIntHashMap<VariableDescriptor> { return CachedValuesManager.getCachedValue(this) { Result.create(doGetVarIndexes(this), PsiModificationTracker.MODIFICATION_COUNT) } } private fun doGetVarIndexes(owner: GrControlFlowOwner): TObjectIntHashMap<VariableDescriptor> { val result = TObjectIntHashMap<VariableDescriptor>() var num = 1 for (instruction in owner.controlFlow) { if (instruction !is ReadWriteVariableInstruction) continue val descriptor = instruction.descriptor if (!result.containsKey(descriptor)) { result.put(descriptor, num++) } } return result } private typealias InstructionsByElement = (PsiElement) -> Collection<Instruction> private typealias ReadInstructions = Collection<ReadWriteVariableInstruction> internal fun findReadDependencies(writeInstruction: Instruction, instructionsByElement: InstructionsByElement): ReadInstructions { require( writeInstruction is ReadWriteVariableInstruction && writeInstruction.isWrite || writeInstruction is MixinTypeInstruction || writeInstruction is ArgumentsInstruction ) val element = writeInstruction.element ?: return emptyList() val scope = findDependencyScope(element) ?: return emptyList() return findReadsInside(scope, instructionsByElement) } private fun findDependencyScope(element: PsiElement): PsiElement? { return PsiTreeUtil.findFirstParent(element) { (it.parent !is GrExpression || it is GrBinaryExpression || it is GrInstanceOfExpression || isExpressionStatement(it)) } } private fun findReadsInside(scope: PsiElement, instructionsByElement: InstructionsByElement): ReadInstructions { if (scope is GrForInClause) { val expression = scope.iteratedExpression ?: return emptyList() return findReadsInside(expression, instructionsByElement) } val result = ArrayList<ReadWriteVariableInstruction>() scope.accept(object : PsiRecursiveElementWalkingVisitor() { override fun visitElement(element: PsiElement) { if (element is GrReferenceExpression && !element.isQualified || element is GrParameter && element.parent is GrForInClause) { val instructions = instructionsByElement(element) for (instruction in instructions) { if (instruction !is ReadWriteVariableInstruction || instruction.isWrite) continue result += instruction } } super.visitElement(element) } }) return result }
apache-2.0
a8c629d2bf3faa041542245690bc80f0
47.73494
140
0.807417
4.736534
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/constants/long.kt
6
266
fun box(): String { if (1L != 1.toLong()) return "fail 1" if (0x1L != 0x1.toLong()) return "fail 2" if (0X1L != 0X1.toLong()) return "fail 3" if (0b1L != 0b1.toLong()) return "fail 4" if (0B1L != 0B1.toLong()) return "fail 5" return "OK" }
apache-2.0
5fe767f92692cfeb7cad86b13054161a
25.6
45
0.548872
2.557692
false
false
false
false
room-15/ChatSE
app/src/main/java/com/tristanwiley/chatse/chat/FlowLayout.kt
1
3928
package com.tristanwiley.chatse.chat import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup /** * @author RAW * From StackOverflow: https://stackoverflow.com/a/7895007/1064310 * Converted to Kotlin */ class FlowLayout : ViewGroup { private var lineHeight: Int = 0 class LayoutParams /** * @param horizontal_spacing Pixels between items, horizontally * * * @param vertical_spacing Pixels between items, vertically */ (val horizontal_spacing: Int, val vertical_spacing: Int) : ViewGroup.LayoutParams(0, 0) constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { assert(View.MeasureSpec.getMode(widthMeasureSpec) != View.MeasureSpec.UNSPECIFIED) val width = View.MeasureSpec.getSize(widthMeasureSpec) - paddingLeft - paddingRight var height = View.MeasureSpec.getSize(heightMeasureSpec) - paddingTop - paddingBottom val count = childCount var lineHeight = 0 var xpos = paddingLeft var ypos = paddingTop val childHeightMeasureSpec = if (View.MeasureSpec.getMode(heightMeasureSpec) == View.MeasureSpec.AT_MOST) { View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST) } else { View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) } for (i in 0 until count) { val child = getChildAt(i) if (child.visibility != View.GONE) { val lp = child.layoutParams as FlowLayout.LayoutParams child.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST), childHeightMeasureSpec) val childw = child.measuredWidth lineHeight = Math.max(lineHeight, child.measuredHeight + lp.vertical_spacing) if (xpos + childw > width) { xpos = paddingLeft ypos += lineHeight } xpos += childw + lp.horizontal_spacing } } this.lineHeight = lineHeight if (View.MeasureSpec.getMode(heightMeasureSpec) == View.MeasureSpec.UNSPECIFIED) { height = ypos + lineHeight } else if (View.MeasureSpec.getMode(heightMeasureSpec) == View.MeasureSpec.AT_MOST) { if (ypos + lineHeight < height) { height = ypos + lineHeight } } setMeasuredDimension(width, height) } override fun generateDefaultLayoutParams(): ViewGroup.LayoutParams { return FlowLayout.LayoutParams(1, 1) // default of 1px spacing } override fun generateLayoutParams( p: android.view.ViewGroup.LayoutParams): android.view.ViewGroup.LayoutParams { return FlowLayout.LayoutParams(1, 1) } override fun checkLayoutParams(p: ViewGroup.LayoutParams): Boolean { if (p is FlowLayout.LayoutParams) { return true } return false } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { val count = childCount val width = r - l var xpos = paddingLeft var ypos = paddingTop for (i in 0 until count) { val child = getChildAt(i) if (child.visibility != View.GONE) { val childw = child.measuredWidth val childh = child.measuredHeight val lp = child.layoutParams as FlowLayout.LayoutParams if (xpos + childw > width) { xpos = paddingLeft ypos += lineHeight } child.layout(xpos, ypos, xpos + childw, ypos + childh) xpos += childw + lp.horizontal_spacing } } } }
apache-2.0
83cc0926fa1aaa6a403ab923959d8373
34.080357
120
0.616599
4.825553
false
false
false
false
afollestad/photo-affix
viewcomponents/src/main/java/com/afollestad/photoaffix/viewcomponents/SquareFrameLayout.kt
1
1903
/** * Designed and developed by Aidan Follestad (@afollestad) * * 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.afollestad.photoaffix.viewcomponents import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Paint.Style.STROKE import android.util.AttributeSet import android.widget.FrameLayout import androidx.core.content.ContextCompat.getColor /** @author Aidan Follestad (afollestad) */ class SquareFrameLayout( context: Context, attrs: AttributeSet? = null ) : FrameLayout(context, attrs) { private val edgePaint: Paint private val borderRadius: Int = context.resources.getDimension(R.dimen.default_square_border_radius) .toInt() init { edgePaint = Paint().apply { isAntiAlias = true style = STROKE color = getColor(context, R.color.browseButtonBorder) strokeWidth = borderRadius.toFloat() } } override fun onMeasure( widthMeasureSpec: Int, heightMeasureSpec: Int ) { super.onMeasure(widthMeasureSpec, widthMeasureSpec) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val left = borderRadius val top = borderRadius val bottom = measuredHeight - borderRadius val right = measuredWidth - borderRadius canvas.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), edgePaint) } }
apache-2.0
a2f8c1eaa98b7444baba25e37a283647
30.196721
96
0.735155
4.415313
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/GradleCommandLineProjectConfigurator.kt
1
10187
// 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.plugins.gradle import com.intellij.ide.CommandLineInspectionProgressReporter import com.intellij.ide.CommandLineInspectionProjectConfigurator import com.intellij.ide.CommandLineInspectionProjectConfigurator.ConfiguratorContext import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.autoimport.AutoImportProjectTracker import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataImportListener import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import org.jetbrains.plugins.gradle.service.notification.ExternalAnnotationsProgressNotificationListener import org.jetbrains.plugins.gradle.service.notification.ExternalAnnotationsProgressNotificationManager import org.jetbrains.plugins.gradle.service.notification.ExternalAnnotationsTaskId import org.jetbrains.plugins.gradle.service.project.open.createLinkSettings import org.jetbrains.plugins.gradle.settings.GradleImportHintService import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleBundle import org.jetbrains.plugins.gradle.util.GradleConstants import java.io.BufferedWriter import java.io.File import java.io.FileWriter import java.nio.file.Paths import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap private val LOG = Logger.getInstance(GradleCommandLineProjectConfigurator::class.java) private val gradleLogWriter = BufferedWriter(FileWriter(PathManager.getLogPath() + "/gradle-import.log")) private val GRADLE_OUTPUT_LOG = Logger.getInstance("GradleOutput") private const val DISABLE_GRADLE_AUTO_IMPORT = "external.system.auto.import.disabled" private const val DISABLE_ANDROID_GRADLE_PROJECT_STARTUP_ACTIVITY = "android.gradle.project.startup.activity.disabled" private const val DISABLE_UPDATE_ANDROID_SDK_LOCAL_PROPERTIES = "android.sdk.local.properties.update.disabled" class GradleCommandLineProjectConfigurator : CommandLineInspectionProjectConfigurator { override fun getName() = "gradle" override fun getDescription(): String = GradleBundle.message("gradle.commandline.description") override fun configureEnvironment(context: ConfiguratorContext) = context.run { Registry.get(DISABLE_GRADLE_AUTO_IMPORT).setValue(true) Registry.get(DISABLE_ANDROID_GRADLE_PROJECT_STARTUP_ACTIVITY).setValue(true) Registry.get(DISABLE_UPDATE_ANDROID_SDK_LOCAL_PROPERTIES).setValue(true) val progressManager = ExternalSystemProgressNotificationManager.getInstance() progressManager.addNotificationListener(LoggingNotificationListener(context.logger)) Unit } override fun configureProject(project: Project, context: ConfiguratorContext) { val basePath = project.basePath ?: return val state = GradleImportHintService.getInstance(project).state if (state.skip) return if (GradleSettings.getInstance(project).linkedProjectsSettings.isEmpty()) { linkProjects(basePath, project) } val progressManager = ExternalSystemProgressNotificationManager.getInstance() val notificationListener = StateNotificationListener(project) val externalAnnotationsNotificationManager = ExternalAnnotationsProgressNotificationManager.getInstance() val externalAnnotationsProgressListener = StateExternalAnnotationNotificationListener() try { externalAnnotationsNotificationManager.addNotificationListener(externalAnnotationsProgressListener) progressManager.addNotificationListener(notificationListener) importProjects(project) notificationListener.waitForImportEnd() externalAnnotationsProgressListener.waitForResolveExternalAnnotationEnd() } finally { progressManager.removeNotificationListener(notificationListener) externalAnnotationsNotificationManager.removeNotificationListener(externalAnnotationsProgressListener) } } private fun linkProjects(basePath: String, project: Project) { if (linkGradleHintProjects(basePath, project)) { return } linkRootProject(basePath, project) } private fun importProjects(project: Project) { if (!GradleSettings.getInstance(project).linkedProjectsSettings.isEmpty()) { Registry.get(DISABLE_GRADLE_AUTO_IMPORT).setValue(false) AutoImportProjectTracker.getInstance(project).scheduleProjectRefresh() Registry.get(DISABLE_GRADLE_AUTO_IMPORT).setValue(true) } } private fun linkRootProject(basePath: String, project: Project): Boolean { val gradleGroovyDslFile = basePath + "/" + GradleConstants.DEFAULT_SCRIPT_NAME val kotlinDslGradleFile = basePath + "/" + GradleConstants.KOTLIN_DSL_SCRIPT_NAME if (FileUtil.findFirstThatExist(gradleGroovyDslFile, kotlinDslGradleFile) == null) return false LOG.info("Link gradle project from root directory") val settings = createLinkSettings(Paths.get(basePath), project) ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID).linkProject(settings) return true } private fun linkGradleHintProjects(basePath: String, project: Project): Boolean { val state = GradleImportHintService.getInstance(project).state if (state.projectsToImport.isNotEmpty()) { for (projectPath in state.projectsToImport) { val buildFile = File(basePath).toPath().resolve(projectPath) if (buildFile.toFile().exists()) { LOG.info("Link gradle project from intellij.yaml: $projectPath") val settings = createLinkSettings(buildFile.parent, project) ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID).linkProject(settings) } else { LOG.error("File for linking gradle project doesn't exist: " + buildFile.toAbsolutePath().toString()) return false } } return true } return false } private class StateExternalAnnotationNotificationListener : ExternalAnnotationsProgressNotificationListener { private val externalAnnotationsState = ConcurrentHashMap<ExternalAnnotationsTaskId, CompletableFuture<ExternalAnnotationsTaskId>>() override fun onStartResolve(id: ExternalAnnotationsTaskId) { externalAnnotationsState[id] = CompletableFuture() LOG.info("Gradle resolving external annotations started ${id.projectId}") } override fun onFinishResolve(id: ExternalAnnotationsTaskId) { val feature = externalAnnotationsState[id] ?: return feature.complete(id) LOG.info("Gradle resolving external annotations completed ${id.projectId}") } fun waitForResolveExternalAnnotationEnd() { externalAnnotationsState.values.forEach { it.get() } } } class StateNotificationListener(private val project: Project) : ExternalSystemTaskNotificationListenerAdapter() { private val externalSystemState = ConcurrentHashMap<ExternalSystemTaskId, CompletableFuture<ExternalSystemTaskId>>() override fun onSuccess(id: ExternalSystemTaskId) { if (!id.isGradleProjectResolveTask()) return LOG.info("Gradle resolve success: ${id.ideProjectId}") val connection = project.messageBus.simpleConnect() connection.subscribe(ProjectDataImportListener.TOPIC, object : ProjectDataImportListener { override fun onImportFinished(projectPath: String?) { LOG.info("Gradle import success: ${id.ideProjectId}") val future = externalSystemState[id] ?: return future.complete(id) } override fun onImportFailed(projectPath: String?) { LOG.info("Gradle import failure: ${id.ideProjectId}") val future = externalSystemState[id] ?: return future.completeExceptionally(IllegalStateException("Gradle project ${id.ideProjectId} import failed.")) } }) } override fun onFailure(id: ExternalSystemTaskId, e: Exception) { if (!id.isGradleProjectResolveTask()) return LOG.error("Gradle resolve failure ${id.ideProjectId}", e) val future = externalSystemState[id] ?: return future.completeExceptionally(IllegalStateException("Gradle project ${id.ideProjectId} resolve failed.", e)) } override fun onCancel(id: ExternalSystemTaskId) { if (!id.isGradleProjectResolveTask()) return LOG.error("Gradle resolve canceled ${id.ideProjectId}") val future = externalSystemState[id] ?: return future.completeExceptionally(IllegalStateException("Resolve of ${id.ideProjectId} was canceled")) } override fun onStart(id: ExternalSystemTaskId) { if (!id.isGradleProjectResolveTask()) return externalSystemState[id] = CompletableFuture() LOG.info("Gradle project resolve started ${id.ideProjectId}") } fun waitForImportEnd() { externalSystemState.values.forEach { it.get() } } private fun ExternalSystemTaskId.isGradleProjectResolveTask() = this.projectSystemId == GradleConstants.SYSTEM_ID && this.type == ExternalSystemTaskType.RESOLVE_PROJECT } class LoggingNotificationListener(val logger: CommandLineInspectionProgressReporter) : ExternalSystemTaskNotificationListenerAdapter() { override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { val gradleText = (if (stdOut) "" else "STDERR: ") + text gradleLogWriter.write(gradleText) logger.reportMessage(1, gradleText) } override fun onEnd(id: ExternalSystemTaskId) { gradleLogWriter.flush() } } }
apache-2.0
26b0b023d907cc371bffae1aec766cd6
46.602804
158
0.773829
5.147549
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/kotlinRefactoringUtil.kt
1
46252
// 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.refactoring import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils import com.intellij.codeInsight.unwrap.RangeSplitter import com.intellij.codeInsight.unwrap.UnwrapHandler import com.intellij.ide.IdeBundle import com.intellij.ide.util.PsiElementListCellRenderer import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.TransactionGuard import com.intellij.openapi.command.CommandEvent import com.intellij.openapi.command.CommandListener import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.editor.markup.RangeHighlighter import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.Pass import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.file.PsiPackageBase import com.intellij.psi.impl.light.LightElement import com.intellij.psi.presentation.java.SymbolPresentationUtil import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.BaseRefactoringProcessor.ConflictsInTestsException import com.intellij.refactoring.changeSignature.ChangeSignatureUtil import com.intellij.refactoring.listeners.RefactoringEventData import com.intellij.refactoring.listeners.RefactoringEventListener import com.intellij.refactoring.ui.ConflictsDialog import com.intellij.refactoring.util.ConflictsUtil import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.usageView.UsageViewTypeLocation import com.intellij.util.VisibilityUtil import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.getAccessorLightMethods import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.analysis.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.showYesNoCancelDialog import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar import org.jetbrains.kotlin.idea.refactoring.changeSignature.toValVar import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.rename.canonicalRender import org.jetbrains.kotlin.idea.roots.isOutsideKotlinAwareSourceRoot import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.ProgressIndicatorUtils.underModalProgress import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.idea.util.actualsForExpected import org.jetbrains.kotlin.idea.util.application.invokeLater import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.liftToExpected import org.jetbrains.kotlin.idea.util.string.collapseSpaces import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.* import org.jetbrains.kotlin.resolve.calls.callUtil.getCallWithAssert import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.typeUtil.unCapture import java.lang.annotation.Retention import java.util.* import javax.swing.Icon import kotlin.math.min import org.jetbrains.kotlin.idea.core.util.getLineCount as newGetLineCount import org.jetbrains.kotlin.idea.core.util.toPsiDirectory as newToPsiDirectory import org.jetbrains.kotlin.idea.core.util.toPsiFile as newToPsiFile const val CHECK_SUPER_METHODS_YES_NO_DIALOG = "CHECK_SUPER_METHODS_YES_NO_DIALOG" @JvmOverloads fun getOrCreateKotlinFile( fileName: String, targetDir: PsiDirectory, packageName: String? = targetDir.getFqNameWithImplicitPrefix()?.asString() ): KtFile = (targetDir.findFile(fileName) ?: createKotlinFile(fileName, targetDir, packageName)) as KtFile fun createKotlinFile( fileName: String, targetDir: PsiDirectory, packageName: String? = targetDir.getFqNameWithImplicitPrefix()?.asString() ): KtFile { targetDir.checkCreateFile(fileName) val packageFqName = packageName?.let(::FqName) ?: FqName.ROOT val file = PsiFileFactory.getInstance(targetDir.project).createFileFromText( fileName, KotlinFileType.INSTANCE, if (!packageFqName.isRoot) "package ${packageFqName.quoteSegmentsIfNeeded()} \n\n" else "" ) return targetDir.add(file) as KtFile } fun PsiElement.getUsageContext(): PsiElement { return when (this) { is KtElement -> PsiTreeUtil.getParentOfType( this, KtPropertyAccessor::class.java, KtProperty::class.java, KtNamedFunction::class.java, KtConstructor::class.java, KtClassOrObject::class.java ) ?: containingFile else -> ConflictsUtil.getContainer(this) } } fun PsiElement.isInKotlinAwareSourceRoot(): Boolean = !isOutsideKotlinAwareSourceRoot(containingFile) fun KtFile.createTempCopy(text: String? = null): KtFile { val tmpFile = KtPsiFactory(this).createAnalyzableFile(name, text ?: this.text ?: "", this) tmpFile.originalFile = this return tmpFile } fun PsiElement.getAllExtractionContainers(strict: Boolean = true): List<KtElement> { val containers = ArrayList<KtElement>() var objectOrNonInnerNestedClassFound = false val parents = if (strict) parents else parentsWithSelf for (element in parents) { val isValidContainer = when (element) { is KtFile -> true is KtClassBody -> !objectOrNonInnerNestedClassFound || element.parent is KtObjectDeclaration is KtBlockExpression -> !objectOrNonInnerNestedClassFound else -> false } if (!isValidContainer) continue containers.add(element as KtElement) if (!objectOrNonInnerNestedClassFound) { val bodyParent = (element as? KtClassBody)?.parent objectOrNonInnerNestedClassFound = (bodyParent is KtObjectDeclaration && !bodyParent.isObjectLiteral()) || (bodyParent is KtClass && !bodyParent.isInner()) } } return containers } fun PsiElement.getExtractionContainers(strict: Boolean = true, includeAll: Boolean = false): List<KtElement> { fun getEnclosingDeclaration(element: PsiElement, strict: Boolean): PsiElement? { return (if (strict) element.parents else element.parentsWithSelf) .filter { (it is KtDeclarationWithBody && it !is KtFunctionLiteral && !(it is KtNamedFunction && it.name == null)) || it is KtAnonymousInitializer || it is KtClassBody || it is KtFile } .firstOrNull() } if (includeAll) return getAllExtractionContainers(strict) val enclosingDeclaration = getEnclosingDeclaration(this, strict)?.let { if (it is KtDeclarationWithBody || it is KtAnonymousInitializer) getEnclosingDeclaration(it, true) else it } return when (enclosingDeclaration) { is KtFile -> Collections.singletonList(enclosingDeclaration) is KtClassBody -> getAllExtractionContainers(strict).filterIsInstance<KtClassBody>() else -> { val targetContainer = when (enclosingDeclaration) { is KtDeclarationWithBody -> enclosingDeclaration.bodyExpression is KtAnonymousInitializer -> enclosingDeclaration.body else -> null } if (targetContainer is KtBlockExpression) Collections.singletonList(targetContainer) else Collections.emptyList() } } } fun Project.checkConflictsInteractively( conflicts: MultiMap<PsiElement, String>, onShowConflicts: () -> Unit = {}, onAccept: () -> Unit ) { if (!conflicts.isEmpty) { if (isUnitTestMode()) throw ConflictsInTestsException(conflicts.values()) val dialog = ConflictsDialog(this, conflicts) { onAccept() } dialog.show() if (!dialog.isOK) { if (dialog.isShowConflicts) { onShowConflicts() } return } } onAccept() } fun reportDeclarationConflict( conflicts: MultiMap<PsiElement, String>, declaration: PsiElement, message: (renderedDeclaration: String) -> String ) { conflicts.putValue(declaration, message(RefactoringUIUtil.getDescription(declaration, true).capitalize())) } fun <T : PsiElement> getPsiElementPopup( editor: Editor, elements: List<T>, renderer: PsiElementListCellRenderer<T>, title: String?, highlightSelection: Boolean, processor: (T) -> Boolean ): JBPopup = with(JBPopupFactory.getInstance().createPopupChooserBuilder(elements)) { val highlighter = if (highlightSelection) SelectionAwareScopeHighlighter(editor) else null setRenderer(renderer) setItemSelectedCallback { element: T? -> highlighter?.dropHighlight() element?.let { highlighter?.highlight(element) } } title?.let { setTitle(it) } renderer.installSpeedSearch(this, true) setItemChosenCallback { it?.let(processor) } addListener(object : JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { highlighter?.dropHighlight() } }) createPopup() } class SelectionAwareScopeHighlighter(val editor: Editor) { private val highlighters = ArrayList<RangeHighlighter>() private fun addHighlighter(r: TextRange, attr: TextAttributes) { highlighters.add( editor.markupModel.addRangeHighlighter( r.startOffset, r.endOffset, UnwrapHandler.HIGHLIGHTER_LEVEL, attr, HighlighterTargetArea.EXACT_RANGE ) ) } fun highlight(wholeAffected: PsiElement) { dropHighlight() val affectedRange = wholeAffected.textRange ?: return val attributes = EditorColorsManager.getInstance().globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)!! val selectedRange = with(editor.selectionModel) { TextRange(selectionStart, selectionEnd) } val textLength = editor.document.textLength for (r in RangeSplitter.split(affectedRange, Collections.singletonList(selectedRange))) { if (r.endOffset <= textLength) addHighlighter(r, attributes) } } fun dropHighlight() { highlighters.forEach { it.dispose() } highlighters.clear() } } @Deprecated( "Use org.jetbrains.kotlin.idea.core.util.getLineStartOffset() instead", ReplaceWith("this.getLineStartOffset(line)", "org.jetbrains.kotlin.idea.core.util.getLineStartOffset"), DeprecationLevel.ERROR ) fun PsiFile.getLineStartOffset(line: Int): Int? { val doc = viewProvider.document ?: PsiDocumentManager.getInstance(project).getDocument(this) if (doc != null && line >= 0 && line < doc.lineCount) { val startOffset = doc.getLineStartOffset(line) val element = findElementAt(startOffset) ?: return startOffset if (element is PsiWhiteSpace || element is PsiComment) { return PsiTreeUtil.skipSiblingsForward(element, PsiWhiteSpace::class.java, PsiComment::class.java)?.startOffset ?: startOffset } return startOffset } return null } @Deprecated( "Use org.jetbrains.kotlin.idea.core.util.getLineEndOffset() instead", ReplaceWith("this.getLineEndOffset(line)", "org.jetbrains.kotlin.idea.core.util.getLineEndOffset"), DeprecationLevel.ERROR ) fun PsiFile.getLineEndOffset(line: Int): Int? { val document = viewProvider.document ?: PsiDocumentManager.getInstance(project).getDocument(this) return document?.getLineEndOffset(line) } fun PsiElement.getLineNumber(start: Boolean = true): Int { val document = containingFile.viewProvider.document ?: PsiDocumentManager.getInstance(project).getDocument(containingFile) val index = if (start) this.startOffset else this.endOffset if (index > (document?.textLength ?: 0)) return 0 return document?.getLineNumber(index) ?: 0 } class SeparateFileWrapper(manager: PsiManager) : LightElement(manager, KotlinLanguage.INSTANCE) { override fun toString() = "" } fun <T> chooseContainerElement( containers: List<T>, editor: Editor, title: String, highlightSelection: Boolean, toPsi: (T) -> PsiElement, onSelect: (T) -> Unit ) { val psiElements = containers.map(toPsi) choosePsiContainerElement( elements = psiElements, editor = editor, title = title, highlightSelection = highlightSelection, psi2Container = { containers[psiElements.indexOf(it)] }, onSelect = onSelect ) } fun <T : PsiElement> chooseContainerElement( elements: List<T>, editor: Editor, title: String, highlightSelection: Boolean, onSelect: (T) -> Unit ): Unit = choosePsiContainerElement( elements = elements, editor = editor, title = title, highlightSelection = highlightSelection, psi2Container = { it }, onSelect = onSelect, ) private fun psiElementRenderer() = object : PsiElementListCellRenderer<PsiElement>() { private fun PsiElement.renderName(): String = when { this is KtPropertyAccessor -> property.renderName() + if (isGetter) ".get" else ".set" this is KtObjectDeclaration && isCompanion() -> { val name = getStrictParentOfType<KtClassOrObject>()?.renderName() ?: "<anonymous>" "Companion object of $name" } else -> (this as? PsiNamedElement)?.name ?: "<anonymous>" } private fun PsiElement.renderDeclaration(): String? { if (this is KtFunctionLiteral || isFunctionalExpression()) return renderText() val descriptor = when (this) { is KtFile -> name is KtElement -> analyze()[BindingContext.DECLARATION_TO_DESCRIPTOR, this] is PsiMember -> getJavaMemberDescriptor() else -> null } ?: return null val name = renderName() val params = (descriptor as? FunctionDescriptor)?.valueParameters?.joinToString( ", ", "(", ")" ) { DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(it.type) } ?: "" return "$name$params" } private fun PsiElement.renderText(): String = when (this) { is SeparateFileWrapper -> KotlinBundle.message("refactoring.extract.to.separate.file.text") is PsiPackageBase -> qualifiedName else -> { val text = text ?: "<invalid text>" StringUtil.shortenTextWithEllipsis(text.collapseSpaces(), 53, 0) } } private fun PsiElement.getRepresentativeElement(): PsiElement = when (this) { is KtBlockExpression -> (parent as? KtDeclarationWithBody) ?: this is KtClassBody -> parent as KtClassOrObject else -> this } override fun getElementText(element: PsiElement): String { val representativeElement = element.getRepresentativeElement() return representativeElement.renderDeclaration() ?: representativeElement.renderText() } override fun getContainerText(element: PsiElement, name: String?): String? = null override fun getIcon(element: PsiElement): Icon? = super.getIcon(element.getRepresentativeElement()) } private fun <T, E : PsiElement> choosePsiContainerElement( elements: List<E>, editor: Editor, title: String, highlightSelection: Boolean, psi2Container: (E) -> T, onSelect: (T) -> Unit, ) { val popup = getPsiElementPopup( editor, elements, psiElementRenderer(), title, highlightSelection, ) { psiElement -> @Suppress("UNCHECKED_CAST") onSelect(psi2Container(psiElement as E)) true } invokeLater { popup.showInBestPositionFor(editor) } } fun <T> chooseContainerElementIfNecessary( containers: List<T>, editor: Editor, title: String, highlightSelection: Boolean, toPsi: (T) -> PsiElement, onSelect: (T) -> Unit ): Unit = chooseContainerElementIfNecessaryImpl(containers, editor, title, highlightSelection, toPsi, onSelect) fun <T : PsiElement> chooseContainerElementIfNecessary( containers: List<T>, editor: Editor, title: String, highlightSelection: Boolean, onSelect: (T) -> Unit ): Unit = chooseContainerElementIfNecessaryImpl(containers, editor, title, highlightSelection, null, onSelect) private fun <T> chooseContainerElementIfNecessaryImpl( containers: List<T>, editor: Editor, title: String, highlightSelection: Boolean, toPsi: ((T) -> PsiElement)?, onSelect: (T) -> Unit ) { when { containers.isEmpty() -> return containers.size == 1 || isUnitTestMode() -> onSelect(containers.first()) toPsi != null -> chooseContainerElement(containers, editor, title, highlightSelection, toPsi, onSelect) else -> { @Suppress("UNCHECKED_CAST") chooseContainerElement(containers as List<PsiElement>, editor, title, highlightSelection, onSelect as (PsiElement) -> Unit) } } } fun PsiElement.isTrueJavaMethod(): Boolean = this is PsiMethod && this !is KtLightMethod fun PsiElement.canRefactor(): Boolean = when { !isValid -> false this is PsiPackage -> directories.any { it.canRefactor() } this is KtElement || this is PsiMember && language == JavaLanguage.INSTANCE || this is PsiDirectory -> ProjectRootsUtil.isInProjectSource( this, includeScriptsOutsideSourceRoots = true ) else -> false } private fun copyModifierListItems(from: PsiModifierList, to: PsiModifierList, withPsiModifiers: Boolean = true) { if (withPsiModifiers) { for (modifier in PsiModifier.MODIFIERS) { if (from.hasExplicitModifier(modifier)) { to.setModifierProperty(modifier, true) } } } for (annotation in from.annotations) { val annotationName = annotation.qualifiedName ?: continue if (Retention::class.java.name != annotationName) { to.addAnnotation(annotationName) } } } private fun <T> copyTypeParameters( from: T, to: T, inserter: (T, PsiTypeParameterList) -> Unit ) where T : PsiTypeParameterListOwner, T : PsiNameIdentifierOwner { val factory = PsiElementFactory.getInstance((from as PsiElement).project) val templateTypeParams = from.typeParameterList?.typeParameters ?: PsiTypeParameter.EMPTY_ARRAY if (templateTypeParams.isNotEmpty()) { inserter(to, factory.createTypeParameterList()) val targetTypeParamList = to.typeParameterList val newTypeParams = templateTypeParams.map { factory.createTypeParameter(it.name!!, it.extendsList.referencedTypes) } ChangeSignatureUtil.synchronizeList( targetTypeParamList, newTypeParams, { it!!.typeParameters.toList() }, BooleanArray(newTypeParams.size) ) } } fun createJavaMethod(function: KtFunction, targetClass: PsiClass): PsiMethod { val template = LightClassUtil.getLightClassMethod(function) ?: throw AssertionError("Can't generate light method: ${function.getElementTextWithContext()}") return createJavaMethod(template, targetClass) } fun createJavaMethod(template: PsiMethod, targetClass: PsiClass): PsiMethod { val factory = PsiElementFactory.getInstance(template.project) val methodToAdd = if (template.isConstructor) { factory.createConstructor(template.name) } else { factory.createMethod(template.name, template.returnType) } val method = targetClass.add(methodToAdd) as PsiMethod copyModifierListItems(template.modifierList, method.modifierList) if (targetClass.isInterface) { method.modifierList.setModifierProperty(PsiModifier.FINAL, false) } copyTypeParameters(template, method) { psiMethod, typeParameterList -> psiMethod.addAfter(typeParameterList, psiMethod.modifierList) } val targetParamList = method.parameterList val newParams = template.parameterList.parameters.map { val param = factory.createParameter(it.name, it.type) copyModifierListItems(it.modifierList!!, param.modifierList!!) param } ChangeSignatureUtil.synchronizeList( targetParamList, newParams, { it.parameters.toList() }, BooleanArray(newParams.size) ) if (template.modifierList.hasModifierProperty(PsiModifier.ABSTRACT) || targetClass.isInterface) { method.body!!.delete() } else if (!template.isConstructor) { CreateFromUsageUtils.setupMethodBody(method) } return method } fun createJavaField(property: KtNamedDeclaration, targetClass: PsiClass): PsiField { val accessorLightMethods = property.getAccessorLightMethods() val template = accessorLightMethods.getter ?: throw AssertionError("Can't generate light method: ${property.getElementTextWithContext()}") val factory = PsiElementFactory.getInstance(template.project) val field = targetClass.add(factory.createField(property.name!!, template.returnType!!)) as PsiField with(field.modifierList!!) { val templateModifiers = template.modifierList setModifierProperty(VisibilityUtil.getVisibilityModifier(templateModifiers), true) if ((property as KtValVarKeywordOwner).valOrVarKeyword.toValVar() != KotlinValVar.Var || targetClass.isInterface) { setModifierProperty(PsiModifier.FINAL, true) } copyModifierListItems(templateModifiers, this, false) } return field } fun createJavaClass(klass: KtClass, targetClass: PsiClass?, forcePlainClass: Boolean = false): PsiClass { val kind = if (forcePlainClass) ClassKind.CLASS else (klass.unsafeResolveToDescriptor() as ClassDescriptor).kind val factory = PsiElementFactory.getInstance(klass.project) val className = klass.name!! val javaClassToAdd = when (kind) { ClassKind.CLASS -> factory.createClass(className) ClassKind.INTERFACE -> factory.createInterface(className) ClassKind.ANNOTATION_CLASS -> factory.createAnnotationType(className) ClassKind.ENUM_CLASS -> factory.createEnum(className) else -> throw AssertionError("Unexpected class kind: ${klass.getElementTextWithContext()}") } val javaClass = (targetClass?.add(javaClassToAdd) ?: javaClassToAdd) as PsiClass val template = klass.toLightClass() ?: throw AssertionError("Can't generate light class: ${klass.getElementTextWithContext()}") copyModifierListItems(template.modifierList!!, javaClass.modifierList!!) if (template.isInterface) { javaClass.modifierList!!.setModifierProperty(PsiModifier.ABSTRACT, false) } copyTypeParameters(template, javaClass) { clazz, typeParameterList -> clazz.addAfter(typeParameterList, clazz.nameIdentifier) } // Turning interface to class if (!javaClass.isInterface && template.isInterface) { val implementsList = factory.createReferenceListWithRole( template.extendsList?.referenceElements ?: PsiJavaCodeReferenceElement.EMPTY_ARRAY, PsiReferenceList.Role.IMPLEMENTS_LIST ) implementsList?.let { javaClass.implementsList?.replace(it) } } else { val extendsList = factory.createReferenceListWithRole( template.extendsList?.referenceElements ?: PsiJavaCodeReferenceElement.EMPTY_ARRAY, PsiReferenceList.Role.EXTENDS_LIST ) extendsList?.let { javaClass.extendsList?.replace(it) } val implementsList = factory.createReferenceListWithRole( template.implementsList?.referenceElements ?: PsiJavaCodeReferenceElement.EMPTY_ARRAY, PsiReferenceList.Role.IMPLEMENTS_LIST ) implementsList?.let { javaClass.implementsList?.replace(it) } } for (method in template.methods) { val hasParams = method.parameterList.parametersCount > 0 val needSuperCall = !template.isEnum && (template.superClass?.constructors ?: PsiMethod.EMPTY_ARRAY).all { it.parameterList.parametersCount > 0 } if (method.isConstructor && !(hasParams || needSuperCall)) continue with(createJavaMethod(method, javaClass)) { if (isConstructor && needSuperCall) { body!!.add(factory.createStatementFromText("super();", this)) } } } return javaClass } internal fun broadcastRefactoringExit(project: Project, refactoringId: String) { project.messageBus.syncPublisher(KotlinRefactoringEventListener.EVENT_TOPIC).onRefactoringExit(refactoringId) } // IMPORTANT: Target refactoring must support KotlinRefactoringEventListener internal abstract class CompositeRefactoringRunner( val project: Project, val refactoringId: String ) { protected abstract fun runRefactoring() protected open fun onRefactoringDone() {} protected open fun onExit() {} fun run() { val connection = project.messageBus.connect() connection.subscribe( RefactoringEventListener.REFACTORING_EVENT_TOPIC, object : RefactoringEventListener { override fun undoRefactoring(refactoringId: String) { } override fun refactoringStarted(refactoringId: String, beforeData: RefactoringEventData?) { } override fun conflictsDetected(refactoringId: String, conflictsData: RefactoringEventData) { } override fun refactoringDone(refactoringId: String, afterData: RefactoringEventData?) { if (refactoringId == [email protected]) { onRefactoringDone() } } } ) connection.subscribe( KotlinRefactoringEventListener.EVENT_TOPIC, object : KotlinRefactoringEventListener { override fun onRefactoringExit(refactoringId: String) { if (refactoringId == [email protected]) { try { onExit() } finally { connection.disconnect() } } } } ) runRefactoring() } } @Throws(ConfigurationException::class) fun KtElement?.validateElement(@NlsContexts.DialogMessage errorMessage: String) { if (this == null) throw ConfigurationException(errorMessage) try { AnalyzingUtils.checkForSyntacticErrors(this) } catch (e: Exception) { throw ConfigurationException(errorMessage) } } fun invokeOnceOnCommandFinish(action: () -> Unit) { val simpleConnect = ApplicationManager.getApplication().messageBus.simpleConnect() simpleConnect.subscribe(CommandListener.TOPIC, object : CommandListener { override fun beforeCommandFinished(event: CommandEvent) { action() simpleConnect.disconnect() } }) } fun FqNameUnsafe.hasIdentifiersOnly(): Boolean = pathSegments().all { it.asString().quoteIfNeeded().isIdentifier() } fun FqName.hasIdentifiersOnly(): Boolean = pathSegments().all { it.asString().quoteIfNeeded().isIdentifier() } fun PsiNamedElement.isInterfaceClass(): Boolean = when (this) { is KtClass -> isInterface() is PsiClass -> isInterface is KtPsiClassWrapper -> psiClass.isInterface else -> false } fun KtNamedDeclaration.isAbstract(): Boolean = when { hasModifier(KtTokens.ABSTRACT_KEYWORD) -> true containingClassOrObject?.isInterfaceClass() != true -> false this is KtProperty -> initializer == null && delegate == null && accessors.isEmpty() this is KtNamedFunction -> !hasBody() else -> false } fun KtNamedDeclaration.isConstructorDeclaredProperty() = this is KtParameter && ownerFunction is KtPrimaryConstructor && hasValOrVar() fun <ListType : KtElement> replaceListPsiAndKeepDelimiters( changeInfo: KotlinChangeInfo, originalList: ListType, newList: ListType, @Suppress("UNCHECKED_CAST") listReplacer: ListType.(ListType) -> ListType = { replace(it) as ListType }, itemsFun: ListType.() -> List<KtElement> ): ListType { originalList.children.takeWhile { it is PsiErrorElement }.forEach { it.delete() } val oldParameters = originalList.itemsFun().toMutableList() val newParameters = newList.itemsFun() val oldCount = oldParameters.size val newCount = newParameters.size val commonCount = min(oldCount, newCount) val originalIndexes = changeInfo.newParameters.map { it.originalIndex } val keepComments = originalList.allChildren.any { it is PsiComment } && oldCount > commonCount && originalIndexes == originalIndexes.sorted() if (!keepComments) { for (i in 0 until commonCount) { oldParameters[i] = oldParameters[i].replace(newParameters[i]) as KtElement } } if (commonCount == 0) return originalList.listReplacer(newList) val lastOriginalParameter = oldParameters.last() if (oldCount > commonCount) { if (keepComments) { ((0 until oldParameters.size) - originalIndexes).forEach { index -> val oldParameter = oldParameters[index] val nextComma = oldParameter.getNextSiblingIgnoringWhitespaceAndComments()?.takeIf { it.node.elementType == KtTokens.COMMA } if (nextComma != null) { nextComma.delete() } else { oldParameter.getPrevSiblingIgnoringWhitespaceAndComments()?.takeIf { it.node.elementType == KtTokens.COMMA }?.delete() } oldParameter.delete() } } else { originalList.deleteChildRange(oldParameters[commonCount - 1].nextSibling, lastOriginalParameter) } } else if (newCount > commonCount) { val psiBeforeLastParameter = lastOriginalParameter.prevSibling val withMultiline = (psiBeforeLastParameter is PsiWhiteSpace || psiBeforeLastParameter is PsiComment) && psiBeforeLastParameter.textContains('\n') val extraSpace = if (withMultiline) KtPsiFactory(originalList).createNewLine() else null originalList.addRangeAfter(newParameters[commonCount - 1].nextSibling, newParameters.last(), lastOriginalParameter) if (extraSpace != null) { val addedItems = originalList.itemsFun().subList(commonCount, newCount) for (addedItem in addedItems) { val elementBefore = addedItem.prevSibling if ((elementBefore !is PsiWhiteSpace && elementBefore !is PsiComment) || !elementBefore.textContains('\n')) { addedItem.parent.addBefore(extraSpace, addedItem) } } } } return originalList } fun <T> Pass(body: (T) -> Unit) = object : Pass<T>() { override fun pass(t: T) = body(t) } fun KtExpression.removeTemplateEntryBracesIfPossible(): KtExpression { val parent = parent as? KtBlockStringTemplateEntry ?: return this val newEntry = if (parent.canDropBraces()) parent.dropBraces() else parent return newEntry.expression!! } fun dropOverrideKeywordIfNecessary(element: KtNamedDeclaration) { val callableDescriptor = element.resolveToDescriptorIfAny() as? CallableDescriptor ?: return if (callableDescriptor.overriddenDescriptors.isEmpty()) { element.removeModifier(KtTokens.OVERRIDE_KEYWORD) } } fun dropOperatorKeywordIfNecessary(element: KtNamedDeclaration) { val callableDescriptor = element.resolveToDescriptorIfAny() as? CallableDescriptor ?: return val diagnosticHolder = BindingTraceContext() OperatorModifierChecker.check(element, callableDescriptor, diagnosticHolder, element.languageVersionSettings) if (diagnosticHolder.bindingContext.diagnostics.any { it.factory == Errors.INAPPLICABLE_OPERATOR_MODIFIER }) { element.removeModifier(KtTokens.OPERATOR_KEYWORD) } } fun getQualifiedTypeArgumentList(initializer: KtExpression): KtTypeArgumentList? { val call = initializer.resolveToCall() ?: return null val typeArgumentMap = call.typeArguments val typeArguments = call.candidateDescriptor.typeParameters.mapNotNull { typeArgumentMap[it] } val renderedList = typeArguments.joinToString(prefix = "<", postfix = ">") { IdeDescriptorRenderers.SOURCE_CODE_NOT_NULL_TYPE_APPROXIMATION.renderType(it.unCapture()) } return KtPsiFactory(initializer).createTypeArguments(renderedList) } fun addTypeArgumentsIfNeeded(expression: KtExpression, typeArgumentList: KtTypeArgumentList) { val context = expression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) val call = expression.getCallWithAssert(context) val callElement = call.callElement as? KtCallExpression ?: return if (call.typeArgumentList != null) return val callee = call.calleeExpression ?: return if (context.diagnostics.forElement(callee).all { it.factory != Errors.TYPE_INFERENCE_NO_INFORMATION_FOR_PARAMETER && it.factory != Errors.NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER } ) { return } callElement.addAfter(typeArgumentList, callElement.calleeExpression) ShortenReferences.DEFAULT.process(callElement.typeArgumentList!!) } internal fun DeclarationDescriptor.getThisLabelName(): String { if (!name.isSpecial) return name.asString() if (this is AnonymousFunctionDescriptor) { val function = source.getPsi() as? KtFunction val argument = function?.parent as? KtValueArgument ?: (function?.parent as? KtLambdaExpression)?.parent as? KtValueArgument val callElement = argument?.getStrictParentOfType<KtCallElement>() val callee = callElement?.calleeExpression as? KtSimpleNameExpression if (callee != null) return callee.text } return "" } internal fun DeclarationDescriptor.explicateAsTextForReceiver(): String { val labelName = getThisLabelName() return if (labelName.isEmpty()) "this" else "this@$labelName" } internal fun ImplicitReceiver.explicateAsText(): String { return declarationDescriptor.explicateAsTextForReceiver() } val PsiFile.isInjectedFragment: Boolean get() = InjectedLanguageManager.getInstance(project).isInjectedFragment(this) val PsiElement.isInsideInjectedFragment: Boolean get() = containingFile.isInjectedFragment fun checkSuperMethods( declaration: KtDeclaration, ignore: Collection<PsiElement>?, @Nls actionString: String ): List<PsiElement> { if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return listOf(declaration) val (declarationDescriptor, overriddenElementsToDescriptor) = getSuperDescriptors(declaration, ignore) if (overriddenElementsToDescriptor.isEmpty()) return listOf(declaration) fun getClassDescriptions(overriddenElementsToDescriptor: Map<PsiElement, CallableDescriptor>): List<String> { return overriddenElementsToDescriptor.entries.map { entry -> val (element, descriptor) = entry val description = when (element) { is KtNamedFunction, is KtProperty, is KtParameter -> formatClassDescriptor(descriptor.containingDeclaration) is PsiMethod -> { val psiClass = element.containingClass ?: error("Invalid element: ${element.getText()}") formatPsiClass(psiClass, markAsJava = true, inCode = false) } else -> error("Unexpected element: ${element.getElementTextWithContext()}") } " $description\n" } } fun askUserForMethodsToSearch( declarationDescriptor: CallableDescriptor, overriddenElementsToDescriptor: Map<PsiElement, CallableDescriptor> ): List<PsiElement> { val superClassDescriptions = getClassDescriptions(overriddenElementsToDescriptor) val message = KotlinBundle.message( "override.declaration.x.overrides.y.in.class.list", DescriptorRenderer.COMPACT_WITH_SHORT_TYPES.render(declarationDescriptor), "\n${superClassDescriptions.joinToString(separator = "")}", actionString ) val exitCode = showYesNoCancelDialog( CHECK_SUPER_METHODS_YES_NO_DIALOG, declaration.project, message, IdeBundle.message("title.warning"), Messages.getQuestionIcon(), Messages.YES ) return when (exitCode) { Messages.YES -> overriddenElementsToDescriptor.keys.toList() Messages.NO -> listOf(declaration) else -> emptyList() } } return askUserForMethodsToSearch(declarationDescriptor, overriddenElementsToDescriptor) } private fun getSuperDescriptors(declaration: KtDeclaration, ignore: Collection<PsiElement>?) = underModalProgress( declaration.project, KotlinBundle.message("find.usages.progress.text.declaration.superMethods") ) { val declarationDescriptor = declaration.unsafeResolveToDescriptor() as CallableDescriptor if (declarationDescriptor is LocalVariableDescriptor) return@underModalProgress (declarationDescriptor to emptyMap<PsiElement, CallableDescriptor>()) val overriddenElementsToDescriptor = HashMap<PsiElement, CallableDescriptor>() for (overriddenDescriptor in DescriptorUtils.getAllOverriddenDescriptors( declarationDescriptor )) { val overriddenDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration( declaration.project, overriddenDescriptor ) ?: continue if (overriddenDeclaration is KtNamedFunction || overriddenDeclaration is KtProperty || overriddenDeclaration is PsiMethod || overriddenDeclaration is KtParameter) { overriddenElementsToDescriptor[overriddenDeclaration] = overriddenDescriptor } } if (ignore != null) { overriddenElementsToDescriptor.keys.removeAll(ignore) } (declarationDescriptor to overriddenElementsToDescriptor) } fun getSuperMethods(declaration: KtDeclaration, ignore: Collection<PsiElement>?): List<PsiElement> { if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return listOf(declaration) val (_, overriddenElementsToDescriptor) = getSuperDescriptors(declaration, ignore) return if (overriddenElementsToDescriptor.isEmpty()) listOf(declaration) else overriddenElementsToDescriptor.keys.toList() } fun checkSuperMethodsWithPopup( declaration: KtNamedDeclaration, deepestSuperMethods: List<PsiElement>, actionStringPrefixKey: String, editor: Editor, action: (List<PsiElement>) -> Unit ) { if (deepestSuperMethods.isEmpty()) return action(listOf(declaration)) val superMethod = deepestSuperMethods.first() val (superClass, isAbstract) = when (superMethod) { is PsiMember -> superMethod.containingClass to superMethod.hasModifierProperty(PsiModifier.ABSTRACT) is KtNamedDeclaration -> superMethod.containingClassOrObject to superMethod.isAbstract() else -> null } ?: return action(listOf(declaration)) if (superClass == null) return action(listOf(declaration)) if (isUnitTestMode()) return action(deepestSuperMethods) val kindIndex = when (declaration) { is KtNamedFunction -> 1 // "function" is KtProperty, is KtParameter -> 2 // "property" else -> return } val unwrappedSupers = deepestSuperMethods.mapNotNull { it.namedUnwrappedElement } val hasJavaMethods = unwrappedSupers.any { it is PsiMethod } val hasKtMembers = unwrappedSupers.any { it is KtNamedDeclaration } val superKindIndex = when { hasJavaMethods && hasKtMembers -> 3 // "member" hasJavaMethods -> 4 // "method" else -> kindIndex } val renameBase = KotlinBundle.message("$actionStringPrefixKey.base.0", superKindIndex + (if (deepestSuperMethods.size > 1) 10 else 0)) val renameCurrent = KotlinBundle.message("$actionStringPrefixKey.only.current.0", kindIndex) val title = KotlinBundle.message( "$actionStringPrefixKey.declaration.title.0.implements.1.2.of.3", declaration.name ?: "", if (isAbstract) 1 else 2, ElementDescriptionUtil.getElementDescription(superMethod, UsageViewTypeLocation.INSTANCE), SymbolPresentationUtil.getSymbolPresentableText(superClass) ) JBPopupFactory.getInstance() .createPopupChooserBuilder(listOf(renameBase, renameCurrent)) .setTitle(title) .setMovable(false) .setResizable(false) .setRequestFocus(true) .setItemChosenCallback { value: String? -> if (value == null) return@setItemChosenCallback val chosenElements = if (value == renameBase) deepestSuperMethods + declaration else listOf(declaration) action(chosenElements) } .createPopup() .showInBestPositionFor(editor) } fun KtNamedDeclaration.isCompanionMemberOf(klass: KtClassOrObject): Boolean { val containingObject = containingClassOrObject as? KtObjectDeclaration ?: return false return containingObject.isCompanion() && containingObject.containingClassOrObject == klass } internal fun KtDeclaration.withExpectedActuals(): List<KtDeclaration> { val expect = liftToExpected() ?: return listOf(this) val actuals = expect.actualsForExpected() return listOf(expect) + actuals } internal fun KtDeclaration.resolveToExpectedDescriptorIfPossible(): DeclarationDescriptor { val descriptor = unsafeResolveToDescriptor() return descriptor.liftToExpected() ?: descriptor } fun DialogWrapper.showWithTransaction() { TransactionGuard.submitTransaction(disposable, Runnable { show() }) } fun PsiMethod.checkDeclarationConflict(name: String, conflicts: MultiMap<PsiElement, String>, callables: Collection<PsiElement>) { containingClass ?.findMethodsByName(name, true) // as is necessary here: see KT-10386 ?.firstOrNull { it.parameterList.parametersCount == 0 && !callables.contains(it.namedUnwrappedElement as PsiElement?) } ?.let { reportDeclarationConflict(conflicts, it) { s -> "$s already exists" } } } fun <T : KtExpression> T.replaceWithCopyWithResolveCheck( resolveStrategy: (T, BindingContext) -> DeclarationDescriptor?, context: BindingContext = analyze(), preHook: T.() -> Unit = {}, postHook: T.() -> T? = { this } ): T? { val originDescriptor = resolveStrategy(this, context) ?: return null @Suppress("UNCHECKED_CAST") val elementCopy = copy() as T elementCopy.preHook() val newContext = elementCopy.analyzeAsReplacement(this, context) val newDescriptor = resolveStrategy(elementCopy, newContext) ?: return null return if (originDescriptor.canonicalRender() == newDescriptor.canonicalRender()) elementCopy.postHook() else null } @Deprecated( "Use org.jetbrains.kotlin.idea.core.util.getLineCount() instead", ReplaceWith("this.getLineCount()", "org.jetbrains.kotlin.idea.core.util.getLineCount"), DeprecationLevel.ERROR ) fun PsiElement.getLineCount(): Int { return newGetLineCount() } @Deprecated( "Use org.jetbrains.kotlin.idea.core.util.toPsiDirectory() instead", ReplaceWith("this.toPsiDirectory(project)", "org.jetbrains.kotlin.idea.core.util.toPsiDirectory"), DeprecationLevel.ERROR ) fun VirtualFile.toPsiDirectory(project: Project): PsiDirectory? { return newToPsiDirectory(project) } @Deprecated( "Use org.jetbrains.kotlin.idea.core.util.toPsiFile() instead", ReplaceWith("this.toPsiFile(project)", "org.jetbrains.kotlin.idea.core.util.toPsiFile"), DeprecationLevel.ERROR ) fun VirtualFile.toPsiFile(project: Project): PsiFile? { return newToPsiFile(project) }
apache-2.0
0f865ee0ed23f89544bf116f9ba239cc
39.537248
172
0.712337
5.040541
false
false
false
false